diff --git a/.gitignore b/.gitignore index b5157e17..90bf0a44 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ installer installer.tar dist .idea/* +node_modules/* \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..b0f8227f --- /dev/null +++ b/.prettierignore @@ -0,0 +1,9 @@ +*.min.* +*.py +*.json +*.html +/* +!/ui +/ui/easydiffusion +!/ui/plugins +!/ui/media \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..a42b3fd7 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,7 @@ +{ + "printWidth": 120, + "tabWidth": 4, + "semi": false, + "arrowParens": "always", + "trailingComma": "es5" +} diff --git a/CHANGES.md b/CHANGES.md index 4b225b32..b13083dc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,18 +2,19 @@ ## v2.5 ### Major Changes -- **Nearly twice as fast** - significantly faster speed of image generation. We're now pretty close to automatic1111's speed. Code contributions are welcome to make our project even faster: https://github.com/easydiffusion/sdkit/#is-it-fast +- **Nearly twice as fast** - significantly faster speed of image generation. Code contributions are welcome to make our project even faster: https://github.com/easydiffusion/sdkit/#is-it-fast - **Mac M1/M2 support** - Experimental support for Mac M1/M2. Thanks @michaelgallacher, @JeLuf and vishae. +- **AMD support for Linux** - Experimental support for AMD GPUs on Linux. Thanks @DianaNites and @JeLuf. - **Full support for Stable Diffusion 2.1 (including CPU)** - supports loading v1.4 or v2.0 or v2.1 models seamlessly. No need to enable "Test SD2", and no need to add `sd2_` to your SD 2.0 model file names. Works on CPU as well. - **Memory optimized Stable Diffusion 2.1** - you can now use Stable Diffusion 2.1 models, with the same low VRAM optimizations that we've always had for SD 1.4. Please note, the SD 2.0 and 2.1 models require more GPU and System RAM, as compared to the SD 1.4 and 1.5 models. - **11 new samplers!** - explore the new samplers, some of which can generate great images in less than 10 inference steps! We've added the Karras and UniPC samplers. Thanks @Schorny for the UniPC samplers. -- **Model Merging** - You can now merge two models (`.ckpt` or `.safetensors`) and output `.ckpt` or `.safetensors` models, optionally in `fp16` precision. Details: https://github.com/cmdr2/stable-diffusion-ui/wiki/Model-Merging . Thanks @JeLuf. +- **Model Merging** - You can now merge two models (`.ckpt` or `.safetensors`) and output `.ckpt` or `.safetensors` models, optionally in `fp16` precision. Details: https://github.com/easydiffusion/easydiffusion/wiki/Model-Merging . Thanks @JeLuf. - **Fast loading/unloading of VAEs** - No longer needs to reload the entire Stable Diffusion model, each time you change the VAE - **Database of known models** - automatically picks the right configuration for known models. E.g. we automatically detect and apply "v" parameterization (required for some SD 2.0 models), and "fp32" attention precision (required for some SD 2.1 models). - **Color correction for img2img** - an option to preserve the color profile (histogram) of the initial image. This is especially useful if you're getting red-tinted images after inpainting/masking. - **Three GPU Memory Usage Settings** - `High` (fastest, maximum VRAM usage), `Balanced` (default - almost as fast, significantly lower VRAM usage), `Low` (slowest, very low VRAM usage). The `Low` setting is applied automatically for GPUs with less than 4 GB of VRAM. - **Find models in sub-folders** - This allows you to organize your models into sub-folders inside `models/stable-diffusion`, instead of keeping them all in a single folder. Thanks @patriceac and @ogmaresca. -- **Custom Modifier Categories** - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). Details: https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Modifiers . Thanks @ogmaresca. +- **Custom Modifier Categories** - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). Details: https://github.com/easydiffusion/easydiffusion/wiki/Custom-Modifiers . Thanks @ogmaresca. - **Embed metadata, or save as TXT/JSON** - You can now embed the metadata directly into the images, or save them as text or json files (choose in the Settings tab). Thanks @patriceac. - **Major rewrite of the code** - Most of the codebase has been reorganized and rewritten, to make it more manageable and easier for new developers to contribute features. We've separated our core engine into a new project called `sdkit`, which allows anyone to easily integrate Stable Diffusion (and related modules like GFPGAN etc) into their programming projects (via a simple `pip install sdkit`): https://github.com/easydiffusion/sdkit/ - **Name change** - Last, and probably the least, the UI is now called "Easy Diffusion". It indicates the focus of this project - an easy way for people to play with Stable Diffusion. @@ -21,14 +22,49 @@ Our focus continues to remain on an easy installation experience, and an easy user-interface. While still remaining pretty powerful, in terms of features and speed. ### Detailed changelog +* 2.5.41 - 24 Jun 2023 - (beta-only) Fix broken inpainting in low VRAM usage mode. +* 2.5.41 - 24 Jun 2023 - (beta-only) Fix a recent regression where the LoRA would not get applied when changing SD models. +* 2.5.41 - 23 Jun 2023 - Fix a regression where latent upscaler stopped working on PCs without a graphics card. +* 2.5.41 - 20 Jun 2023 - Automatically fix black images if fp32 attention precision is required in diffusers. +* 2.5.41 - 19 Jun 2023 - Another fix for multi-gpu rendering (in all VRAM usage modes). +* 2.5.41 - 13 Jun 2023 - Fix multi-gpu bug with "low" VRAM usage mode while generating images. +* 2.5.41 - 12 Jun 2023 - Fix multi-gpu bug with CodeFormer. +* 2.5.41 - 6 Jun 2023 - Allow changing the strength of CodeFormer, and slightly improved styling of the CodeFormer options. +* 2.5.41 - 5 Jun 2023 - Allow sharing an Easy Diffusion instance via https://try.cloudflare.com/ . You can find this option at the bottom of the Settings tab. Thanks @JeLuf. +* 2.5.41 - 5 Jun 2023 - Show an option to download for tiled images. Shows a button on the generated image. Creates larger images by tiling them with the image generated by Easy Diffusion. Thanks @JeLuf. +* 2.5.41 - 5 Jun 2023 - (beta-only) Allow LoRA strengths between -2 and 2. Thanks @ogmaresca. +* 2.5.40 - 5 Jun 2023 - Reduce the VRAM usage of Latent Upscaling when using "balanced" VRAM usage mode. +* 2.5.40 - 5 Jun 2023 - Fix the "realesrgan" key error when using CodeFormer with more than 1 image in a batch. +* 2.5.40 - 3 Jun 2023 - Added CodeFormer as another option for fixing faces and eyes. CodeFormer tends to perform better than GFPGAN for many images. Thanks @patriceac for the implementation, and for contacting the CodeFormer team (who were supportive of it being integrated into Easy Diffusion). +* 2.5.39 - 25 May 2023 - (beta-only) Seamless Tiling - make seamlessly tiled images, e.g. rock and grass textures. Thanks @JeLuf. +* 2.5.38 - 24 May 2023 - Better reporting of errors, and show an explanation if the user cannot disable the "Use CPU" setting. +* 2.5.38 - 23 May 2023 - Add Latent Upscaler as another option for upscaling images. Thanks @JeLuf for the implementation of the Latent Upscaler model. +* 2.5.37 - 19 May 2023 - (beta-only) Two more samplers: DDPM and DEIS. Also disables the samplers that aren't working yet in the Diffusers version. Thanks @ogmaresca. +* 2.5.37 - 19 May 2023 - (beta-only) Support CLIP-Skip. You can set this option under the models dropdown. Thanks @JeLuf. +* 2.5.37 - 19 May 2023 - (beta-only) More VRAM optimizations for all modes in diffusers. The VRAM usage for diffusers in "low" and "balanced" should now be equal or less than the non-diffusers version. Performs softmax in half precision, like sdkit does. +* 2.5.36 - 16 May 2023 - (beta-only) More VRAM optimizations for "balanced" VRAM usage mode. +* 2.5.36 - 11 May 2023 - (beta-only) More VRAM optimizations for "low" VRAM usage mode. +* 2.5.36 - 10 May 2023 - (beta-only) Bug fix for "meta" error when using a LoRA in 'low' VRAM usage mode. +* 2.5.35 - 8 May 2023 - Allow dragging a zoomed-in image (after opening an image with the "expand" button). Thanks @ogmaresca. +* 2.5.35 - 3 May 2023 - (beta-only) First round of VRAM Optimizations for the "Test Diffusers" version. This change significantly reduces the amount of VRAM used by the diffusers version during image generation. The VRAM usage is still not equal to the "non-diffusers" version, but more optimizations are coming soon. +* 2.5.34 - 22 Apr 2023 - Don't start the browser in an incognito new profile (on Windows). Thanks @JeLuf. +* 2.5.33 - 21 Apr 2023 - Install PyTorch 2.0 on new installations (on Windows and Linux). +* 2.5.32 - 19 Apr 2023 - Automatically check for black images, and set full-precision if necessary (for attn). This means custom models based on Stable Diffusion v2.1 will just work, without needing special command-line arguments or editing of yaml config files. +* 2.5.32 - 18 Apr 2023 - Automatic support for AMD graphics cards on Linux. Thanks @DianaNites and @JeLuf. +* 2.5.31 - 10 Apr 2023 - Reduce VRAM usage while upscaling. +* 2.5.31 - 6 Apr 2023 - Allow seeds upto `4,294,967,295`. Thanks @ogmaresca. +* 2.5.31 - 6 Apr 2023 - Buttons to show the previous/next image in the image popup. Thanks @ogmaresca. +* 2.5.30 - 5 Apr 2023 - Fix a bug where the JPEG image quality wasn't being respected when embedding the metadata into it. Thanks @JeLuf. +* 2.5.30 - 1 Apr 2023 - (beta-only) Slider to control the strength of the LoRA model. +* 2.5.30 - 28 Mar 2023 - Refactor task entry config to use a generating method. Added ability for plugins to easily add to this. Removed confusing sentence from `contributing.md` * 2.5.30 - 28 Mar 2023 - Allow the user to undo the deletion of tasks or images, instead of showing a pop-up each time. The new `Undo` button will be present at the top of the UI. Thanks @JeLuf. * 2.5.30 - 28 Mar 2023 - Support saving lossless WEBP images. Thanks @ogmaresca. * 2.5.30 - 28 Mar 2023 - Lots of bug fixes for the UI (Read LoRA flag in metadata files, new prompt weight format with scrollwheel, fix overflow with lots of tabs, clear button in image editor, shorter filenames in download). Thanks @patriceac, @JeLuf and @ogmaresca. -* 2.5.29 - 27 Mar 2023 - Fix a bug where some non-square images would fail while inpainting with a `The size of tensor a must match size of tensor b` error. -* 2.5.29 - 27 Mar 2023 - Fix the `incorrect number of channels` error, when given a PNG image with an alpha channel in `Test Diffusers`. -* 2.5.29 - 27 Mar 2023 - Fix broken inpainting in `Test Diffusers` (beta). -* 2.5.28 - 24 Mar 2023 - Support for weighted prompts and long prompt lengths (not limited to 77 tokens). This change requires enabling the `Test Diffusers` setting in beta (in the Settings tab), and restarting the program. -* 2.5.27 - 21 Mar 2023 - LoRA support, accessible by enabling the `Test Diffusers` setting (in the Settings tab in the UI). This change switches the internal engine to diffusers (if the `Test Diffusers` setting is enabled). If the `Test Diffusers` flag is disabled, it'll have no impact for the user. +* 2.5.29 - 27 Mar 2023 - (beta-only) Fix a bug where some non-square images would fail while inpainting with a `The size of tensor a must match size of tensor b` error. +* 2.5.29 - 27 Mar 2023 - (beta-only) Fix the `incorrect number of channels` error, when given a PNG image with an alpha channel in `Test Diffusers`. +* 2.5.29 - 27 Mar 2023 - (beta-only) Fix broken inpainting in `Test Diffusers`. +* 2.5.28 - 24 Mar 2023 - (beta-only) Support for weighted prompts and long prompt lengths (not limited to 77 tokens). This change requires enabling the `Test Diffusers` setting in beta (in the Settings tab), and restarting the program. +* 2.5.27 - 21 Mar 2023 - (beta-only) LoRA support, accessible by enabling the `Test Diffusers` setting (in the Settings tab in the UI). This change switches the internal engine to diffusers (if the `Test Diffusers` setting is enabled). If the `Test Diffusers` flag is disabled, it'll have no impact for the user. * 2.5.26 - 15 Mar 2023 - Allow styling the buttons displayed on an image. Update the API to allow multiple buttons and text labels in a single row. Thanks @ogmaresca. * 2.5.26 - 15 Mar 2023 - View images in full-screen, by either clicking on the image, or clicking the "Full screen" icon next to the Seed number on the image. Thanks @ogmaresca for the internal API. * 2.5.25 - 14 Mar 2023 - Button to download all the images, and all the metadata as a zip file. This is available at the top of the UI, as well as on each image. Thanks @JeLuf. @@ -36,7 +72,7 @@ Our focus continues to remain on an easy installation experience, and an easy us * 2.5.24 - 11 Mar 2023 - Button to load an image mask from a file. * 2.5.24 - 10 Mar 2023 - Logo change. Image credit: @lazlo_vii. * 2.5.23 - 8 Mar 2023 - Experimental support for Mac M1/M2. Thanks @michaelgallacher, @JeLuf and vishae! -* 2.5.23 - 8 Mar 2023 - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). More details - https://github.com/cmdr2/stable-diffusion-ui/wiki/Custom-Modifiers . Thanks @ogmaresca. +* 2.5.23 - 8 Mar 2023 - Ability to create custom modifiers with thumbnails, and custom categories (and hierarchy of categories). More details - https://github.com/easydiffusion/easydiffusion/wiki/Custom-Modifiers . Thanks @ogmaresca. * 2.5.22 - 28 Feb 2023 - Minor styling changes to UI buttons, and the models dropdown. * 2.5.22 - 28 Feb 2023 - Lots of UI-related bug fixes. Thanks @patriceac. * 2.5.21 - 22 Feb 2023 - An option to control the size of the image thumbnails. You can use the `Display options` in the top-right corner to change this. Thanks @JeLuf. @@ -61,7 +97,7 @@ Our focus continues to remain on an easy installation experience, and an easy us * 2.5.14 - 3 Feb 2023 - Fix the 'Make Similar Images' button, which was producing incorrect images (weren't very similar). * 2.5.13 - 1 Feb 2023 - Fix the remaining GPU memory leaks, including a better fix (more comprehensive) for the change in 2.5.12 (27 Jan). * 2.5.12 - 27 Jan 2023 - Fix a memory leak, which made the UI unresponsive after an out-of-memory error. The allocated memory is now freed-up after an error. -* 2.5.11 - 25 Jan 2023 - UI for Merging Models. Thanks @JeLuf. More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/Model-Merging +* 2.5.11 - 25 Jan 2023 - UI for Merging Models. Thanks @JeLuf. More info: https://github.com/easydiffusion/easydiffusion/wiki/Model-Merging * 2.5.10 - 24 Jan 2023 - Reduce the VRAM usage for img2img in 'balanced' mode (without reducing the rendering speed), to make it similar to v2.4 of this UI. * 2.5.9 - 23 Jan 2023 - Fix a bug where img2img would produce poorer-quality images for the same settings, as compared to version 2.4 of this UI. * 2.5.9 - 23 Jan 2023 - Reduce the VRAM usage for 'balanced' mode (without reducing the rendering speed), to make it similar to v2.4 of the UI. @@ -90,8 +126,8 @@ Our focus continues to remain on an easy installation experience, and an easy us - **Automatic scanning for malicious model files** - using `picklescan`, and support for `safetensor` model format. Thanks @JeLuf - **Image Editor** - for drawing simple images for guiding the AI. Thanks @mdiller - **Use pre-trained hypernetworks** - for improving the quality of images. Thanks @C0bra5 -- **Support for custom VAE models**. You can place your VAE files in the `models/vae` folder, and refresh the browser page to use them. More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/VAE-Variational-Auto-Encoder -- **Experimental support for multiple GPUs!** It should work automatically. Just open one browser tab per GPU, and spread your tasks across your GPUs. For e.g. open our UI in two browser tabs if you have two GPUs. You can customize which GPUs it should use in the "Settings" tab, otherwise let it automatically pick the best GPUs. Thanks @madrang . More info: https://github.com/cmdr2/stable-diffusion-ui/wiki/Run-on-Multiple-GPUs +- **Support for custom VAE models**. You can place your VAE files in the `models/vae` folder, and refresh the browser page to use them. More info: https://github.com/easydiffusion/easydiffusion/wiki/VAE-Variational-Auto-Encoder +- **Experimental support for multiple GPUs!** It should work automatically. Just open one browser tab per GPU, and spread your tasks across your GPUs. For e.g. open our UI in two browser tabs if you have two GPUs. You can customize which GPUs it should use in the "Settings" tab, otherwise let it automatically pick the best GPUs. Thanks @madrang . More info: https://github.com/easydiffusion/easydiffusion/wiki/Run-on-Multiple-GPUs - **Cleaner UI design** - Show settings and help in new tabs, instead of dropdown popups (which were buggy). Thanks @mdiller - **Progress bar.** Thanks @mdiller - **Custom Image Modifiers** - You can now save your custom image modifiers! Your saved modifiers can include special characters like `{}, (), [], |` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 02ce6fc6..bb6408c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ Hi there, these instructions are meant for the developers of this project. -If you only want to use the Stable Diffusion UI, you've downloaded the wrong file. In that case, please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation +If you only want to use the Stable Diffusion UI, you've downloaded the wrong file. In that case, please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation Thanks @@ -13,7 +13,7 @@ If you would like to contribute to this project, there is a discord for discussi This is in-flux, but one way to get a development environment running for editing the UI of this project is: (swap `.sh` or `.bat` in instructions depending on your environment, and be sure to adjust any paths to match where you're working) -1) Install the project to a new location using the [usual installation process](https://github.com/cmdr2/stable-diffusion-ui#installation), e.g. to `/projects/stable-diffusion-ui-archive` +1) Install the project to a new location using the [usual installation process](https://github.com/easydiffusion/easydiffusion#installation), e.g. to `/projects/stable-diffusion-ui-archive` 2) Start the newly installed project, and check that you can view and generate images on `localhost:9000` 3) Next, please clone the project repository using `git clone` (e.g. to `/projects/stable-diffusion-ui-repo`) 4) Close the server (started in step 2), and edit `/projects/stable-diffusion-ui-archive/scripts/on_env_start.sh` (or `on_env_start.bat`) @@ -42,8 +42,6 @@ or for Windows 10) Congrats, now any changes you make in your repo `ui` folder are linked to this running archive of the app and can be previewed in the browser. 11) Please update CHANGES.md in your pull requests. -Check the `ui/frontend/build/README.md` for instructions on running and building the React code. - ## Development environment for Installer changes Build the Windows installer using Windows, and the Linux installer using Linux. Don't mix the two, and don't use WSL. An Ubuntu VM is fine for building the Linux installer on a Windows host. diff --git a/How to install and run.txt b/How to install and run.txt index e48d217c..af783b64 100644 --- a/How to install and run.txt +++ b/How to install and run.txt @@ -1,6 +1,6 @@ Congrats on downloading Stable Diffusion UI, version 2! -If you haven't downloaded Stable Diffusion UI yet, please download from https://github.com/cmdr2/stable-diffusion-ui#installation +If you haven't downloaded Stable Diffusion UI yet, please download from https://github.com/easydiffusion/easydiffusion#installation After downloading, to install please follow these instructions: @@ -16,9 +16,9 @@ To start the UI in the future, please run the same command mentioned above. If you have any problems, please: -1. Try the troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting +1. Try the troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting 2. Or, seek help from the community at https://discord.com/invite/u9yhsFmEkB -3. Or, file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues +3. Or, file an issue at https://github.com/easydiffusion/easydiffusion/issues Thanks cmdr2 (and contributors to the project) \ No newline at end of file diff --git a/NSIS/sdui.nsi b/NSIS/sdui.nsi index 0a1a8f9d..aabe6775 100644 --- a/NSIS/sdui.nsi +++ b/NSIS/sdui.nsi @@ -235,7 +235,7 @@ Section "MainSection" SEC01 NScurl::http get "https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt" "$INSTDIR\models\stable-diffusion\sd-v1-4.ckpt" /CANCEL /INSIST /END DetailPrint 'Downloading the GFPGAN model...' - NScurl::http get "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth" "$INSTDIR\models\gfpgan\GFPGANv1.3.pth" /CANCEL /INSIST /END + NScurl::http get "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth" "$INSTDIR\models\gfpgan\GFPGANv1.4.pth" /CANCEL /INSIST /END DetailPrint 'Downloading the RealESRGAN_x4plus model...' NScurl::http get "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth" "$INSTDIR\models\realesrgan\RealESRGAN_x4plus.pth" /CANCEL /INSIST /END diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 00000000..543a167d --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,9 @@ +// placeholder until a more formal and legal-sounding privacy policy document is written. but the information below is true. + +This is a summary of whether Easy Diffusion uses your data or tracks you: +* The short answer is - Easy Diffusion does *not* use your data, and does *not* track you. +* Easy Diffusion does not send your prompts or usage or analytics to anyone. There is no tracking. We don't even know how many people use Easy Diffusion, let alone their prompts. +* Easy Diffusion fetches updates to the code whenever it starts up. It does this by contacting GitHub directly, via SSL (secure connection). Only your computer and GitHub and [this repository](https://github.com/easydiffusion/easydiffusion) are involved, and no third party is involved. Some countries intercepts SSL connections, that's not something we can do much about. GitHub does *not* share statistics (even with me) about how many people fetched code updates. +* Easy Diffusion fetches the models from huggingface.co and github.com, if they don't exist on your PC. For e.g. if the safety checker (NSFW) model doesn't exist, it'll try to download it. +* Easy Diffusion fetches code packages from pypi.org, which is the standard hosting service for all Python projects. That's where packages installed via `pip install` are stored. +* Occasionally, antivirus software are known to *incorrectly* flag and delete some model files, which will result in Easy Diffusion re-downloading `pytorch_model.bin`. This *incorrect deletion* affects other Stable Diffusion UIs as well, like Invoke AI - https://itch.io/post/7509488 diff --git a/README BEFORE YOU RUN THIS.txt b/README BEFORE YOU RUN THIS.txt index e9f81544..a989b835 100644 --- a/README BEFORE YOU RUN THIS.txt +++ b/README BEFORE YOU RUN THIS.txt @@ -3,6 +3,6 @@ Hi there, What you have downloaded is meant for the developers of this project, not for users. If you only want to use the Stable Diffusion UI, you've downloaded the wrong file. -Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation +Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation Thanks \ No newline at end of file diff --git a/README.md b/README.md index 51ba812a..b97c35d1 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Easy Diffusion 2.5 -### The easiest way to install and use [Stable Diffusion](https://github.com/CompVis/stable-diffusion) on your own computer. +### The easiest way to install and use [Stable Diffusion](https://github.com/CompVis/stable-diffusion) on your computer. Does not require technical knowledge, does not require pre-installed software. 1-click install, powerful features, friendly community. -[Installation guide](#installation) | [Troubleshooting guide](https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting) | [![Discord Server](https://img.shields.io/discord/1014774730907209781?label=Discord)](https://discord.com/invite/u9yhsFmEkB) (for support queries, and development discussions) +[Installation guide](#installation) | [Troubleshooting guide](https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting) | [![Discord Server](https://img.shields.io/discord/1014774730907209781?label=Discord)](https://discord.com/invite/u9yhsFmEkB) (for support queries, and development discussions) ![t2i](https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/assets/stable-samples/txt2img/768/merged-0006.png) @@ -11,11 +11,18 @@ Does not require technical knowledge, does not require pre-installed software. 1 Click the download button for your operating system:

- - - + + +

+**Hardware requirements:** +- **Windows:** NVIDIA graphics card (minimum 2 GB RAM), or run on your CPU. +- **Linux:** NVIDIA or AMD graphics card (minimum 2 GB RAM), or run on your CPU. +- **Mac:** M1 or M2, or run on your CPU. +- Minimum 8 GB of system RAM. +- Atleast 25 GB of space on the hard disk. + The installer will take care of whatever is needed. If you face any problems, you can join the friendly [Discord community](https://discord.com/invite/u9yhsFmEkB) and ask for assistance. ## On Windows: @@ -53,7 +60,7 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages. ### Image generation - **Supports**: "*Text to Image*" and "*Image to Image*". -- **19 Samplers**: `ddim`, `plms`, `heun`, `euler`, `euler_a`, `dpm2`, `dpm2_a`, `lms`, `dpm_solver_stability`, `dpmpp_2s_a`, `dpmpp_2m`, `dpmpp_sde`, `dpm_fast`, `dpm_adaptive`, `unipc_snr`, `unipc_tu`, `unipc_tq`, `unipc_snr_2`, `unipc_tu_2`. +- **21 Samplers**: `ddim`, `plms`, `heun`, `euler`, `euler_a`, `dpm2`, `dpm2_a`, `lms`, `dpm_solver_stability`, `dpmpp_2s_a`, `dpmpp_2m`, `dpmpp_sde`, `dpm_fast`, `dpm_adaptive`, `ddpm`, `deis`, `unipc_snr`, `unipc_tu`, `unipc_tq`, `unipc_snr_2`, `unipc_tu_2`. - **In-Painting**: Specify areas of your image to paint into. - **Simple Drawing Tool**: Draw basic images to guide the AI, without needing an external drawing program. - **Face Correction (GFPGAN)** @@ -63,6 +70,7 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages. - **Attention/Emphasis**: () in the prompt increases the model's attention to enclosed words, and [] decreases it. - **Weighted Prompts**: Use weights for specific words in your prompt to change their importance, e.g. `red:2.4 dragon:1.2`. - **Prompt Matrix**: Quickly create multiple variations of your prompt, e.g. `a photograph of an astronaut riding a horse | illustration | cinematic lighting`. +- **Prompt Set**: Quickly create multiple variations of your prompt, e.g. `a photograph of an astronaut on the {moon,earth}` - **1-click Upscale/Face Correction**: Upscale or correct an image after it has been generated. - **Make Similar Images**: Click to generate multiple variations of a generated image. - **NSFW Setting**: A setting in the UI to control *NSFW content*. @@ -75,11 +83,11 @@ Just delete the `EasyDiffusion` folder to uninstall all the downloaded packages. - **Use custom VAE models** - **Use pre-trained Hypernetworks** - **Use custom GFPGAN models** -- **UI Plugins**: Choose from a growing list of [community-generated UI plugins](https://github.com/cmdr2/stable-diffusion-ui/wiki/UI-Plugins), or write your own plugin to add features to the project! +- **UI Plugins**: Choose from a growing list of [community-generated UI plugins](https://github.com/easydiffusion/easydiffusion/wiki/UI-Plugins), or write your own plugin to add features to the project! ### Performance and security - **Fast**: Creates a 512x512 image with euler_a in 5 seconds, on an NVIDIA 3060 12GB. -- **Low Memory Usage**: Create 512x512 images with less than 3 GB of GPU RAM, and 768x768 images with less than 4 GB of GPU RAM! +- **Low Memory Usage**: Create 512x512 images with less than 2 GB of GPU RAM, and 768x768 images with less than 3 GB of GPU RAM! - **Use CPU setting**: If you don't have a compatible graphics card, but still want to run it on your CPU. - **Multi-GPU support**: Automatically spreads your tasks across multiple GPUs (if available), for faster performance! - **Auto scan for malicious models**: Uses picklescan to prevent malicious models. @@ -108,21 +116,13 @@ Useful for judging (and stopping) an image quickly, without waiting for it to fi ![Screenshot of task queue](https://user-images.githubusercontent.com/844287/217043984-0b35f73b-1318-47cb-9eed-a2a91b430490.png) - -# System Requirements -1. Windows 10/11, or Linux. Experimental support for Mac is coming soon. -2. An NVIDIA graphics card, preferably with 4GB or more of VRAM. If you don't have a compatible graphics card, it'll automatically run in the slower "CPU Mode". -3. Minimum 8 GB of RAM and 25GB of disk space. - -You don't need to install or struggle with Python, Anaconda, Docker etc. The installer will take care of whatever is needed. - ---- # How to use? -Please refer to our [guide](https://github.com/cmdr2/stable-diffusion-ui/wiki/How-to-Use) to understand how to use the features in this UI. +Please refer to our [guide](https://github.com/easydiffusion/easydiffusion/wiki/How-to-Use) to understand how to use the features in this UI. # Bugs reports and code contributions welcome -If there are any problems or suggestions, please feel free to ask on the [discord server](https://discord.com/invite/u9yhsFmEkB) or [file an issue](https://github.com/cmdr2/stable-diffusion-ui/issues). +If there are any problems or suggestions, please feel free to ask on the [discord server](https://discord.com/invite/u9yhsFmEkB) or [file an issue](https://github.com/easydiffusion/easydiffusion/issues). We could really use help on these aspects (click to view tasks that need your help): * [User Interface](https://github.com/users/cmdr2/projects/1/views/1) diff --git a/build.bat b/build.bat index b9c6b9ab..2c7890ee 100644 --- a/build.bat +++ b/build.bat @@ -2,7 +2,7 @@ @echo "Hi there, what you are running is meant for the developers of this project, not for users." & echo. @echo "If you only want to use the Stable Diffusion UI, you've downloaded the wrong file." -@echo "Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation" & echo. +@echo "Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation" & echo. @echo "If you are actually a developer of this project, please type Y and press enter" & echo. set /p answer=Are you a developer of this project (Y/N)? diff --git a/build.sh b/build.sh index a7ed152c..dfb8f420 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ printf "Hi there, what you are running is meant for the developers of this project, not for users.\n\n" printf "If you only want to use the Stable Diffusion UI, you've downloaded the wrong file.\n" -printf "Please download and follow the instructions at https://github.com/cmdr2/stable-diffusion-ui#installation\n\n" +printf "Please download and follow the instructions at https://github.com/easydiffusion/easydiffusion#installation \n\n" printf "If you are actually a developer of this project, please type Y and press enter\n\n" read -p "Are you a developer of this project (Y/N) " yn diff --git a/package.json b/package.json new file mode 100644 index 00000000..fbf1dadb --- /dev/null +++ b/package.json @@ -0,0 +1,9 @@ +{ + "scripts": { + "prettier-fix": "npx prettier --write \"./**/*.js\"", + "prettier-check": "npx prettier --check \"./**/*.js\"" + }, + "devDependencies": { + "prettier": "^1.19.1" + } +} diff --git a/scripts/Developer Console.cmd b/scripts/Developer Console.cmd index 921a9dca..0efbda13 100644 --- a/scripts/Developer Console.cmd +++ b/scripts/Developer Console.cmd @@ -2,6 +2,8 @@ echo "Opening Stable Diffusion UI - Developer Console.." & echo. +cd /d %~dp0 + set PATH=C:\Windows\System32;%PATH% @rem set legacy and new installer's PATH, if they exist @@ -21,6 +23,8 @@ call git --version call where conda call conda --version +echo. +echo COMSPEC=%COMSPEC% echo. @rem activate the legacy environment (if present) and set PYTHONPATH diff --git a/scripts/Start Stable Diffusion UI.cmd b/scripts/Start Stable Diffusion UI.cmd index 4f8555ea..9a4a6303 100644 --- a/scripts/Start Stable Diffusion UI.cmd +++ b/scripts/Start Stable Diffusion UI.cmd @@ -36,8 +36,9 @@ call git --version call where conda call conda --version +echo . +echo COMSPEC=%COMSPEC% @rem Download the rest of the installer and UI call scripts\on_env_start.bat - @pause diff --git a/scripts/bootstrap.bat b/scripts/bootstrap.bat index d3cdd19f..8c1069c8 100644 --- a/scripts/bootstrap.bat +++ b/scripts/bootstrap.bat @@ -11,7 +11,7 @@ setlocal enabledelayedexpansion set MAMBA_ROOT_PREFIX=%cd%\installer_files\mamba set INSTALL_ENV_DIR=%cd%\installer_files\env set LEGACY_INSTALL_ENV_DIR=%cd%\installer -set MICROMAMBA_DOWNLOAD_URL=https://github.com/cmdr2/stable-diffusion-ui/releases/download/v1.1/micromamba.exe +set MICROMAMBA_DOWNLOAD_URL=https://github.com/easydiffusion/easydiffusion/releases/download/v1.1/micromamba.exe set umamba_exists=F set OLD_APPDATA=%APPDATA% diff --git a/scripts/check_modules.py b/scripts/check_modules.py index 416ad851..4634adb3 100644 --- a/scripts/check_modules.py +++ b/scripts/check_modules.py @@ -1,13 +1,161 @@ -''' -This script checks if the given modules exist -''' +""" +This script checks and installs the required modules. -import sys -import pkgutil +This script runs inside the legacy "stable-diffusion" folder -modules = sys.argv[1:] -missing_modules = [] -for m in modules: - if pkgutil.find_loader(m) is None: - print('module', m, 'not found') - exit(1) +TODO - Maybe replace the bulk of this script with a call to `pip install -f requirements.txt`, with +a custom index URL depending on the platform. + +""" + +import os +from importlib.metadata import version as pkg_version +import platform +import traceback + +os_name = platform.system() + +modules_to_check = { + "torch": ("1.11.0", "1.13.1", "2.0.0"), + "torchvision": ("0.12.0", "0.14.1", "0.15.1"), + "sdkit": "1.0.112", + "stable-diffusion-sdkit": "2.1.4", + "rich": "12.6.0", + "uvicorn": "0.19.0", + "fastapi": "0.85.1", + "pycloudflared": "0.2.0", + # "xformers": "0.0.16", +} +modules_to_log = ["torch", "torchvision", "sdkit", "stable-diffusion-sdkit"] + + +def version(module_name: str) -> str: + try: + return pkg_version(module_name) + except: + return None + + +def install(module_name: str, module_version: str): + if module_name == "xformers" and (os_name == "Darwin" or is_amd_on_linux()): + return + + index_url = None + if module_name in ("torch", "torchvision"): + module_version, index_url = apply_torch_install_overrides(module_version) + + if is_amd_on_linux(): # hack until AMD works properly on torch 2.0 (avoids black images on some cards) + if module_name == "torch": + module_version = "1.13.1+rocm5.2" + elif module_name == "torchvision": + module_version = "0.14.1+rocm5.2" + elif os_name == "Darwin": + if module_name == "torch": + module_version = "1.13.1" + elif module_name == "torchvision": + module_version = "0.14.1" + + install_cmd = f"python -m pip install --upgrade {module_name}=={module_version}" + if index_url: + install_cmd += f" --index-url {index_url}" + if module_name == "sdkit" and version("sdkit") is not None: + install_cmd += " -q" + + print(">", install_cmd) + os.system(install_cmd) + + +def init(): + for module_name, allowed_versions in modules_to_check.items(): + if os.path.exists(f"../src/{module_name}"): + print(f"Skipping {module_name} update, since it's in developer/editable mode") + continue + + allowed_versions, latest_version = get_allowed_versions(module_name, allowed_versions) + + requires_install = False + if module_name in ("torch", "torchvision"): + if version(module_name) is None: # allow any torch version + requires_install = True + elif os_name == "Darwin" and ( # force mac to downgrade from torch 2.0 + version("torch").startswith("2.") or version("torchvision").startswith("0.15.") + ): + requires_install = True + elif version(module_name) not in allowed_versions: + requires_install = True + + if requires_install: + try: + install(module_name, latest_version) + except: + traceback.print_exc() + fail(module_name) + + if module_name in modules_to_log: + print(f"{module_name}: {version(module_name)}") + + +### utilities + + +def get_allowed_versions(module_name: str, allowed_versions: tuple): + allowed_versions = (allowed_versions,) if isinstance(allowed_versions, str) else allowed_versions + latest_version = allowed_versions[-1] + + if module_name in ("torch", "torchvision"): + allowed_versions = include_cuda_versions(allowed_versions) + + return allowed_versions, latest_version + + +def apply_torch_install_overrides(module_version: str): + index_url = None + if os_name == "Windows": + module_version += "+cu117" + index_url = "https://download.pytorch.org/whl/cu117" + elif is_amd_on_linux(): + index_url = "https://download.pytorch.org/whl/rocm5.2" + + return module_version, index_url + + +def include_cuda_versions(module_versions: tuple) -> tuple: + "Adds CUDA-specific versions to the list of allowed version numbers" + + allowed_versions = tuple(module_versions) + allowed_versions += tuple(f"{v}+cu116" for v in module_versions) + allowed_versions += tuple(f"{v}+cu117" for v in module_versions) + allowed_versions += tuple(f"{v}+rocm5.2" for v in module_versions) + allowed_versions += tuple(f"{v}+rocm5.4.2" for v in module_versions) + + return allowed_versions + + +def is_amd_on_linux(): + if os_name == "Linux": + try: + with open("/proc/bus/pci/devices", "r") as f: + device_info = f.read() + if "amdgpu" in device_info and "nvidia" not in device_info: + return True + except: + return False + + return False + + +def fail(module_name): + print( + f"""Error installing {module_name}. Sorry about that, please try to: +1. Run this installer again. +2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting +3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB +4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues +Thanks!""" + ) + exit(1) + + +### start + +init() diff --git a/scripts/developer_console.sh b/scripts/developer_console.sh index 73972568..57846eeb 100755 --- a/scripts/developer_console.sh +++ b/scripts/developer_console.sh @@ -39,6 +39,8 @@ if [ "$0" == "bash" ]; then export PYTHONPATH="$(pwd)/stable-diffusion/env/lib/python3.8/site-packages" fi + export PYTHONNOUSERSITE=y + which python python --version diff --git a/scripts/functions.sh b/scripts/functions.sh index 5b1be7f4..477b7743 100644 --- a/scripts/functions.sh +++ b/scripts/functions.sh @@ -15,9 +15,9 @@ fail() { Error downloading Stable Diffusion UI. Sorry about that, please try to: 1. Run this installer again. - 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting + 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB - 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues + 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues Thanks! @@ -31,7 +31,7 @@ EOF filesize() { case "$(uname -s)" in Linux*) stat -c "%s" $1;; - Darwin*) stat -f "%z" $1;; + Darwin*) /usr/bin/stat -f "%z" $1;; *) echo "Unknown OS: $OS_NAME! This script runs only on Linux or Mac" && exit esac } diff --git a/scripts/get_config.py b/scripts/get_config.py new file mode 100644 index 00000000..9cdfb2fe --- /dev/null +++ b/scripts/get_config.py @@ -0,0 +1,46 @@ +import os +import argparse +import sys + +# The config file is in the same directory as this script +config_directory = os.path.dirname(__file__) +config_yaml = os.path.join(config_directory, "config.yaml") +config_json = os.path.join(config_directory, "config.json") + +parser = argparse.ArgumentParser(description='Get values from config file') +parser.add_argument('--default', dest='default', action='store', + help='default value, to be used if the setting is not defined in the config file') +parser.add_argument('key', metavar='key', nargs='+', + help='config key to return') + +args = parser.parse_args() + + +if os.path.isfile(config_yaml): + import yaml + with open(config_yaml, 'r') as configfile: + try: + config = yaml.safe_load(configfile) + except Exception as e: + print(e, file=sys.stderr) + config = {} +elif os.path.isfile(config_json): + import json + with open(config_json, 'r') as configfile: + try: + config = json.load(configfile) + except Exception as e: + print(e, file=sys.stderr) + config = {} +else: + config = {} + +for k in args.key: + if k in config: + config = config[k] + else: + if args.default != None: + print(args.default) + exit() + +print(config) diff --git a/scripts/on_env_start.bat b/scripts/on_env_start.bat index 57dc5da0..0871973f 100644 --- a/scripts/on_env_start.bat +++ b/scripts/on_env_start.bat @@ -8,6 +8,20 @@ if exist "scripts\config.bat" ( @call scripts\config.bat ) +if exist "scripts\user_config.bat" ( + @call scripts\user_config.bat +) + +if exist "stable-diffusion\env" ( + @set PYTHONPATH=%PYTHONPATH%;%cd%\stable-diffusion\env\lib\site-packages +) + +if exist "scripts\get_config.py" ( + @FOR /F "tokens=* USEBACKQ" %%F IN (`python scripts\get_config.py --default=main update_branch`) DO ( + @SET update_branch=%%F + ) +) + if "%update_branch%"=="" ( set update_branch=main ) @@ -41,10 +55,10 @@ if "%update_branch%"=="" ( @echo. & echo "Downloading Easy Diffusion..." & echo. @echo "Using the %update_branch% channel" & echo. - @call git clone -b "%update_branch%" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files && ( + @call git clone -b "%update_branch%" https://github.com/easydiffusion/easydiffusion.git sd-ui-files && ( @echo sd_ui_git_cloned >> scripts\install_status.txt ) || ( - @echo "Error downloading Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" + @echo "Error downloading Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues" & echo "Thanks!" pause @exit /b ) @@ -53,6 +67,7 @@ if "%update_branch%"=="" ( @xcopy sd-ui-files\ui ui /s /i /Y /q @copy sd-ui-files\scripts\on_sd_start.bat scripts\ /Y @copy sd-ui-files\scripts\check_modules.py scripts\ /Y +@copy sd-ui-files\scripts\get_config.py scripts\ /Y @copy "sd-ui-files\scripts\Start Stable Diffusion UI.cmd" . /Y @copy "sd-ui-files\scripts\Developer Console.cmd" . /Y diff --git a/scripts/on_env_start.sh b/scripts/on_env_start.sh index 7e180f02..d936924e 100755 --- a/scripts/on_env_start.sh +++ b/scripts/on_env_start.sh @@ -4,10 +4,22 @@ source ./scripts/functions.sh printf "\n\nEasy Diffusion\n\n" +export PYTHONNOUSERSITE=y + if [ -f "scripts/config.sh" ]; then source scripts/config.sh fi +if [ -f "scripts/user_config.sh" ]; then + source scripts/user_config.sh +fi + +export PYTHONPATH=$(pwd)/installer_files/env/lib/python3.8/site-packages:$(pwd)/stable-diffusion/env/lib/python3.8/site-packages + +if [ -f "scripts/get_config.py" ]; then + export update_branch="$( python scripts/get_config.py --default=main update_branch )" +fi + if [ "$update_branch" == "" ]; then export update_branch="main" fi @@ -26,7 +38,7 @@ else printf "\n\nDownloading Easy Diffusion..\n\n" printf "Using the $update_branch channel\n\n" - if git clone -b "$update_branch" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files ; then + if git clone -b "$update_branch" https://github.com/easydiffusion/easydiffusion.git sd-ui-files ; then echo sd_ui_git_cloned >> scripts/install_status.txt else fail "git clone failed" @@ -38,6 +50,7 @@ cp -Rf sd-ui-files/ui . cp sd-ui-files/scripts/on_sd_start.sh scripts/ cp sd-ui-files/scripts/bootstrap.sh scripts/ cp sd-ui-files/scripts/check_modules.py scripts/ +cp sd-ui-files/scripts/get_config.py scripts/ cp sd-ui-files/scripts/start.sh . cp sd-ui-files/scripts/developer_console.sh . cp sd-ui-files/scripts/functions.sh scripts/ diff --git a/scripts/on_sd_start.bat b/scripts/on_sd_start.bat index 50925816..860361d4 100644 --- a/scripts/on_sd_start.bat +++ b/scripts/on_sd_start.bat @@ -4,11 +4,11 @@ @REM Note to self: Please rewrite this in Python. For the sake of your own sanity. @copy sd-ui-files\scripts\on_env_start.bat scripts\ /Y -@copy sd-ui-files\scripts\bootstrap.bat scripts\ /Y @copy sd-ui-files\scripts\check_modules.py scripts\ /Y +@copy sd-ui-files\scripts\get_config.py scripts\ /Y if exist "%cd%\profile" ( - set USERPROFILE=%cd%\profile + set HF_HOME=%cd%\profile\.cache\huggingface ) @rem set the correct installer path (current vs legacy) @@ -26,7 +26,7 @@ if exist "%cd%\stable-diffusion\env" ( @rem activate the installer env call conda activate @if "%ERRORLEVEL%" NEQ "0" ( - @echo. & echo "Error activating conda for Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. + @echo. & echo "Error activating conda for Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues" & echo "Thanks!" & echo. pause exit /b ) @@ -34,8 +34,6 @@ call conda activate @REM remove the old version of the dev console script, if it's still present if exist "Open Developer Console.cmd" del "Open Developer Console.cmd" -@call python -c "import os; import shutil; frm = 'sd-ui-files\\ui\\hotfix\\9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'; dst = os.path.join(os.path.expanduser('~'), '.cache', 'huggingface', 'transformers', '9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'); shutil.copyfile(frm, dst) if os.path.exists(dst) else print(''); print('Hotfixed broken JSON file from OpenAI');" - @rem create the stable-diffusion folder, to work with legacy installations if not exist "stable-diffusion" mkdir stable-diffusion cd stable-diffusion @@ -49,134 +47,28 @@ if exist "env" ( if exist src rename src src-old if exist ldm rename ldm ldm-old -if not exist "..\models\stable-diffusion" mkdir "..\models\stable-diffusion" -if not exist "..\models\gfpgan" mkdir "..\models\gfpgan" -if not exist "..\models\realesrgan" mkdir "..\models\realesrgan" -if not exist "..\models\vae" mkdir "..\models\vae" - -@rem migrate the legacy models to the correct path (if already downloaded) -if exist "sd-v1-4.ckpt" move sd-v1-4.ckpt ..\models\stable-diffusion\ -if exist "custom-model.ckpt" move custom-model.ckpt ..\models\stable-diffusion\ -if exist "GFPGANv1.3.pth" move GFPGANv1.3.pth ..\models\gfpgan\ -if exist "RealESRGAN_x4plus.pth" move RealESRGAN_x4plus.pth ..\models\realesrgan\ -if exist "RealESRGAN_x4plus_anime_6B.pth" move RealESRGAN_x4plus_anime_6B.pth ..\models\realesrgan\ if not exist "%INSTALL_ENV_DIR%\DLLs\libssl-1_1-x64.dll" copy "%INSTALL_ENV_DIR%\Library\bin\libssl-1_1-x64.dll" "%INSTALL_ENV_DIR%\DLLs\" if not exist "%INSTALL_ENV_DIR%\DLLs\libcrypto-1_1-x64.dll" copy "%INSTALL_ENV_DIR%\Library\bin\libcrypto-1_1-x64.dll" "%INSTALL_ENV_DIR%\DLLs\" -@rem install torch and torchvision -call python ..\scripts\check_modules.py torch torchvision -if "%ERRORLEVEL%" EQU "0" ( - echo "torch and torchvision have already been installed." -) else ( - echo "Installing torch and torchvision.." - - @REM prevent from using packages from the user's home directory, to avoid conflicts - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - call python -m pip install --upgrade torch==1.13.1+cu116 torchvision==0.14.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116 || ( - echo "Error installing torch. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - exit /b - ) -) - +@rem install or upgrade the required modules set PATH=C:\Windows\System32;%PATH% -@rem install/upgrade sdkit -call python ..\scripts\check_modules.py sdkit sdkit.models ldm transformers numpy antlr4 gfpgan realesrgan -if "%ERRORLEVEL%" EQU "0" ( - echo "sdkit is already installed." +@REM prevent from using packages from the user's home directory, to avoid conflicts +set PYTHONNOUSERSITE=1 +set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - @rem skip sdkit upgrade if in developer-mode - if not exist "..\src\sdkit" ( - @REM prevent from using packages from the user's home directory, to avoid conflicts - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - call python -m pip install --upgrade sdkit==1.0.60 -q || ( - echo "Error updating sdkit" - ) - ) -) else ( - echo "Installing sdkit: https://pypi.org/project/sdkit/" - - @REM prevent from using packages from the user's home directory, to avoid conflicts - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - call python -m pip install sdkit==1.0.60 || ( - echo "Error installing sdkit. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - exit /b - ) -) - -call python -c "from importlib.metadata import version; print('sdkit version:', version('sdkit'))" - -@rem upgrade stable-diffusion-sdkit -call python -m pip install --upgrade stable-diffusion-sdkit==2.1.4 -q || ( - echo "Error updating stable-diffusion-sdkit" -) -call python -c "from importlib.metadata import version; print('stable-diffusion version:', version('stable-diffusion-sdkit'))" - -@rem install rich -call python ..\scripts\check_modules.py rich -if "%ERRORLEVEL%" EQU "0" ( - echo "rich has already been installed." -) else ( - echo "Installing rich.." - - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - call python -m pip install rich || ( - echo "Error installing rich. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - exit /b - ) -) - -@rem install ruamel.yaml -call python ..\scripts\check_modules.py ruamel.yaml -if "%ERRORLEVEL%" EQU "0" ( - echo "ruamel.yaml has already been installed." -) else ( - echo "Installing ruamel.yaml.." - - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - call python -m pip install ruamel.yaml==0.17.21 || ( - echo "Error installing ruamel.yaml. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - exit /b - ) -) - -set PATH=C:\Windows\System32;%PATH% - -call python ..\scripts\check_modules.py uvicorn fastapi -@if "%ERRORLEVEL%" EQU "0" ( - echo "Packages necessary for Easy Diffusion were already installed" -) else ( - @echo. & echo "Downloading packages necessary for Easy Diffusion..." & echo. - - set PYTHONNOUSERSITE=1 - set PYTHONPATH=%INSTALL_ENV_DIR%\lib\site-packages - - @call conda install -c conda-forge -y uvicorn fastapi || ( - echo "Error installing the packages necessary for Easy Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" - pause - exit /b - ) +@rem Download the required packages +call python ..\scripts\check_modules.py +if "%ERRORLEVEL%" NEQ "0" ( + pause + exit /b ) call WHERE uvicorn > .tmp @>nul findstr /m "uvicorn" .tmp @if "%ERRORLEVEL%" NEQ "0" ( - @echo. & echo "UI packages not found! Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. + @echo. & echo "UI packages not found! Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/easydiffusion/easydiffusion/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues" & echo "Thanks!" & echo. pause exit /b ) @@ -186,162 +78,6 @@ call WHERE uvicorn > .tmp @echo conda_sd_ui_deps_installed >> ..\scripts\install_status.txt ) -@if exist "..\models\stable-diffusion\sd-v1-4.ckpt" ( - for %%I in ("..\models\stable-diffusion\sd-v1-4.ckpt") do if "%%~zI" EQU "4265380512" ( - echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the HuggingFace 4 GB Model." - ) else ( - for %%J in ("..\models\stable-diffusion\sd-v1-4.ckpt") do if "%%~zJ" EQU "7703807346" ( - echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the HuggingFace 7 GB Model." - ) else ( - for %%K in ("..\models\stable-diffusion\sd-v1-4.ckpt") do if "%%~zK" EQU "7703810927" ( - echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the Waifu Model." - ) else ( - echo. & echo "The model file present at models\stable-diffusion\sd-v1-4.ckpt is invalid. It is only %%~zK bytes in size. Re-downloading.." & echo. - del "..\models\stable-diffusion\sd-v1-4.ckpt" - ) - ) - ) -) - -@if not exist "..\models\stable-diffusion\sd-v1-4.ckpt" ( - @echo. & echo "Downloading data files (weights) for Stable Diffusion.." & echo. - - @call curl -L -k https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt > ..\models\stable-diffusion\sd-v1-4.ckpt - - @if exist "..\models\stable-diffusion\sd-v1-4.ckpt" ( - for %%I in ("..\models\stable-diffusion\sd-v1-4.ckpt") do if "%%~zI" NEQ "4265380512" ( - echo. & echo "Error: The downloaded model file was invalid! Bytes downloaded: %%~zI" & echo. - echo. & echo "Error downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) - ) else ( - @echo. & echo "Error downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) -) - - - -@if exist "..\models\gfpgan\GFPGANv1.3.pth" ( - for %%I in ("..\models\gfpgan\GFPGANv1.3.pth") do if "%%~zI" EQU "348632874" ( - echo "Data files (weights) necessary for GFPGAN (Face Correction) were already downloaded" - ) else ( - echo. & echo "The GFPGAN model file present at models\gfpgan\GFPGANv1.3.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo. - del "..\models\gfpgan\GFPGANv1.3.pth" - ) -) - -@if not exist "..\models\gfpgan\GFPGANv1.3.pth" ( - @echo. & echo "Downloading data files (weights) for GFPGAN (Face Correction).." & echo. - - @call curl -L -k https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth > ..\models\gfpgan\GFPGANv1.3.pth - - @if exist "..\models\gfpgan\GFPGANv1.3.pth" ( - for %%I in ("..\models\gfpgan\GFPGANv1.3.pth") do if "%%~zI" NEQ "348632874" ( - echo. & echo "Error: The downloaded GFPGAN model file was invalid! Bytes downloaded: %%~zI" & echo. - echo. & echo "Error downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) - ) else ( - @echo. & echo "Error downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) -) - - - -@if exist "..\models\realesrgan\RealESRGAN_x4plus.pth" ( - for %%I in ("..\models\realesrgan\RealESRGAN_x4plus.pth") do if "%%~zI" EQU "67040989" ( - echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus were already downloaded" - ) else ( - echo. & echo "The RealESRGAN model file present at models\realesrgan\RealESRGAN_x4plus.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo. - del "..\models\realesrgan\RealESRGAN_x4plus.pth" - ) -) - -@if not exist "..\models\realesrgan\RealESRGAN_x4plus.pth" ( - @echo. & echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus.." & echo. - - @call curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth > ..\models\realesrgan\RealESRGAN_x4plus.pth - - @if exist "..\models\realesrgan\RealESRGAN_x4plus.pth" ( - for %%I in ("..\models\realesrgan\RealESRGAN_x4plus.pth") do if "%%~zI" NEQ "67040989" ( - echo. & echo "Error: The downloaded ESRGAN x4plus model file was invalid! Bytes downloaded: %%~zI" & echo. - echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) - ) else ( - @echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) -) - - - -@if exist "..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth" ( - for %%I in ("..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth") do if "%%~zI" EQU "17938799" ( - echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus_anime were already downloaded" - ) else ( - echo. & echo "The RealESRGAN model file present at models\realesrgan\RealESRGAN_x4plus_anime_6B.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo. - del "..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth" - ) -) - -@if not exist "..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth" ( - @echo. & echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime.." & echo. - - @call curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth > ..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth - - @if exist "..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth" ( - for %%I in ("..\models\realesrgan\RealESRGAN_x4plus_anime_6B.pth") do if "%%~zI" NEQ "17938799" ( - echo. & echo "Error: The downloaded ESRGAN x4plus_anime model file was invalid! Bytes downloaded: %%~zI" & echo. - echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) - ) else ( - @echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) -) - - - -@if exist "..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt" ( - for %%I in ("..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt") do if "%%~zI" EQU "334695179" ( - echo "Data files (weights) necessary for the default VAE (sd-vae-ft-mse-original) were already downloaded" - ) else ( - echo. & echo "The default VAE (sd-vae-ft-mse-original) file present at models\vae\vae-ft-mse-840000-ema-pruned.ckpt is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo. - del "..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt" - ) -) - -@if not exist "..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt" ( - @echo. & echo "Downloading data files (weights) for the default VAE (sd-vae-ft-mse-original).." & echo. - - @call curl -L -k https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt > ..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt - - @if exist "..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt" ( - for %%I in ("..\models\vae\vae-ft-mse-840000-ema-pruned.ckpt") do if "%%~zI" NEQ "334695179" ( - echo. & echo "Error: The downloaded default VAE (sd-vae-ft-mse-original) file was invalid! Bytes downloaded: %%~zI" & echo. - echo. & echo "Error downloading the data files (weights) for the default VAE (sd-vae-ft-mse-original). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) - ) else ( - @echo. & echo "Error downloading the data files (weights) for the default VAE (sd-vae-ft-mse-original). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo. - pause - exit /b - ) -) - @>nul findstr /m "sd_install_complete" ..\scripts\install_status.txt @if "%ERRORLEVEL%" NEQ "0" ( @echo sd_weights_downloaded >> ..\scripts\install_status.txt @@ -360,14 +96,25 @@ call python --version @cd .. @set SD_UI_PATH=%cd%\ui + +@FOR /F "tokens=* USEBACKQ" %%F IN (`python scripts\get_config.py --default=9000 net listen_port`) DO ( + @SET ED_BIND_PORT=%%F +) + +@FOR /F "tokens=* USEBACKQ" %%F IN (`python scripts\get_config.py --default=False net listen_to_network`) DO ( + if "%%F" EQU "True" ( + @SET ED_BIND_IP=0.0.0.0 + ) else ( + @SET ED_BIND_IP=127.0.0.1 + ) +) + @cd stable-diffusion @rem set any overrides set HF_HUB_DISABLE_SYMLINKS_WARNING=true -@if NOT DEFINED SD_UI_BIND_PORT set SD_UI_BIND_PORT=9000 -@if NOT DEFINED SD_UI_BIND_IP set SD_UI_BIND_IP=0.0.0.0 -@uvicorn main:server_api --app-dir "%SD_UI_PATH%" --port %SD_UI_BIND_PORT% --host %SD_UI_BIND_IP% --log-level error +@uvicorn main:server_api --app-dir "%SD_UI_PATH%" --port %ED_BIND_PORT% --host %ED_BIND_IP% --log-level error @pause diff --git a/scripts/on_sd_start.sh b/scripts/on_sd_start.sh index 724d9a31..be5161d4 100755 --- a/scripts/on_sd_start.sh +++ b/scripts/on_sd_start.sh @@ -4,6 +4,7 @@ cp sd-ui-files/scripts/functions.sh scripts/ cp sd-ui-files/scripts/on_env_start.sh scripts/ cp sd-ui-files/scripts/bootstrap.sh scripts/ cp sd-ui-files/scripts/check_modules.py scripts/ +cp sd-ui-files/scripts/get_config.py scripts/ source ./scripts/functions.sh @@ -18,11 +19,6 @@ if [ -e "open_dev_console.sh" ]; then rm "open_dev_console.sh" fi -python -c "import os; import shutil; frm = 'sd-ui-files/ui/hotfix/9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'; dst = os.path.join(os.path.expanduser('~'), '.cache', 'huggingface', 'transformers', '9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'); shutil.copyfile(frm, dst) if os.path.exists(dst) else print(''); print('Hotfixed broken JSON file from OpenAI');" - -# Caution, this file will make your eyes and brain bleed. It's such an unholy mess. -# Note to self: Please rewrite this in Python. For the sake of your own sanity. - # set the correct installer path (current vs legacy) if [ -e "installer_files/env" ]; then export INSTALL_ENV_DIR="$(pwd)/installer_files/env" @@ -44,274 +40,14 @@ fi if [ -e "src" ]; then mv src src-old; fi if [ -e "ldm" ]; then mv ldm ldm-old; fi -mkdir -p "../models/stable-diffusion" -mkdir -p "../models/gfpgan" -mkdir -p "../models/realesrgan" -mkdir -p "../models/vae" - -# migrate the legacy models to the correct path (if already downloaded) -if [ -e "sd-v1-4.ckpt" ]; then mv sd-v1-4.ckpt ../models/stable-diffusion/; fi -if [ -e "custom-model.ckpt" ]; then mv custom-model.ckpt ../models/stable-diffusion/; fi -if [ -e "GFPGANv1.3.pth" ]; then mv GFPGANv1.3.pth ../models/gfpgan/; fi -if [ -e "RealESRGAN_x4plus.pth" ]; then mv RealESRGAN_x4plus.pth ../models/realesrgan/; fi -if [ -e "RealESRGAN_x4plus_anime_6B.pth" ]; then mv RealESRGAN_x4plus_anime_6B.pth ../models/realesrgan/; fi - -OS_NAME=$(uname -s) -case "${OS_NAME}" in - Linux*) OS_NAME="linux";; - Darwin*) OS_NAME="macos";; - *) echo "Unknown OS: $OS_NAME! This script runs only on Linux or Mac" && exit -esac - -# install torch and torchvision -if python ../scripts/check_modules.py torch torchvision; then - # temp fix for installations that installed torch 2.0 by mistake - if [ "$OS_NAME" == "linux" ]; then - python -m pip install --upgrade torch==1.13.1+cu116 torchvision==0.14.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116 -q - elif [ "$OS_NAME" == "macos" ]; then - python -m pip install --upgrade torch==1.13.1 torchvision==0.14.1 -q - fi - - echo "torch and torchvision have already been installed." -else - echo "Installing torch and torchvision.." - - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - if [ "$OS_NAME" == "linux" ]; then - if python -m pip install --upgrade torch==1.13.1+cu116 torchvision==0.14.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116 ; then - echo "Installed." - else - fail "torch install failed" - fi - elif [ "$OS_NAME" == "macos" ]; then - if python -m pip install --upgrade torch==1.13.1 torchvision==0.14.1 ; then - echo "Installed." - else - fail "torch install failed" - fi - fi +# Download the required packages +if ! python ../scripts/check_modules.py; then + read -p "Press any key to continue" + exit 1 fi -# install/upgrade sdkit -if python ../scripts/check_modules.py sdkit sdkit.models ldm transformers numpy antlr4 gfpgan realesrgan ; then - echo "sdkit is already installed." - - # skip sdkit upgrade if in developer-mode - if [ ! -e "../src/sdkit" ]; then - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - python -m pip install --upgrade sdkit==1.0.60 -q - fi -else - echo "Installing sdkit: https://pypi.org/project/sdkit/" - - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - if python -m pip install sdkit==1.0.60 ; then - echo "Installed." - else - fail "sdkit install failed" - fi -fi - -python -c "from importlib.metadata import version; print('sdkit version:', version('sdkit'))" - -# upgrade stable-diffusion-sdkit -python -m pip install --upgrade stable-diffusion-sdkit==2.1.4 -q -python -c "from importlib.metadata import version; print('stable-diffusion version:', version('stable-diffusion-sdkit'))" - -# install rich -if python ../scripts/check_modules.py rich; then - echo "rich has already been installed." -else - echo "Installing rich.." - - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - if python -m pip install rich ; then - echo "Installed." - else - fail "Install failed for rich" - fi -fi - -# install ruamel -if python ../scripts/check_modules.py ruamel.yaml; then - echo "ruamel.yaml has already been installed." -else - echo "Installing ruamel.yaml.." - - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - if python -m pip install ruamel.yaml==0.17.21 ; then - echo "Installed." - else - fail "Install failed for rich" - fi -fi - -if python ../scripts/check_modules.py uvicorn fastapi ; then - echo "Packages necessary for Easy Diffusion were already installed" -else - printf "\n\nDownloading packages necessary for Easy Diffusion..\n\n" - - export PYTHONNOUSERSITE=1 - export PYTHONPATH="$INSTALL_ENV_DIR/lib/python3.8/site-packages" - - if conda install -c conda-forge -y uvicorn fastapi ; then - echo "Installed. Testing.." - else - fail "'conda install uvicorn' failed" - fi - - if ! command -v uvicorn &> /dev/null; then - fail "UI packages not found!" - fi -fi - -if [ -f "../models/stable-diffusion/sd-v1-4.ckpt" ]; then - model_size=`filesize "../models/stable-diffusion/sd-v1-4.ckpt"` - - if [ "$model_size" -eq "4265380512" ] || [ "$model_size" -eq "7703807346" ] || [ "$model_size" -eq "7703810927" ]; then - echo "Data files (weights) necessary for Stable Diffusion were already downloaded" - else - printf "\n\nThe model file present at models/stable-diffusion/sd-v1-4.ckpt is invalid. It is only $model_size bytes in size. Re-downloading.." - rm ../models/stable-diffusion/sd-v1-4.ckpt - fi -fi - -if [ ! -f "../models/stable-diffusion/sd-v1-4.ckpt" ]; then - echo "Downloading data files (weights) for Stable Diffusion.." - - curl -L -k https://huggingface.co/CompVis/stable-diffusion-v-1-4-original/resolve/main/sd-v1-4.ckpt > ../models/stable-diffusion/sd-v1-4.ckpt - - if [ -f "../models/stable-diffusion/sd-v1-4.ckpt" ]; then - model_size=`filesize "../models/stable-diffusion/sd-v1-4.ckpt"` - if [ ! "$model_size" == "4265380512" ]; then - fail "The downloaded model file was invalid! Bytes downloaded: $model_size" - fi - else - fail "Error downloading the data files (weights) for Stable Diffusion" - fi -fi - - -if [ -f "../models/gfpgan/GFPGANv1.3.pth" ]; then - model_size=`filesize "../models/gfpgan/GFPGANv1.3.pth"` - - if [ "$model_size" -eq "348632874" ]; then - echo "Data files (weights) necessary for GFPGAN (Face Correction) were already downloaded" - else - printf "\n\nThe model file present at models/gfpgan/GFPGANv1.3.pth is invalid. It is only $model_size bytes in size. Re-downloading.." - rm ../models/gfpgan/GFPGANv1.3.pth - fi -fi - -if [ ! -f "../models/gfpgan/GFPGANv1.3.pth" ]; then - echo "Downloading data files (weights) for GFPGAN (Face Correction).." - - curl -L -k https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth > ../models/gfpgan/GFPGANv1.3.pth - - if [ -f "../models/gfpgan/GFPGANv1.3.pth" ]; then - model_size=`filesize "../models/gfpgan/GFPGANv1.3.pth"` - if [ ! "$model_size" -eq "348632874" ]; then - fail "The downloaded GFPGAN model file was invalid! Bytes downloaded: $model_size" - fi - else - fail "Error downloading the data files (weights) for GFPGAN (Face Correction)." - fi -fi - - -if [ -f "../models/realesrgan/RealESRGAN_x4plus.pth" ]; then - model_size=`filesize "../models/realesrgan/RealESRGAN_x4plus.pth"` - - if [ "$model_size" -eq "67040989" ]; then - echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus were already downloaded" - else - printf "\n\nThe model file present at models/realesrgan/RealESRGAN_x4plus.pth is invalid. It is only $model_size bytes in size. Re-downloading.." - rm ../models/realesrgan/RealESRGAN_x4plus.pth - fi -fi - -if [ ! -f "../models/realesrgan/RealESRGAN_x4plus.pth" ]; then - echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus.." - - curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth > ../models/realesrgan/RealESRGAN_x4plus.pth - - if [ -f "../models/realesrgan/RealESRGAN_x4plus.pth" ]; then - model_size=`filesize "../models/realesrgan/RealESRGAN_x4plus.pth"` - if [ ! "$model_size" -eq "67040989" ]; then - fail "The downloaded ESRGAN x4plus model file was invalid! Bytes downloaded: $model_size" - fi - else - fail "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus" - fi -fi - - -if [ -f "../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth" ]; then - model_size=`filesize "../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth"` - - if [ "$model_size" -eq "17938799" ]; then - echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus_anime were already downloaded" - else - printf "\n\nThe model file present at models/realesrgan/RealESRGAN_x4plus_anime_6B.pth is invalid. It is only $model_size bytes in size. Re-downloading.." - rm ../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth - fi -fi - -if [ ! -f "../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth" ]; then - echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime.." - - curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth > ../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth - - if [ -f "../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth" ]; then - model_size=`filesize "../models/realesrgan/RealESRGAN_x4plus_anime_6B.pth"` - if [ ! "$model_size" -eq "17938799" ]; then - fail "The downloaded ESRGAN x4plus_anime model file was invalid! Bytes downloaded: $model_size" - fi - else - fail "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime." - fi -fi - - -if [ -f "../models/vae/vae-ft-mse-840000-ema-pruned.ckpt" ]; then - model_size=`filesize "../models/vae/vae-ft-mse-840000-ema-pruned.ckpt"` - - if [ "$model_size" -eq "334695179" ]; then - echo "Data files (weights) necessary for the default VAE (sd-vae-ft-mse-original) were already downloaded" - else - printf "\n\nThe model file present at models/vae/vae-ft-mse-840000-ema-pruned.ckpt is invalid. It is only $model_size bytes in size. Re-downloading.." - rm ../models/vae/vae-ft-mse-840000-ema-pruned.ckpt - fi -fi - -if [ ! -f "../models/vae/vae-ft-mse-840000-ema-pruned.ckpt" ]; then - echo "Downloading data files (weights) for the default VAE (sd-vae-ft-mse-original).." - - curl -L -k https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt > ../models/vae/vae-ft-mse-840000-ema-pruned.ckpt - - if [ -f "../models/vae/vae-ft-mse-840000-ema-pruned.ckpt" ]; then - model_size=`filesize "../models/vae/vae-ft-mse-840000-ema-pruned.ckpt"` - if [ ! "$model_size" -eq "334695179" ]; then - printf "\n\nError: The downloaded default VAE (sd-vae-ft-mse-original) file was invalid! Bytes downloaded: $model_size\n\n" - printf "\n\nError downloading the data files (weights) for the default VAE (sd-vae-ft-mse-original). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n" - read -p "Press any key to continue" - exit - fi - else - printf "\n\nError downloading the data files (weights) for the default VAE (sd-vae-ft-mse-original). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/wiki/Troubleshooting\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n" - read -p "Press any key to continue" - exit - fi +if ! command -v uvicorn &> /dev/null; then + fail "UI packages not found!" fi if [ `grep -c sd_install_complete ../scripts/install_status.txt` -gt "0" ]; then @@ -332,8 +68,17 @@ python --version cd .. export SD_UI_PATH=`pwd`/ui +export ED_BIND_PORT="$( python scripts/get_config.py --default=9000 net listen_port )" +case "$( python scripts/get_config.py --default=False net listen_to_network )" in + "True") + export ED_BIND_IP=0.0.0.0 + ;; + "False") + export ED_BIND_IP=127.0.0.1 + ;; +esac cd stable-diffusion -uvicorn main:server_api --app-dir "$SD_UI_PATH" --port ${SD_UI_BIND_PORT:-9000} --host ${SD_UI_BIND_IP:-0.0.0.0} --log-level error +uvicorn main:server_api --app-dir "$SD_UI_PATH" --port "$ED_BIND_PORT" --host "$ED_BIND_IP" --log-level error read -p "Press any key to continue" diff --git a/ui/easydiffusion/app.py b/ui/easydiffusion/app.py index 1f106335..d50ee5d1 100644 --- a/ui/easydiffusion/app.py +++ b/ui/easydiffusion/app.py @@ -1,20 +1,23 @@ +import json +import logging import os import socket import sys -import json import traceback -import logging import shlex from ruamel.yaml import YAML -yaml = YAML() import urllib -from rich.logging import RichHandler - -from sdkit.utils import log as sdkit_log # hack, so we can overwrite the log config +import warnings from easydiffusion import task_manager from easydiffusion.utils import log +from rich.logging import RichHandler +from rich.console import Console +from rich.panel import Panel +from sdkit.utils import log as sdkit_log # hack, so we can overwrite the log config + +yaml = YAML() # Remove all handlers associated with the root logger object. for handler in logging.root.handlers[:]: @@ -58,54 +61,81 @@ APP_CONFIG_DEFAULTS = { }, } -IMAGE_EXTENSIONS = [".png", ".apng", ".jpg", ".jpeg", ".jfif", ".pjpeg", ".pjp", ".jxl", ".gif", ".webp", ".avif", ".svg"] +IMAGE_EXTENSIONS = [ + ".png", + ".apng", + ".jpg", + ".jpeg", + ".jfif", + ".pjpeg", + ".pjp", + ".jxl", + ".gif", + ".webp", + ".avif", + ".svg", +] CUSTOM_MODIFIERS_DIR = os.path.abspath(os.path.join(SD_DIR, "..", "modifiers")) -CUSTOM_MODIFIERS_PORTRAIT_EXTENSIONS=[".portrait", "_portrait", " portrait", "-portrait"] -CUSTOM_MODIFIERS_LANDSCAPE_EXTENSIONS=[".landscape", "_landscape", " landscape", "-landscape"] +CUSTOM_MODIFIERS_PORTRAIT_EXTENSIONS = [ + ".portrait", + "_portrait", + " portrait", + "-portrait", +] +CUSTOM_MODIFIERS_LANDSCAPE_EXTENSIONS = [ + ".landscape", + "_landscape", + " landscape", + "-landscape", +] + def init(): os.makedirs(USER_UI_PLUGINS_DIR, exist_ok=True) os.makedirs(USER_SERVER_PLUGINS_DIR, exist_ok=True) + # https://pytorch.org/docs/stable/storage.html + warnings.filterwarnings("ignore", category=UserWarning, message="TypedStorage is deprecated") + load_server_plugins() update_render_threads() def getConfig(default_val=APP_CONFIG_DEFAULTS): - config_yaml_path = os.path.join(CONFIG_DIR, 'config.yaml') + config_yaml_path = os.path.join(CONFIG_DIR, "config.yaml") if os.path.isfile(config_yaml_path): try: - log.info('Loading config.yaml') - with open(config_yaml_path, 'r', encoding='utf-8') as f: + log.info("Loading config.yaml") + with open(config_yaml_path, "r", encoding="utf-8") as f: config = yaml.load(f) - if 'net' not in config: - config['net'] = {} - if os.getenv('SD_UI_BIND_PORT') is not None: - config['net']['listen_port'] = int(os.getenv('SD_UI_BIND_PORT')) + if "net" not in config: + config["net"] = {} + if os.getenv("SD_UI_BIND_PORT") is not None: + config["net"]["listen_port"] = int(os.getenv("SD_UI_BIND_PORT")) else: config['net']['listen_port'] = 9000 - if os.getenv('SD_UI_BIND_IP') is not None: - config['net']['listen_to_network'] = (os.getenv('SD_UI_BIND_IP') == '0.0.0.0') + if os.getenv("SD_UI_BIND_IP") is not None: + config["net"]["listen_to_network"] = os.getenv("SD_UI_BIND_IP") == "0.0.0.0" else: - config['net']['listen_to_network'] = True + config["net"]["listen_to_network"] = True return config except Exception as e: log.warn(traceback.format_exc()) return default_val else: try: - config_json_path = os.path.join(CONFIG_DIR, 'config.json') + config_json_path = os.path.join(CONFIG_DIR, "config.json") if not os.path.exists(config_json_path): return default_val else: - log.info('Converting old json config file to yaml') - with open(config_json_path, 'r', encoding='utf-8') as f: + log.info("Converting old json config file to yaml") + with open(config_json_path, "r", encoding="utf-8") as f: config = json.load(f) # Save config in new format setConfig(config) - os.rename(config_json_path, config_json_path + '.bak') - log.info('Saved old config.json as config.json.bak') + os.rename(config_json_path, config_json_path + ".bak") + log.info("Saved old config.json as config.json.bak") return getConfig(default_val) except Exception as e: log.warn(traceback.format_exc()) @@ -121,50 +151,6 @@ def setConfig(config): except: log.error(traceback.format_exc()) - try: # config.bat - config_bat_path = os.path.join(CONFIG_DIR, "config.bat") - config_bat = [] - - if "update_branch" in config: - config_bat.append(f"@set update_branch={config['update_branch']}") - - config_bat.append(f"@set SD_UI_BIND_PORT={config['net']['listen_port']}") - bind_ip = "0.0.0.0" if config["net"]["listen_to_network"] else "127.0.0.1" - config_bat.append(f"@set SD_UI_BIND_IP={bind_ip}") - - # Preserve these variables if they are set - for var in PRESERVE_CONFIG_VARS: - if os.getenv(var) is not None: - config_bat.append(f"@set {var}={os.getenv(var)}") - - if len(config_bat) > 0: - with open(config_bat_path, "w", encoding="utf-8") as f: - f.write("\n".join(config_bat)) - except: - log.error(traceback.format_exc()) - - try: # config.sh - config_sh_path = os.path.join(CONFIG_DIR, "config.sh") - config_sh = ["#!/bin/bash"] - - if "update_branch" in config: - config_sh.append(f"export update_branch={config['update_branch']}") - - config_sh.append(f"export SD_UI_BIND_PORT={config['net']['listen_port']}") - bind_ip = "0.0.0.0" if config["net"]["listen_to_network"] else "127.0.0.1" - config_sh.append(f"export SD_UI_BIND_IP={bind_ip}") - - # Preserve these variables if they are set - for var in PRESERVE_CONFIG_VARS: - if os.getenv(var) is not None: - config_bat.append(f'export {var}="{shlex.quote(os.getenv(var))}"') - - if len(config_sh) > 1: - with open(config_sh_path, "w", encoding="utf-8") as f: - f.write("\n".join(config_sh)) - except: - log.error(traceback.format_exc()) - def save_to_config(ckpt_model_name, vae_model_name, hypernetwork_model_name, vram_usage_level): config = getConfig() @@ -253,18 +239,56 @@ def getIPConfig(): def open_browser(): config = getConfig() ui = config.get("ui", {}) - net = config.get("net", {"listen_port": 9000}) + net = config.get("net", {}) port = net.get("listen_port", 9000) + if ui.get("open_browser_on_start", True): import webbrowser webbrowser.open(f"http://localhost:{port}") + Console().print( + Panel( + "\n" + + "[white]Easy Diffusion is ready to serve requests.\n\n" + + "A new browser tab should have been opened by now.\n" + + f"If not, please open your web browser and navigate to [bold yellow underline]http://localhost:{port}/\n", + title="Easy Diffusion is ready", + style="bold yellow on blue", + ) + ) + + +def fail_and_die(fail_type: str, data: str): + suggestions = [ + "Run this installer again.", + "If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB", + "If that doesn't solve the problem, please file an issue at https://github.com/easydiffusion/easydiffusion/issues", + ] + + if fail_type == "model_download": + fail_label = f"Error downloading the {data} model" + suggestions.insert( + 1, + "If that doesn't fix it, please try to download the file manually. The address to download from, and the destination to save to are printed above this message.", + ) + else: + fail_label = "Error while installing Easy Diffusion" + + msg = [f"{fail_label}. Sorry about that, please try to:"] + for i, suggestion in enumerate(suggestions): + msg.append(f"{i+1}. {suggestion}") + msg.append("Thanks!") + + print("\n".join(msg)) + exit(1) + + def get_image_modifiers(): modifiers_json_path = os.path.join(SD_UI_DIR, "modifiers.json") modifier_categories = {} - original_category_order=[] + original_category_order = [] with open(modifiers_json_path, "r", encoding="utf-8") as f: modifiers_file = json.load(f) @@ -274,14 +298,14 @@ def get_image_modifiers(): # convert modifiers from a list of objects to a dict of dicts for category_item in modifiers_file: - category_name = category_item['category'] + category_name = category_item["category"] original_category_order.append(category_name) category = {} - for modifier_item in category_item['modifiers']: + for modifier_item in category_item["modifiers"]: modifier = {} - for preview_item in modifier_item['previews']: - modifier[preview_item['name']] = preview_item['path'] - category[modifier_item['modifier']] = modifier + for preview_item in modifier_item["previews"]: + modifier[preview_item["name"]] = preview_item["path"] + category[modifier_item["modifier"]] = modifier modifier_categories[category_name] = category def scan_directory(directory_path: str, category_name="Modifiers"): @@ -294,12 +318,27 @@ def get_image_modifiers(): modifier_name = entry.name[: -len(file_extension[0])] modifier_path = f"custom/{entry.path[len(CUSTOM_MODIFIERS_DIR) + 1:]}" # URL encode path segments - modifier_path = "/".join(map(lambda segment: urllib.parse.quote(segment), modifier_path.split("/"))) + modifier_path = "/".join( + map( + lambda segment: urllib.parse.quote(segment), + modifier_path.split("/"), + ) + ) is_portrait = True is_landscape = True - portrait_extension = list(filter(lambda e: modifier_name.lower().endswith(e), CUSTOM_MODIFIERS_PORTRAIT_EXTENSIONS)) - landscape_extension = list(filter(lambda e: modifier_name.lower().endswith(e), CUSTOM_MODIFIERS_LANDSCAPE_EXTENSIONS)) + portrait_extension = list( + filter( + lambda e: modifier_name.lower().endswith(e), + CUSTOM_MODIFIERS_PORTRAIT_EXTENSIONS, + ) + ) + landscape_extension = list( + filter( + lambda e: modifier_name.lower().endswith(e), + CUSTOM_MODIFIERS_LANDSCAPE_EXTENSIONS, + ) + ) if len(portrait_extension) > 0: is_landscape = False @@ -307,24 +346,24 @@ def get_image_modifiers(): elif len(landscape_extension) > 0: is_portrait = False modifier_name = modifier_name[: -len(landscape_extension[0])] - - if (category_name not in modifier_categories): + + if category_name not in modifier_categories: modifier_categories[category_name] = {} - + category = modifier_categories[category_name] - if (modifier_name not in category): + if modifier_name not in category: category[modifier_name] = {} - if (is_portrait or "portrait" not in category[modifier_name]): + if is_portrait or "portrait" not in category[modifier_name]: category[modifier_name]["portrait"] = modifier_path - - if (is_landscape or "landscape" not in category[modifier_name]): + + if is_landscape or "landscape" not in category[modifier_name]: category[modifier_name]["landscape"] = modifier_path elif entry.is_dir(): scan_directory( entry.path, - entry.name if directory_path==CUSTOM_MODIFIERS_DIR else f"{category_name}/{entry.name}", + entry.name if directory_path == CUSTOM_MODIFIERS_DIR else f"{category_name}/{entry.name}", ) scan_directory(CUSTOM_MODIFIERS_DIR) @@ -337,12 +376,12 @@ def get_image_modifiers(): # convert the modifiers back into a list of objects modifier_categories_list = [] for category_name in [*original_category_order, *custom_categories]: - category = { 'category': category_name, 'modifiers': [] } + category = {"category": category_name, "modifiers": []} for modifier_name in sorted(modifier_categories[category_name].keys(), key=str.casefold): - modifier = { 'modifier': modifier_name, 'previews': [] } + modifier = {"modifier": modifier_name, "previews": []} for preview_name, preview_path in modifier_categories[category_name][modifier_name].items(): - modifier['previews'].append({ 'name': preview_name, 'path': preview_path }) - category['modifiers'].append(modifier) + modifier["previews"].append({"name": preview_name, "path": preview_path}) + category["modifiers"].append(modifier) modifier_categories_list.append(category) return modifier_categories_list diff --git a/ui/easydiffusion/device_manager.py b/ui/easydiffusion/device_manager.py index 18069a82..dc705927 100644 --- a/ui/easydiffusion/device_manager.py +++ b/ui/easydiffusion/device_manager.py @@ -1,9 +1,9 @@ import os import platform -import torch -import traceback import re +import traceback +import torch from easydiffusion.utils import log """ @@ -118,7 +118,10 @@ def auto_pick_devices(currently_active_devices): # These already-running devices probably aren't terrible, since they were picked in the past. # Worst case, the user can restart the program and that'll get rid of them. devices = list( - filter((lambda x: x["mem_free"] > mem_free_threshold or x["device"] in currently_active_devices), devices) + filter( + (lambda x: x["mem_free"] > mem_free_threshold or x["device"] in currently_active_devices), + devices, + ) ) devices = list(map(lambda x: x["device"], devices)) return devices @@ -162,6 +165,7 @@ def needs_to_force_full_precision(context): and ( " 1660" in device_name or " 1650" in device_name + or " 1630" in device_name or " t400" in device_name or " t550" in device_name or " t600" in device_name @@ -221,9 +225,9 @@ def is_device_compatible(device): try: _, mem_total = torch.cuda.mem_get_info(device) mem_total /= float(10**9) - if mem_total < 3.0: + if mem_total < 1.9: if is_device_compatible.history.get(device) == None: - log.warn(f"GPU {device} with less than 3 GB of VRAM is not compatible with Stable Diffusion") + log.warn(f"GPU {device} with less than 2 GB of VRAM is not compatible with Stable Diffusion") is_device_compatible.history[device] = 1 return False except RuntimeError as e: diff --git a/ui/easydiffusion/model_manager.py b/ui/easydiffusion/model_manager.py index a06c56cf..de2c10ac 100644 --- a/ui/easydiffusion/model_manager.py +++ b/ui/easydiffusion/model_manager.py @@ -1,13 +1,24 @@ import os +import shutil +from glob import glob +import traceback from easydiffusion import app from easydiffusion.types import TaskData from easydiffusion.utils import log - from sdkit import Context -from sdkit.models import load_model, unload_model, scan_model +from sdkit.models import load_model, scan_model, unload_model, download_model, get_model_info_from_db +from sdkit.utils import hash_file_quick -KNOWN_MODEL_TYPES = ["stable-diffusion", "vae", "hypernetwork", "gfpgan", "realesrgan", "lora"] +KNOWN_MODEL_TYPES = [ + "stable-diffusion", + "vae", + "hypernetwork", + "gfpgan", + "realesrgan", + "lora", + "codeformer", +] MODEL_EXTENSIONS = { "stable-diffusion": [".ckpt", ".safetensors"], "vae": [".vae.pt", ".ckpt", ".safetensors"], @@ -15,14 +26,22 @@ MODEL_EXTENSIONS = { "gfpgan": [".pth"], "realesrgan": [".pth"], "lora": [".ckpt", ".safetensors"], + "codeformer": [".pth"], } DEFAULT_MODELS = { - "stable-diffusion": [ # needed to support the legacy installations - "custom-model", # only one custom model file was supported initially, creatively named 'custom-model' - "sd-v1-4", # Default fallback. + "stable-diffusion": [ + {"file_name": "sd-v1-4.ckpt", "model_id": "1.4"}, + ], + "gfpgan": [ + {"file_name": "GFPGANv1.4.pth", "model_id": "1.4"}, + ], + "realesrgan": [ + {"file_name": "RealESRGAN_x4plus.pth", "model_id": "x4plus"}, + {"file_name": "RealESRGAN_x4plus_anime_6B.pth", "model_id": "x4plus_anime_6"}, + ], + "vae": [ + {"file_name": "vae-ft-mse-840000-ema-pruned.ckpt", "model_id": "vae-ft-mse-840000-ema-pruned"}, ], - "gfpgan": ["GFPGANv1.3"], - "realesrgan": ["RealESRGAN_x4plus"], } MODELS_TO_LOAD_ON_START = ["stable-diffusion", "vae", "hypernetwork", "lora"] @@ -31,6 +50,8 @@ known_models = {} def init(): make_model_folders() + migrate_legacy_model_location() # if necessary + download_default_models_if_necessary() getModels() # run this once, to cache the picklescan results @@ -39,26 +60,42 @@ def load_default_models(context: Context): # init default model paths for model_type in MODELS_TO_LOAD_ON_START: - context.model_paths[model_type] = resolve_model_to_use(model_type=model_type) + context.model_paths[model_type] = resolve_model_to_use(model_type=model_type, fail_if_not_found=False) try: - load_model(context, model_type) + load_model( + context, + model_type, + scan_model=context.model_paths[model_type] != None + and not context.model_paths[model_type].endswith(".safetensors"), + ) + if model_type in context.model_load_errors: + del context.model_load_errors[model_type] except Exception as e: log.error(f"[red]Error while loading {model_type} model: {context.model_paths[model_type]}[/red]") - log.error(f"[red]Error: {e}[/red]") - log.error(f"[red]Consider removing the model from the model folder.[red]") + if "DefaultCPUAllocator: not enough memory" in str(e): + log.error( + f"[red]Your PC is low on system RAM. Please add some virtual memory (or swap space) by following the instructions at this link: https://www.ibm.com/docs/en/opw/8.2.0?topic=tuning-optional-increasing-paging-file-size-windows-computers[/red]" + ) + else: + log.exception(e) + del context.model_paths[model_type] + + context.model_load_errors[model_type] = str(e) # storing the entire Exception can lead to memory leaks def unload_all(context: Context): for model_type in KNOWN_MODEL_TYPES: unload_model(context, model_type) + if model_type in context.model_load_errors: + del context.model_load_errors[model_type] -def resolve_model_to_use(model_name: str = None, model_type: str = None): +def resolve_model_to_use(model_name: str = None, model_type: str = None, fail_if_not_found: bool = True): model_extensions = MODEL_EXTENSIONS.get(model_type, []) default_models = DEFAULT_MODELS.get(model_type, []) config = app.getConfig() - model_dirs = [os.path.join(app.MODELS_DIR, model_type), app.SD_DIR] + model_dir = os.path.join(app.MODELS_DIR, model_type) if not model_name: # When None try user configured model. # config = getConfig() if "model" in config and model_type in config["model"]: @@ -66,42 +103,42 @@ def resolve_model_to_use(model_name: str = None, model_type: str = None): if model_name: # Check models directory - models_dir_path = os.path.join(app.MODELS_DIR, model_type, model_name) + model_path = os.path.join(model_dir, model_name) + if os.path.exists(model_path): + return model_path for model_extension in model_extensions: - if os.path.exists(models_dir_path + model_extension): - return models_dir_path + model_extension + if os.path.exists(model_path + model_extension): + return model_path + model_extension if os.path.exists(model_name + model_extension): return os.path.abspath(model_name + model_extension) - # Default locations - if model_name in default_models: - default_model_path = os.path.join(app.SD_DIR, model_name) - for model_extension in model_extensions: - if os.path.exists(default_model_path + model_extension): - return default_model_path + model_extension - # Can't find requested model, check the default paths. - for default_model in default_models: - for model_dir in model_dirs: - default_model_path = os.path.join(model_dir, default_model) - for model_extension in model_extensions: - if os.path.exists(default_model_path + model_extension): - if model_name is not None: - log.warn( - f"Could not find the configured custom model {model_name}{model_extension}. Using the default one: {default_model_path}{model_extension}" - ) - return default_model_path + model_extension + if model_type == "stable-diffusion" and not fail_if_not_found: + for default_model in default_models: + default_model_path = os.path.join(model_dir, default_model["file_name"]) + if os.path.exists(default_model_path): + if model_name is not None: + log.warn( + f"Could not find the configured custom model {model_name}. Using the default one: {default_model_path}" + ) + return default_model_path - return None + if model_name and fail_if_not_found: + raise Exception(f"Could not find the desired model {model_name}! Is it present in the {model_dir} folder?") def reload_models_if_necessary(context: Context, task_data: TaskData): + face_fix_lower = task_data.use_face_correction.lower() if task_data.use_face_correction else "" + upscale_lower = task_data.use_upscale.lower() if task_data.use_upscale else "" + model_paths_in_req = { "stable-diffusion": task_data.use_stable_diffusion_model, "vae": task_data.use_vae_model, "hypernetwork": task_data.use_hypernetwork_model, - "gfpgan": task_data.use_face_correction, - "realesrgan": task_data.use_upscale, + "codeformer": task_data.use_face_correction if "codeformer" in face_fix_lower else None, + "gfpgan": task_data.use_face_correction if "gfpgan" in face_fix_lower else None, + "realesrgan": task_data.use_upscale if "realesrgan" in upscale_lower else None, + "latent_upscaler": True if "latent_upscaler" in upscale_lower else None, "nsfw_checker": True if task_data.block_nsfw else None, "lora": task_data.use_lora_model, } @@ -111,14 +148,28 @@ def reload_models_if_necessary(context: Context, task_data: TaskData): if context.model_paths.get(model_type) != path } - if set_vram_optimizations(context): # reload SD + if task_data.codeformer_upscale_faces: + if "realesrgan" not in models_to_reload and "realesrgan" not in context.models: + default_realesrgan = DEFAULT_MODELS["realesrgan"][0]["file_name"] + models_to_reload["realesrgan"] = resolve_model_to_use(default_realesrgan, "realesrgan") + elif "realesrgan" in models_to_reload and models_to_reload["realesrgan"] is None: + del models_to_reload["realesrgan"] # don't unload realesrgan + + if set_vram_optimizations(context) or set_clip_skip(context, task_data): # reload SD models_to_reload["stable-diffusion"] = model_paths_in_req["stable-diffusion"] for model_type, model_path_in_req in models_to_reload.items(): context.model_paths[model_type] = model_path_in_req action_fn = unload_model if context.model_paths[model_type] is None else load_model - action_fn(context, model_type, scan_model=False) # we've scanned them already + try: + action_fn(context, model_type, scan_model=False) # we've scanned them already + if model_type in context.model_load_errors: + del context.model_load_errors[model_type] + except Exception as e: + log.exception(e) + if action_fn == load_model: + context.model_load_errors[model_type] = str(e) # storing the entire Exception can lead to memory leaks def resolve_model_paths(task_data: TaskData): @@ -130,11 +181,49 @@ def resolve_model_paths(task_data: TaskData): task_data.use_lora_model = resolve_model_to_use(task_data.use_lora_model, model_type="lora") if task_data.use_face_correction: - task_data.use_face_correction = resolve_model_to_use(task_data.use_face_correction, "gfpgan") - if task_data.use_upscale: + if "gfpgan" in task_data.use_face_correction.lower(): + model_type = "gfpgan" + elif "codeformer" in task_data.use_face_correction.lower(): + model_type = "codeformer" + download_if_necessary("codeformer", "codeformer.pth", "codeformer-0.1.0") + + task_data.use_face_correction = resolve_model_to_use(task_data.use_face_correction, model_type) + if task_data.use_upscale and "realesrgan" in task_data.use_upscale.lower(): task_data.use_upscale = resolve_model_to_use(task_data.use_upscale, "realesrgan") +def fail_if_models_did_not_load(context: Context): + for model_type in KNOWN_MODEL_TYPES: + if model_type in context.model_load_errors: + e = context.model_load_errors[model_type] + raise Exception(f"Could not load the {model_type} model! Reason: " + e) + + +def download_default_models_if_necessary(): + for model_type, models in DEFAULT_MODELS.items(): + for model in models: + try: + download_if_necessary(model_type, model["file_name"], model["model_id"]) + except: + traceback.print_exc() + app.fail_and_die(fail_type="model_download", data=model_type) + + print(model_type, "model(s) found.") + + +def download_if_necessary(model_type: str, file_name: str, model_id: str): + model_path = os.path.join(app.MODELS_DIR, model_type, file_name) + expected_hash = get_model_info_from_db(model_type=model_type, model_id=model_id)["quick_hash"] + + other_models_exist = any_model_exists(model_type) + known_model_exists = os.path.exists(model_path) + known_model_is_corrupt = known_model_exists and hash_file_quick(model_path) != expected_hash + + if known_model_is_corrupt or (not other_models_exist and not known_model_exists): + print("> download", model_type, model_id) + download_model(model_type, model_id, download_base_dir=app.MODELS_DIR) + + def set_vram_optimizations(context: Context): config = app.getConfig() vram_usage_level = config.get("vram_usage_level", "balanced") @@ -146,6 +235,36 @@ def set_vram_optimizations(context: Context): return False +def migrate_legacy_model_location(): + 'Move the models inside the legacy "stable-diffusion" folder, to their respective folders' + + for model_type, models in DEFAULT_MODELS.items(): + for model in models: + file_name = model["file_name"] + legacy_path = os.path.join(app.SD_DIR, file_name) + if os.path.exists(legacy_path): + shutil.move(legacy_path, os.path.join(app.MODELS_DIR, model_type, file_name)) + + +def any_model_exists(model_type: str) -> bool: + extensions = MODEL_EXTENSIONS.get(model_type, []) + for ext in extensions: + if any(glob(f"{app.MODELS_DIR}/{model_type}/**/*{ext}", recursive=True)): + return True + + return False + + +def set_clip_skip(context: Context, task_data: TaskData): + clip_skip = task_data.clip_skip + + if clip_skip != context.clip_skip: + context.clip_skip = clip_skip + return True + + return False + + def make_model_folders(): for model_type in KNOWN_MODEL_TYPES: model_dir_path = os.path.join(app.MODELS_DIR, model_type) @@ -167,13 +286,23 @@ def is_malicious_model(file_path): if scan_result.issues_count > 0 or scan_result.infected_files > 0: log.warn( ":warning: [bold red]Scan %s: %d scanned, %d issue, %d infected.[/bold red]" - % (file_path, scan_result.scanned_files, scan_result.issues_count, scan_result.infected_files) + % ( + file_path, + scan_result.scanned_files, + scan_result.issues_count, + scan_result.infected_files, + ) ) return True else: log.debug( "Scan %s: [green]%d scanned, %d issue, %d infected.[/green]" - % (file_path, scan_result.scanned_files, scan_result.issues_count, scan_result.infected_files) + % ( + file_path, + scan_result.scanned_files, + scan_result.issues_count, + scan_result.infected_files, + ) ) return False except Exception as e: @@ -183,17 +312,12 @@ def is_malicious_model(file_path): def getModels(): models = { - "active": { - "stable-diffusion": "sd-v1-4", - "vae": "", - "hypernetwork": "", - "lora": "", - }, "options": { "stable-diffusion": ["sd-v1-4"], "vae": [], "hypernetwork": [], "lora": [], + "codeformer": ["codeformer"], }, } @@ -201,13 +325,13 @@ def getModels(): class MaliciousModelException(Exception): "Raised when picklescan reports a problem with a model" - pass def scan_directory(directory, suffixes, directoriesFirst: bool = True): nonlocal models_scanned tree = [] for entry in sorted( - os.scandir(directory), key=lambda entry: (entry.is_file() == directoriesFirst, entry.name.lower()) + os.scandir(directory), + key=lambda entry: (entry.is_file() == directoriesFirst, entry.name.lower()), ): if entry.is_file(): matching_suffix = list(filter(lambda s: entry.name.endswith(s), suffixes)) @@ -243,6 +367,7 @@ def getModels(): except MaliciousModelException as e: models["scan-error"] = e + log.info(f"[green]Scanning all model folders for models...[/]") # custom models listModels(model_type="stable-diffusion") listModels(model_type="vae") @@ -253,9 +378,4 @@ def getModels(): if models_scanned > 0: log.info(f"[green]Scanned {models_scanned} models. Nothing infected[/]") - # legacy - custom_weight_path = os.path.join(app.SD_DIR, "custom-model.ckpt") - if os.path.exists(custom_weight_path): - models["options"]["stable-diffusion"].append("custom-model") - return models diff --git a/ui/easydiffusion/renderer.py b/ui/easydiffusion/renderer.py index 8270d232..a57dfc6c 100644 --- a/ui/easydiffusion/renderer.py +++ b/ui/easydiffusion/renderer.py @@ -1,16 +1,26 @@ -import queue -import time import json import pprint +import queue +import time from easydiffusion import device_manager -from easydiffusion.types import TaskData, Response, Image as ResponseImage, UserInitiatedStop, GenerateImageRequest -from easydiffusion.utils import get_printable_request, save_images_to_disk, log - +from easydiffusion.types import GenerateImageRequest +from easydiffusion.types import Image as ResponseImage +from easydiffusion.types import Response, TaskData, UserInitiatedStop +from easydiffusion.model_manager import DEFAULT_MODELS, resolve_model_to_use +from easydiffusion.utils import get_printable_request, log, save_images_to_disk from sdkit import Context -from sdkit.generate import generate_images from sdkit.filter import apply_filters -from sdkit.utils import img_to_buffer, img_to_base64_str, latent_samples_to_images, diffusers_latent_samples_to_images +from sdkit.generate import generate_images +from sdkit.models import load_model +from sdkit.utils import ( + diffusers_latent_samples_to_images, + gc, + img_to_base64_str, + img_to_buffer, + latent_samples_to_images, + get_device_usage, +) context = Context() # thread-local """ @@ -25,24 +35,39 @@ def init(device): context.stop_processing = False context.temp_images = {} context.partial_x_samples = None + context.model_load_errors = {} + context.enable_codeformer = True from easydiffusion import app app_config = app.getConfig() - context.test_diffusers = app_config.get("test_diffusers", False) + context.test_diffusers = ( + app_config.get("test_diffusers", False) and app_config.get("update_branch", "main") != "main" + ) + + log.info("Device usage during initialization:") + get_device_usage(device, log_info=True, process_usage_only=False) device_manager.device_init(context, device) def make_images( - req: GenerateImageRequest, task_data: TaskData, data_queue: queue.Queue, task_temp_images: list, step_callback + req: GenerateImageRequest, + task_data: TaskData, + data_queue: queue.Queue, + task_temp_images: list, + step_callback, ): context.stop_processing = False print_task_info(req, task_data) images, seeds = make_images_internal(req, task_data, data_queue, task_temp_images, step_callback) - res = Response(req, task_data, images=construct_response(images, seeds, task_data, base_seed=req.seed)) + res = Response( + req, + task_data, + images=construct_response(images, seeds, task_data, base_seed=req.seed), + ) res = res.json() data_queue.put(json.dumps(res)) log.info("Task completed") @@ -51,16 +76,19 @@ def make_images( def print_task_info(req: GenerateImageRequest, task_data: TaskData): - req_str = pprint.pformat(get_printable_request(req)).replace("[", "\[") + req_str = pprint.pformat(get_printable_request(req, task_data)).replace("[", "\[") task_str = pprint.pformat(task_data.dict()).replace("[", "\[") log.info(f"request: {req_str}") log.info(f"task data: {task_str}") def make_images_internal( - req: GenerateImageRequest, task_data: TaskData, data_queue: queue.Queue, task_temp_images: list, step_callback + req: GenerateImageRequest, + task_data: TaskData, + data_queue: queue.Queue, + task_temp_images: list, + step_callback, ): - images, user_stopped = generate_images_internal( req, task_data, @@ -70,7 +98,8 @@ def make_images_internal( task_data.stream_image_progress, task_data.stream_image_progress_interval, ) - filtered_images = filter_images(task_data, images, user_stopped) + gc(context) + filtered_images = filter_images(req, task_data, images, user_stopped) if task_data.save_to_disk_path is not None: save_images_to_disk(images, filtered_images, req, task_data) @@ -126,28 +155,66 @@ def generate_images_internal( return images, user_stopped -def filter_images(task_data: TaskData, images: list, user_stopped): +def filter_images(req: GenerateImageRequest, task_data: TaskData, images: list, user_stopped): if user_stopped: return images - filters_to_apply = [] if task_data.block_nsfw: - filters_to_apply.append("nsfw_checker") - if task_data.use_face_correction and "gfpgan" in task_data.use_face_correction.lower(): - filters_to_apply.append("gfpgan") - if task_data.use_upscale and "realesrgan" in task_data.use_upscale.lower(): - filters_to_apply.append("realesrgan") + images = apply_filters(context, "nsfw_checker", images) - if len(filters_to_apply) == 0: - return images + if task_data.use_face_correction and "codeformer" in task_data.use_face_correction.lower(): + default_realesrgan = DEFAULT_MODELS["realesrgan"][0]["file_name"] + prev_realesrgan_path = None + if task_data.codeformer_upscale_faces and default_realesrgan not in context.model_paths["realesrgan"]: + prev_realesrgan_path = context.model_paths["realesrgan"] + context.model_paths["realesrgan"] = resolve_model_to_use(default_realesrgan, "realesrgan") + load_model(context, "realesrgan") - return apply_filters(context, filters_to_apply, images, scale=task_data.upscale_amount) + try: + images = apply_filters( + context, + "codeformer", + images, + upscale_faces=task_data.codeformer_upscale_faces, + codeformer_fidelity=task_data.codeformer_fidelity, + ) + finally: + if prev_realesrgan_path: + context.model_paths["realesrgan"] = prev_realesrgan_path + load_model(context, "realesrgan") + elif task_data.use_face_correction and "gfpgan" in task_data.use_face_correction.lower(): + images = apply_filters(context, "gfpgan", images) + + if task_data.use_upscale: + if "realesrgan" in task_data.use_upscale.lower(): + images = apply_filters(context, "realesrgan", images, scale=task_data.upscale_amount) + elif task_data.use_upscale == "latent_upscaler": + images = apply_filters( + context, + "latent_upscaler", + images, + scale=task_data.upscale_amount, + latent_upscaler_options={ + "prompt": req.prompt, + "negative_prompt": req.negative_prompt, + "seed": req.seed, + "num_inference_steps": task_data.latent_upscaler_steps, + "guidance_scale": 0, + }, + ) + + return images def construct_response(images: list, seeds: list, task_data: TaskData, base_seed: int): return [ ResponseImage( - data=img_to_base64_str(img, task_data.output_format, task_data.output_quality, task_data.output_lossless), + data=img_to_base64_str( + img, + task_data.output_format, + task_data.output_quality, + task_data.output_lossless, + ), seed=seed, ) for img, seed in zip(images, seeds) diff --git a/ui/easydiffusion/server.py b/ui/easydiffusion/server.py index e27f9c5b..d8940bb5 100644 --- a/ui/easydiffusion/server.py +++ b/ui/easydiffusion/server.py @@ -2,28 +2,31 @@ Notes: async endpoints always run on the main thread. Without they run on the thread pool. """ +import datetime +import mimetypes import os import traceback -import datetime from typing import List, Union +from easydiffusion import app, model_manager, task_manager +from easydiffusion.types import GenerateImageRequest, MergeRequest, TaskData +from easydiffusion.utils import log from fastapi import FastAPI, HTTPException from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, Extra from starlette.responses import FileResponse, JSONResponse, StreamingResponse -from pydantic import BaseModel - -from easydiffusion import app, model_manager, task_manager -from easydiffusion.types import TaskData, GenerateImageRequest, MergeRequest -from easydiffusion.utils import log - -import mimetypes +from pycloudflared import try_cloudflare log.info(f"started in {app.SD_DIR}") log.info(f"started at {datetime.datetime.now():%x %X}") server_api = FastAPI() -NOCACHE_HEADERS = {"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0"} +NOCACHE_HEADERS = { + "Cache-Control": "no-cache, no-store, must-revalidate", + "Pragma": "no-cache", + "Expires": "0", +} class NoCacheStaticFiles(StaticFiles): @@ -44,7 +47,7 @@ class NoCacheStaticFiles(StaticFiles): return super().is_not_modified(response_headers, request_headers) -class SetAppConfigRequest(BaseModel): +class SetAppConfigRequest(BaseModel, extra=Extra.allow): update_branch: str = None render_devices: Union[List[str], List[int], str, int] = None model_vae: str = None @@ -65,11 +68,17 @@ def init(): name="custom-thumbnails", ) - server_api.mount("/media", NoCacheStaticFiles(directory=os.path.join(app.SD_UI_DIR, "media")), name="media") + server_api.mount( + "/media", + NoCacheStaticFiles(directory=os.path.join(app.SD_UI_DIR, "media")), + name="media", + ) for plugins_dir, dir_prefix in app.UI_PLUGINS_SOURCES: server_api.mount( - f"/plugins/{dir_prefix}", NoCacheStaticFiles(directory=plugins_dir), name=f"plugins-{dir_prefix}" + f"/plugins/{dir_prefix}", + NoCacheStaticFiles(directory=plugins_dir), + name=f"plugins-{dir_prefix}", ) @server_api.post("/app_config") @@ -105,6 +114,14 @@ def init(): def get_image(task_id: int, img_id: int): return get_image_internal(task_id, img_id) + @server_api.post("/tunnel/cloudflare/start") + def start_cloudflare_tunnel(req: dict): + return start_cloudflare_tunnel_internal(req) + + @server_api.post("/tunnel/cloudflare/stop") + def stop_cloudflare_tunnel(req: dict): + return stop_cloudflare_tunnel_internal(req) + @server_api.get("/") def read_root(): return FileResponse(os.path.join(app.SD_UI_DIR, "index.html"), headers=NOCACHE_HEADERS) @@ -136,6 +153,10 @@ def set_app_config_internal(req: SetAppConfigRequest): config["test_diffusers"] = req.test_diffusers + for property, property_value in req.dict().items(): + if property_value is not None and property not in req.__fields__: + config[property] = property_value + try: app.setConfig(config) @@ -199,6 +220,8 @@ def ping_internal(session_id: str = None): session = task_manager.get_cached_session(session_id, update_ttl=True) response["tasks"] = {id(t): t.status for t in session.tasks} response["devices"] = task_manager.get_devices() + if cloudflare.address != None: + response["cloudflare"] = cloudflare.address return JSONResponse(response, headers=NOCACHE_HEADERS) @@ -242,8 +265,8 @@ def render_internal(req: dict): def model_merge_internal(req: dict): try: - from sdkit.train import merge_models from easydiffusion.utils.save_utils import filename_regex + from sdkit.train import merge_models mergeReq: MergeRequest = MergeRequest.parse_obj(req) @@ -251,7 +274,11 @@ def model_merge_internal(req: dict): model_manager.resolve_model_to_use(mergeReq.model0, "stable-diffusion"), model_manager.resolve_model_to_use(mergeReq.model1, "stable-diffusion"), mergeReq.ratio, - os.path.join(app.MODELS_DIR, "stable-diffusion", filename_regex.sub("_", mergeReq.out_path)), + os.path.join( + app.MODELS_DIR, + "stable-diffusion", + filename_regex.sub("_", mergeReq.out_path), + ), mergeReq.use_fp16, ) return JSONResponse({"status": "OK"}, headers=NOCACHE_HEADERS) @@ -306,3 +333,47 @@ def get_image_internal(task_id: int, img_id: int): return StreamingResponse(img_data, media_type="image/jpeg") except KeyError as e: raise HTTPException(status_code=500, detail=str(e)) + +#---- Cloudflare Tunnel ---- +class CloudflareTunnel: + def __init__(self): + config = app.getConfig() + self.urls = None + self.port = config.get("net", {}).get("listen_port") + + def start(self): + if self.port: + self.urls = try_cloudflare(self.port) + + def stop(self): + if self.urls: + try_cloudflare.terminate(self.port) + self.urls = None + + @property + def address(self): + if self.urls: + return self.urls.tunnel + else: + return None + +cloudflare = CloudflareTunnel() + +def start_cloudflare_tunnel_internal(req: dict): + try: + cloudflare.start() + log.info(f"- Started cloudflare tunnel. Using address: {cloudflare.address}") + return JSONResponse({"address":cloudflare.address}) + except Exception as e: + log.error(str(e)) + log.error(traceback.format_exc()) + return HTTPException(status_code=500, detail=str(e)) + +def stop_cloudflare_tunnel_internal(req: dict): + try: + cloudflare.stop() + except Exception as e: + log.error(str(e)) + log.error(traceback.format_exc()) + return HTTPException(status_code=500, detail=str(e)) + diff --git a/ui/easydiffusion/task_manager.py b/ui/easydiffusion/task_manager.py index 31fdaa6f..a91cd9c6 100644 --- a/ui/easydiffusion/task_manager.py +++ b/ui/easydiffusion/task_manager.py @@ -7,16 +7,18 @@ Notes: import json import traceback -TASK_TTL = 15 * 60 # seconds, Discard last session's task timeout +TASK_TTL = 30 * 60 # seconds, Discard last session's task timeout -import torch -import queue, threading, time, weakref +import queue +import threading +import time +import weakref from typing import Any, Hashable +import torch from easydiffusion import device_manager -from easydiffusion.types import TaskData, GenerateImageRequest +from easydiffusion.types import GenerateImageRequest, TaskData from easydiffusion.utils import log - from sdkit.utils import gc THREAD_NAME_PREFIX = "" @@ -167,7 +169,7 @@ class DataCache: raise Exception("DataCache.put" + ERR_LOCK_FAILED) try: self._base[key] = (self._get_ttl_time(ttl), value) - except Exception as e: + except Exception: log.error(traceback.format_exc()) return False else: @@ -264,7 +266,7 @@ def thread_get_next_task(): def thread_render(device): global current_state, current_state_error - from easydiffusion import renderer, model_manager + from easydiffusion import model_manager, renderer try: renderer.init(device) @@ -317,6 +319,9 @@ def thread_render(device): def step_callback(): global current_state_error + task_cache.keep(id(task), TASK_TTL) + session_cache.keep(task.task_data.session_id, TASK_TTL) + if ( isinstance(current_state_error, SystemExit) or isinstance(current_state_error, StopAsyncIteration) @@ -331,10 +336,15 @@ def thread_render(device): current_state = ServerStates.LoadingModel model_manager.resolve_model_paths(task.task_data) model_manager.reload_models_if_necessary(renderer.context, task.task_data) + model_manager.fail_if_models_did_not_load(renderer.context) current_state = ServerStates.Rendering task.response = renderer.make_images( - task.render_request, task.task_data, task.buffer_queue, task.temp_images, step_callback + task.render_request, + task.task_data, + task.buffer_queue, + task.temp_images, + step_callback, ) # Before looping back to the generator, mark cache as still alive. task_cache.keep(id(task), TASK_TTL) diff --git a/ui/easydiffusion/types.py b/ui/easydiffusion/types.py index bbec0afa..abf8db29 100644 --- a/ui/easydiffusion/types.py +++ b/ui/easydiffusion/types.py @@ -1,6 +1,7 @@ -from pydantic import BaseModel from typing import Any +from pydantic import BaseModel + class GenerateImageRequest(BaseModel): prompt: str = "" @@ -22,6 +23,7 @@ class GenerateImageRequest(BaseModel): sampler_name: str = None # "ddim", "plms", "heun", "euler", "euler_a", "dpm2", "dpm2_a", "lms" hypernetwork_strength: float = 0 lora_alpha: float = 0 + tiling: str = "none" # "none", "x", "y", "xy" class TaskData(BaseModel): @@ -31,8 +33,9 @@ class TaskData(BaseModel): vram_usage_level: str = "balanced" # or "low" or "medium" use_face_correction: str = None # or "GFPGANv1.3" - use_upscale: str = None # or "RealESRGAN_x4plus" or "RealESRGAN_x4plus_anime_6B" + use_upscale: str = None # or "RealESRGAN_x4plus" or "RealESRGAN_x4plus_anime_6B" or "latent_upscaler" upscale_amount: int = 4 # or 2 + latent_upscaler_steps: int = 10 use_stable_diffusion_model: str = "sd-v1-4" # use_stable_diffusion_config: str = "v1-inference" use_vae_model: str = None @@ -47,6 +50,9 @@ class TaskData(BaseModel): metadata_output_format: str = "txt" # or "json" stream_image_progress: bool = False stream_image_progress_interval: int = 5 + clip_skip: bool = False + codeformer_upscale_faces: bool = False + codeformer_fidelity: float = 0.5 class MergeRequest(BaseModel): diff --git a/ui/easydiffusion/utils/save_utils.py b/ui/easydiffusion/utils/save_utils.py index 6affac78..ff2906a6 100644 --- a/ui/easydiffusion/utils/save_utils.py +++ b/ui/easydiffusion/utils/save_utils.py @@ -1,42 +1,130 @@ import os -import time import re +import time +from datetime import datetime +from functools import reduce -from easydiffusion.types import TaskData, GenerateImageRequest - -from sdkit.utils import save_images, save_dicts +from easydiffusion import app +from easydiffusion.types import GenerateImageRequest, TaskData from numpy import base_repr +from sdkit.utils import save_dicts, save_images filename_regex = re.compile("[^a-zA-Z0-9._-]") +img_number_regex = re.compile("([0-9]{5,})") # keep in sync with `ui/media/js/dnd.js` TASK_TEXT_MAPPING = { "prompt": "Prompt", + "negative_prompt": "Negative Prompt", + "seed": "Seed", + "use_stable_diffusion_model": "Stable Diffusion model", + "clip_skip": "Clip Skip", + "use_vae_model": "VAE model", + "sampler_name": "Sampler", "width": "Width", "height": "Height", - "seed": "Seed", "num_inference_steps": "Steps", "guidance_scale": "Guidance Scale", "prompt_strength": "Prompt Strength", + "use_lora_model": "LoRA model", + "lora_alpha": "LoRA Strength", + "use_hypernetwork_model": "Hypernetwork model", + "hypernetwork_strength": "Hypernetwork Strength", + "tiling": "Seamless Tiling", "use_face_correction": "Use Face Correction", "use_upscale": "Use Upscaling", "upscale_amount": "Upscale By", - "sampler_name": "Sampler", - "negative_prompt": "Negative Prompt", - "use_stable_diffusion_model": "Stable Diffusion model", - "use_vae_model": "VAE model", - "use_hypernetwork_model": "Hypernetwork model", - "hypernetwork_strength": "Hypernetwork Strength", - "use_lora_model": "LoRA model", - # "lora_alpha": "LoRA Strength", + "latent_upscaler_steps": "Latent Upscaler Steps" } +time_placeholders = { + "$yyyy": "%Y", + "$MM": "%m", + "$dd": "%d", + "$HH": "%H", + "$mm": "%M", + "$ss": "%S", +} + +other_placeholders = { + "$id": lambda req, task_data: filename_regex.sub("_", task_data.session_id), + "$p": lambda req, task_data: filename_regex.sub("_", req.prompt)[:50], + "$s": lambda req, task_data: str(req.seed), +} + + +class ImageNumber: + _factory = None + _evaluated = False + + def __init__(self, factory): + self._factory = factory + self._evaluated = None + + def __call__(self) -> int: + if self._evaluated is None: + self._evaluated = self._factory() + return self._evaluated + + +def format_placeholders(format: str, req: GenerateImageRequest, task_data: TaskData, now=None): + if now is None: + now = time.time() + + for placeholder, time_format in time_placeholders.items(): + if placeholder in format: + format = format.replace(placeholder, datetime.fromtimestamp(now).strftime(time_format)) + for placeholder, replace_func in other_placeholders.items(): + if placeholder in format: + format = format.replace(placeholder, replace_func(req, task_data)) + + return format + + +def format_folder_name(format: str, req: GenerateImageRequest, task_data: TaskData): + format = format_placeholders(format, req, task_data) + return filename_regex.sub("_", format) + + +def format_file_name( + format: str, + req: GenerateImageRequest, + task_data: TaskData, + now: float, + batch_file_number: int, + folder_img_number: ImageNumber, +): + format = format_placeholders(format, req, task_data, now) + + if "$n" in format: + format = format.replace("$n", f"{folder_img_number():05}") + + if "$tsb64" in format: + img_id = base_repr(int(now * 10000), 36)[-7:] + base_repr( + int(batch_file_number), 36 + ) # Base 36 conversion, 0-9, A-Z + format = format.replace("$tsb64", img_id) + + if "$ts" in format: + format = format.replace("$ts", str(int(now * 1000) + batch_file_number)) + + return filename_regex.sub("_", format) + def save_images_to_disk(images: list, filtered_images: list, req: GenerateImageRequest, task_data: TaskData): now = time.time() - save_dir_path = os.path.join(task_data.save_to_disk_path, filename_regex.sub("_", task_data.session_id)) + app_config = app.getConfig() + folder_format = app_config.get("folder_format", "$id") + save_dir_path = os.path.join(task_data.save_to_disk_path, format_folder_name(folder_format, req, task_data)) metadata_entries = get_metadata_entries_for_request(req, task_data) - make_filename = make_filename_callback(req, now=now) + file_number = calculate_img_number(save_dir_path, task_data) + make_filename = make_filename_callback( + app_config.get("filename_format", "$p_$tsb64"), + req, + task_data, + file_number, + now=now, + ) if task_data.show_only_filtered_image or filtered_images is images: save_images( @@ -47,16 +135,25 @@ def save_images_to_disk(images: list, filtered_images: list, req: GenerateImageR output_quality=task_data.output_quality, output_lossless=task_data.output_lossless, ) - if task_data.metadata_output_format.lower() in ["json", "txt", "embed"]: - save_dicts( - metadata_entries, - save_dir_path, - file_name=make_filename, - output_format=task_data.metadata_output_format, - file_format=task_data.output_format, - ) + if task_data.metadata_output_format: + for metadata_output_format in task_data.metadata_output_format.split(","): + if metadata_output_format.lower() in ["json", "txt", "embed"]: + save_dicts( + metadata_entries, + save_dir_path, + file_name=make_filename, + output_format=metadata_output_format, + file_format=task_data.output_format, + ) else: - make_filter_filename = make_filename_callback(req, now=now, suffix="filtered") + make_filter_filename = make_filename_callback( + app_config.get("filename_format", "$p_$tsb64"), + req, + task_data, + file_number, + now=now, + suffix="filtered", + ) save_images( images, @@ -74,44 +171,23 @@ def save_images_to_disk(images: list, filtered_images: list, req: GenerateImageR output_quality=task_data.output_quality, output_lossless=task_data.output_lossless, ) - if task_data.metadata_output_format.lower() in ["json", "txt", "embed"]: - save_dicts( - metadata_entries, - save_dir_path, - file_name=make_filter_filename, - output_format=task_data.metadata_output_format, - file_format=task_data.output_format, - ) + if task_data.metadata_output_format: + for metadata_output_format in task_data.metadata_output_format.split(","): + if metadata_output_format.lower() in ["json", "txt", "embed"]: + save_dicts( + metadata_entries, + save_dir_path, + file_name=make_filter_filename, + output_format=task_data.metadata_output_format, + file_format=task_data.output_format, + ) def get_metadata_entries_for_request(req: GenerateImageRequest, task_data: TaskData): - metadata = get_printable_request(req) - metadata.update( - { - "use_stable_diffusion_model": task_data.use_stable_diffusion_model, - "use_vae_model": task_data.use_vae_model, - "use_hypernetwork_model": task_data.use_hypernetwork_model, - "use_lora_model": task_data.use_lora_model, - "use_face_correction": task_data.use_face_correction, - "use_upscale": task_data.use_upscale, - } - ) - if metadata["use_upscale"] is not None: - metadata["upscale_amount"] = task_data.upscale_amount - if task_data.use_hypernetwork_model is None: - del metadata["hypernetwork_strength"] - if task_data.use_lora_model is None: - if "lora_alpha" in metadata: - del metadata["lora_alpha"] - - from easydiffusion import app - - app_config = app.getConfig() - if not app_config.get("test_diffusers", False) and "use_lora_model" in metadata: - del metadata["use_lora_model"] + metadata = get_printable_request(req, task_data) # if text, format it in the text format expected by the UI - is_txt_format = task_data.metadata_output_format.lower() == "txt" + is_txt_format = task_data.metadata_output_format and "txt" in task_data.metadata_output_format.lower().split(",") if is_txt_format: metadata = {TASK_TEXT_MAPPING[key]: val for key, val in metadata.items() if key in TASK_TEXT_MAPPING} @@ -122,25 +198,101 @@ def get_metadata_entries_for_request(req: GenerateImageRequest, task_data: TaskD return entries -def get_printable_request(req: GenerateImageRequest): - metadata = req.dict() - del metadata["init_image"] - del metadata["init_image_mask"] - if req.init_image is None: +def get_printable_request(req: GenerateImageRequest, task_data: TaskData): + req_metadata = req.dict() + task_data_metadata = task_data.dict() + + # Save the metadata in the order defined in TASK_TEXT_MAPPING + metadata = {} + for key in TASK_TEXT_MAPPING.keys(): + if key in req_metadata: + metadata[key] = req_metadata[key] + elif key in task_data_metadata: + metadata[key] = task_data_metadata[key] + + # Clean up the metadata + if req.init_image is None and "prompt_strength" in metadata: del metadata["prompt_strength"] + if task_data.use_upscale is None and "upscale_amount" in metadata: + del metadata["upscale_amount"] + if task_data.use_hypernetwork_model is None and "hypernetwork_strength" in metadata: + del metadata["hypernetwork_strength"] + if task_data.use_lora_model is None and "lora_alpha" in metadata: + del metadata["lora_alpha"] + if task_data.use_upscale != "latent_upscaler" and "latent_upscaler_steps" in metadata: + del metadata["latent_upscaler_steps"] + + app_config = app.getConfig() + if not app_config.get("test_diffusers", False): + for key in (x for x in ["use_lora_model", "lora_alpha", "clip_skip", "tiling", "latent_upscaler_steps"] if x in metadata): + del metadata[key] + return metadata -def make_filename_callback(req: GenerateImageRequest, suffix=None, now=None): +def make_filename_callback( + filename_format: str, + req: GenerateImageRequest, + task_data: TaskData, + folder_img_number: int, + suffix=None, + now=None, +): if now is None: now = time.time() def make_filename(i): - img_id = base_repr(int(now * 10000), 36)[-7:] + base_repr(int(i),36) # Base 36 conversion, 0-9, A-Z - - prompt_flattened = filename_regex.sub("_", req.prompt)[:50] - name = f"{prompt_flattened}_{img_id}" + name = format_file_name(filename_format, req, task_data, now, i, folder_img_number) name = name if suffix is None else f"{name}_{suffix}" + return name return make_filename + + +def _calculate_img_number(save_dir_path: str, task_data: TaskData): + def get_highest_img_number(accumulator: int, file: os.DirEntry) -> int: + if not file.is_file: + return accumulator + + if len(list(filter(lambda e: file.name.endswith(e), app.IMAGE_EXTENSIONS))) == 0: + return accumulator + + get_highest_img_number.number_of_images = get_highest_img_number.number_of_images + 1 + + number_match = img_number_regex.match(file.name) + if not number_match: + return accumulator + + file_number = number_match.group().lstrip("0") + + # Handle 00000 + return int(file_number) if file_number else 0 + + get_highest_img_number.number_of_images = 0 + + highest_file_number = -1 + + if os.path.isdir(save_dir_path): + existing_files = list(os.scandir(save_dir_path)) + highest_file_number = reduce(get_highest_img_number, existing_files, -1) + + calculated_img_number = max(highest_file_number, get_highest_img_number.number_of_images - 1) + + if task_data.session_id in _calculate_img_number.session_img_numbers: + calculated_img_number = max( + _calculate_img_number.session_img_numbers[task_data.session_id], + calculated_img_number, + ) + + calculated_img_number = calculated_img_number + 1 + + _calculate_img_number.session_img_numbers[task_data.session_id] = calculated_img_number + return calculated_img_number + + +_calculate_img_number.session_img_numbers = {} + + +def calculate_img_number(save_dir_path: str, task_data: TaskData): + return ImageNumber(lambda: _calculate_img_number(save_dir_path, task_data)) diff --git a/ui/hotfix/9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142 b/ui/hotfix/9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142 deleted file mode 100644 index 2c19f666..00000000 --- a/ui/hotfix/9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142 +++ /dev/null @@ -1,171 +0,0 @@ -{ - "_name_or_path": "clip-vit-large-patch14/", - "architectures": [ - "CLIPModel" - ], - "initializer_factor": 1.0, - "logit_scale_init_value": 2.6592, - "model_type": "clip", - "projection_dim": 768, - "text_config": { - "_name_or_path": "", - "add_cross_attention": false, - "architectures": null, - "attention_dropout": 0.0, - "bad_words_ids": null, - "bos_token_id": 0, - "chunk_size_feed_forward": 0, - "cross_attention_hidden_size": null, - "decoder_start_token_id": null, - "diversity_penalty": 0.0, - "do_sample": false, - "dropout": 0.0, - "early_stopping": false, - "encoder_no_repeat_ngram_size": 0, - "eos_token_id": 2, - "finetuning_task": null, - "forced_bos_token_id": null, - "forced_eos_token_id": null, - "hidden_act": "quick_gelu", - "hidden_size": 768, - "id2label": { - "0": "LABEL_0", - "1": "LABEL_1" - }, - "initializer_factor": 1.0, - "initializer_range": 0.02, - "intermediate_size": 3072, - "is_decoder": false, - "is_encoder_decoder": false, - "label2id": { - "LABEL_0": 0, - "LABEL_1": 1 - }, - "layer_norm_eps": 1e-05, - "length_penalty": 1.0, - "max_length": 20, - "max_position_embeddings": 77, - "min_length": 0, - "model_type": "clip_text_model", - "no_repeat_ngram_size": 0, - "num_attention_heads": 12, - "num_beam_groups": 1, - "num_beams": 1, - "num_hidden_layers": 12, - "num_return_sequences": 1, - "output_attentions": false, - "output_hidden_states": false, - "output_scores": false, - "pad_token_id": 1, - "prefix": null, - "problem_type": null, - "projection_dim" : 768, - "pruned_heads": {}, - "remove_invalid_values": false, - "repetition_penalty": 1.0, - "return_dict": true, - "return_dict_in_generate": false, - "sep_token_id": null, - "task_specific_params": null, - "temperature": 1.0, - "tie_encoder_decoder": false, - "tie_word_embeddings": true, - "tokenizer_class": null, - "top_k": 50, - "top_p": 1.0, - "torch_dtype": null, - "torchscript": false, - "transformers_version": "4.16.0.dev0", - "use_bfloat16": false, - "vocab_size": 49408 - }, - "text_config_dict": { - "hidden_size": 768, - "intermediate_size": 3072, - "num_attention_heads": 12, - "num_hidden_layers": 12, - "projection_dim": 768 - }, - "torch_dtype": "float32", - "transformers_version": null, - "vision_config": { - "_name_or_path": "", - "add_cross_attention": false, - "architectures": null, - "attention_dropout": 0.0, - "bad_words_ids": null, - "bos_token_id": null, - "chunk_size_feed_forward": 0, - "cross_attention_hidden_size": null, - "decoder_start_token_id": null, - "diversity_penalty": 0.0, - "do_sample": false, - "dropout": 0.0, - "early_stopping": false, - "encoder_no_repeat_ngram_size": 0, - "eos_token_id": null, - "finetuning_task": null, - "forced_bos_token_id": null, - "forced_eos_token_id": null, - "hidden_act": "quick_gelu", - "hidden_size": 1024, - "id2label": { - "0": "LABEL_0", - "1": "LABEL_1" - }, - "image_size": 224, - "initializer_factor": 1.0, - "initializer_range": 0.02, - "intermediate_size": 4096, - "is_decoder": false, - "is_encoder_decoder": false, - "label2id": { - "LABEL_0": 0, - "LABEL_1": 1 - }, - "layer_norm_eps": 1e-05, - "length_penalty": 1.0, - "max_length": 20, - "min_length": 0, - "model_type": "clip_vision_model", - "no_repeat_ngram_size": 0, - "num_attention_heads": 16, - "num_beam_groups": 1, - "num_beams": 1, - "num_hidden_layers": 24, - "num_return_sequences": 1, - "output_attentions": false, - "output_hidden_states": false, - "output_scores": false, - "pad_token_id": null, - "patch_size": 14, - "prefix": null, - "problem_type": null, - "projection_dim" : 768, - "pruned_heads": {}, - "remove_invalid_values": false, - "repetition_penalty": 1.0, - "return_dict": true, - "return_dict_in_generate": false, - "sep_token_id": null, - "task_specific_params": null, - "temperature": 1.0, - "tie_encoder_decoder": false, - "tie_word_embeddings": true, - "tokenizer_class": null, - "top_k": 50, - "top_p": 1.0, - "torch_dtype": null, - "torchscript": false, - "transformers_version": "4.16.0.dev0", - "use_bfloat16": false - }, - "vision_config_dict": { - "hidden_size": 1024, - "intermediate_size": 4096, - "num_attention_heads": 16, - "num_hidden_layers": 24, - "patch_size": 14, - "projection_dim": 768 - } -} diff --git a/ui/index.html b/ui/index.html index 0bf90733..77337505 100644 --- a/ui/index.html +++ b/ui/index.html @@ -16,6 +16,7 @@ + @@ -30,7 +31,7 @@

Easy Diffusion - v2.5.30 + v2.5.41

@@ -60,12 +61,42 @@ +
+
+
+
+

Image Modifiers

+ (drawing style, camera, etc.) +
+
+ + + Add Custom Modifiers + + + + +
+
+
+
+ + + Expand Categories + +
+
+
+
@@ -102,7 +133,7 @@
- +
@@ -133,15 +164,18 @@ - Click to learn more about custom models + Click to learn more about custom models - - + + + + + Click to learn more about Clip Skip + + + - Click to learn more about VAEs + Click to learn more about VAEs - Click to learn more about samplers + Click to learn more about samplers
- + - -
+ + + -2 2   +
+ - +
+ + + Click to learn more about Seamless Tiling + - - + + @@ -249,50 +297,43 @@
- -
-

- Image Modifiers (art styles, tags etc) - - - Add Custom Modifiers - - -

-
-
- - -   - - -
-
-
+
+ Type a prompt and press the "Make Image" button.

You can set an "Initial Image" if you want to guide the AI.

+ You can also add modifiers like "Realistic", "Pencil Sketch", "ArtStation" etc by browsing through the "Image Modifiers" section + and selecting the desired modifiers.

+ Click "Image Settings" for additional settings like seed, image size, number of images to generate etc.

Enjoy! :) +
@@ -326,22 +367,22 @@
-
- Type a prompt and press the "Make Image" button.

You can set an "Initial Image" if you want to guide the AI.

- You can also add modifiers like "Realistic", "Pencil Sketch", "ArtStation" etc by browsing through the "Image Modifiers" section - and selecting the desired modifiers.

- Click "Image Settings" for additional settings like seed, image size, number of images to generate etc.

Enjoy! :) -
@@ -399,6 +440,53 @@
+ @@ -481,10 +579,10 @@ @@ -493,13 +591,13 @@ - + @@ -512,15 +610,18 @@ async function init() { await loadUIPlugins() await loadModifiers() await getSystemInfo() + await initPlugins() SD.init({ events: { statusChange: setServerStatus, - idle: onIdle + idle: onIdle, + ping: tunnelUpdate } }) + splashScreen() - playSound() + // playSound() } init() diff --git a/ui/media/css/auto-save.css b/ui/media/css/auto-save.css index 80aa48d8..119a7e10 100644 --- a/ui/media/css/auto-save.css +++ b/ui/media/css/auto-save.css @@ -69,13 +69,15 @@ } .parameters-table > div:first-child { - border-radius: 12px 12px 0px 0px; + border-top-left-radius: 12px; + border-top-right-radius: 12px; } .parameters-table > div:last-child { - border-radius: 0px 0px 12px 12px; + border-bottom-left-radius: 12px; + border-bottom-right-radius: 12px; } .parameters-table .fa-fire { color: #F7630C; -} \ No newline at end of file +} diff --git a/ui/media/css/fonts.css b/ui/media/css/fonts.css index 8bd4f5d5..6a1fbbae 100644 --- a/ui/media/css/fonts.css +++ b/ui/media/css/fonts.css @@ -3,7 +3,7 @@ font-family: 'Work Sans'; font-style: normal; font-weight: 400; - src: local(''), + src: local('Work Sans'), url('/media/fonts/work-sans-v18-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('/media/fonts/work-sans-v18-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } @@ -13,7 +13,7 @@ font-family: 'Work Sans'; font-style: normal; font-weight: 600; - src: local(''), + src: local('Work Sans'), url('/media/fonts/work-sans-v18-latin-600.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('/media/fonts/work-sans-v18-latin-600.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } @@ -23,7 +23,7 @@ font-family: 'Work Sans'; font-style: normal; font-weight: 700; - src: local(''), + src: local('Work Sans'), url('/media/fonts/work-sans-v18-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('/media/fonts/work-sans-v18-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } @@ -33,8 +33,8 @@ font-family: 'Work Sans'; font-style: normal; font-weight: 800; - src: local(''), + src: local('Work Sans'), url('/media/fonts/work-sans-v18-latin-800.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('/media/fonts/work-sans-v18-latin-800.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } - \ No newline at end of file + diff --git a/ui/media/css/image-editor.css b/ui/media/css/image-editor.css index ea8112e3..ba046383 100644 --- a/ui/media/css/image-editor.css +++ b/ui/media/css/image-editor.css @@ -96,7 +96,7 @@ .editor-controls-center { /* background: var(--background-color2); */ - flex: 1; + flex: 0; display: flex; justify-content: center; align-items: center; @@ -105,6 +105,8 @@ .editor-controls-center > div { position: relative; background: black; + margin: 20pt; + margin-top: 40pt; } .editor-controls-center canvas { @@ -164,8 +166,10 @@ margin: var(--popup-margin); padding: var(--popup-padding); min-height: calc(99h - (2 * var(--popup-margin))); - max-width: none; + max-width: fit-content; min-width: fit-content; + margin-left: auto; + margin-right: auto; } .image-editor-popup h1 { diff --git a/ui/media/css/image-modal.css b/ui/media/css/image-modal.css index 1001807c..64096003 100644 --- a/ui/media/css/image-modal.css +++ b/ui/media/css/image-modal.css @@ -70,6 +70,14 @@ max-height: calc(100vh - (var(--popup-padding) * 2) - 4px); } +#viewFullSizeImgModal img:not(.natural-zoom) { + cursor: grab; +} + +#viewFullSizeImgModal .grabbing img:not(.natural-zoom) { + cursor: grabbing; +} + #viewFullSizeImgModal .content > div::-webkit-scrollbar-track, #viewFullSizeImgModal .content > div::-webkit-scrollbar-corner { background: rgba(0, 0, 0, .5) } diff --git a/ui/media/css/main.css b/ui/media/css/main.css index 88b8fc58..771169b3 100644 --- a/ui/media/css/main.css +++ b/ui/media/css/main.css @@ -211,10 +211,6 @@ code { #makeImage { border-radius: 6px; } -#editor-modifiers h5 { - padding: 5pt 0; - margin: 0; -} #makeImage { flex: 0 0 70px; background: var(--accent-color); @@ -238,6 +234,10 @@ code { #stopImage:hover { background: rgb(177, 27, 0); } +#undo { + float: right; + margin-left: 5px; +} div#render-buttons { gap: 3px; @@ -280,14 +280,193 @@ button#resume { .collapsible:not(.active) ~ .collapsible-content { display: none !important; } +#image-modifier-dropdown { + margin-left: 1em; + position: relative; + cursor: pointer; +} +#image-modifier-dropdown[data-active="true"]::before { + content: "➖"; +} +#image-modifier-dropdown[data-active="false"]::before { + content: "➕"; +} #editor-modifiers { - overflow-y: auto; + max-width: 75vw; + min-width: 50vw; + max-height: fit-content; + overflow-y: hidden; overflow-x: hidden; + display: none; + background: var(--background-color1); + border: solid 1px var(--background-color3); + z-index: 999; + border-radius: 6px; + box-shadow: 0px 0px 30px black; + border: 2px solid rgb(255 255 255 / 10%); +} +#editor-modifiers.active { + display: flex; + flex-direction: column; + position: absolute; + left: 5vw; +} +.modifiers-maximized { + position: fixed !important; + top: 0 !important; + bottom: 0px !important; + left: 0px !important; + right: 0px !important; + max-width: unset !important; + max-height: unset !important; + border: 0px !important; + border-radius: 0px !important; +} +.modifiers-maximized #editor-modifiers-entries { + max-height: 100%; + flex: 1; +} +#editor-modifiers-header { + background-color: var(--background-color4); + padding: 0.5em; + border-bottom: 1px solid rgb(255 255 255 / 10%); + display: flex; + justify-content: space-between; + align-items: center; + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; +} +#editor-modifiers-subheader { + background-color: var(--background-color4); + padding: 0.5em; + border-bottom: 1px solid rgb(255 255 255 / 10%); + display: flex; + align-items: center; + grid-gap: 0.8em; + flex-direction: row; + position: relative; + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + transition: all 0.1s ease; +} +#editor-modifiers-subheader::before { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(255, 255, 255, 0.02); + opacity: 1; + pointer-events: none; +} +#modifiers-header-left { + display: flex; + flex-direction: column; + grid-gap: 0.1em; +} +#modifiers-header-left span { + font-size: 0.8em; + color: rgb(127 127 127); + font-weight: 200; +} +#modifiers-header-right { + display: flex; + align-items: center; + align-content: center; + justify-content: center; + grid-gap: 0.8em; + margin-right: 0.3em; +} + +#editor-modifiers-subheader i, +#modifiers-header-right i { + cursor: pointer; + margin: 0; + padding: 0; +} +#modifiers-header-right .section-button, +#editor-modifiers-subheader .section-button { + margin-top: 0.3em; +} +#modifiers-action-collapsibles-btn { + display: flex; + grid-gap: 0.5em; + cursor: pointer; +} +.modifiers-action-text { + font-size: 0.8em; + color: rgb(192 192 192); +} +#modifiers-expand-btn { + z-index: 2; +} +#modifiers-expand-btn .simple-tooltip { + background-color: var(--background-color3); + border-radius: 50px; +} +.modifier-category .collapsible { + position: relative; +} +.modifier-category .collapsible::after { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(255, 255, 255, 0.1); + opacity: 0; + transition: opacity 0.1s ease; + pointer-events: none; +} +.modifier-category:hover .collapsible::after { + opacity: 1; + pointer-events: none; +} +#editor-modifiers-entries { + overflow: auto scroll; + max-height: 50vh; + height: fit-content; + margin-bottom: 0.1em; + padding-left: 0px; +} +#editor-modifiers-entries .collapsible { + transition: opacity 0.1s ease; + padding-left: 0.5em; +} +#editor-modifiers-entries .modifier-category:nth-child(odd) .collapsible::before { + content: ''; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(255, 255, 255, 0.02); + opacity: 1; + pointer-events: none; } #editor-modifiers .editor-modifiers-leaf { padding-top: 10pt; padding-bottom: 10pt; } +#editor-modifiers h5 { + padding: 5pt 0; + margin: 0; + position: sticky; + top: -2px; + z-index: 10; + background-color: var(--background-color3); + border-bottom: 1px solid rgb(255 255 255 / 4%); + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; +} img { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.15), 0 6px 20px 0 rgba(0, 0, 0, 0.15); } @@ -306,6 +485,9 @@ div.img-preview img { margin-top: 5pt; display: none; } +#editor-inputs-tags-list { + max-height: 30em; +} #server-status { position: absolute; right: 16px; @@ -572,6 +754,11 @@ div.img-preview img { margin-bottom: 5pt; margin-top: 5pt; } + +.taskConfigContainer { + display: inline; +} + .img-batch { display: inline; } @@ -770,7 +957,6 @@ input::file-selector-button { height: 19px; } - .input-toggle { display: inline-block; position: relative; @@ -1074,6 +1260,7 @@ input::file-selector-button { /* POPUPS */ .popup:not(.active) { visibility: hidden; + overflow-x: hidden; /* fix overflow from body */ opacity: 0; } @@ -1283,6 +1470,49 @@ body.wait-pause { 100% { border: solid 12px var(--accent-color); } } +#splash-screen div { + text-align: left; + max-width: 70vw; +} + +#splash-screen .splash-img { + float: right; + box-shadow: none; + margin-left: 6px; +} + +#splash-screen tt { + font-family: monospace; + background: var(--input-background-color); + padding: 1px 4px 1px 4px; + border-radius: 5px; +} + +#splash-screen li { + margin-bottom: 6px; +} + +#splash-screen a +{ + color: #ccf; + text-decoration: none; + font-weight: bold; +} + +#splash-screen a[href^="http"]::after, +#splash-screen a[href^="https://"]::after +{ + content: ""; + width: 11px; + height: 11px; + margin-left: 4px; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='lightblue' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5z'/%3E%3Cpath fill-rule='evenodd' d='M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0v-5z'/%3E%3C/svg%3E"); + background-position: center; + background-repeat: no-repeat; + background-size: contain; + display: inline-block; +} + .jconfirm.jconfirm-modern .jconfirm-box div.jconfirm-title-c { color: var(--button-text-color); } @@ -1293,3 +1523,83 @@ body.wait-pause { .displayNone { display:none !important; } + +.sub-settings { + padding-top: 3pt; + padding-bottom: 3pt; + padding-left: 5pt; +} + +#cloudflare-address { + background-color: var(--background-color3); + padding: 6px; + border-radius: var(--input-border-radius); + border: var(--input-border-size) solid var(--input-border-color); + margin-top: 0.2em; + margin-bottom: 0.2em; + display: inline-block; +} + +#copy-cloudflare-address { + padding: 4px 8px; + margin-left: 0.5em; +} + +.expandedSettingRow { + background: var(--background-color1); + width: 95%; + border-radius: 4pt; + margin-top: 5pt; + margin-bottom: 3pt; +} + +/* TOAST NOTIFICATIONS */ +.toast-notification { + position: fixed; + bottom: 10px; + right: -300px; + width: 300px; + background-color: #333; + color: #fff; + padding: 10px 20px; + border-radius: 5px; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); + z-index: 9999; + animation: slideInRight 0.5s ease forwards; + transition: bottom 0.5s ease; /* Add a transition to smoothly reposition the toasts */ +} + +.toast-notification-error { + color: red; +} + +@keyframes slideInRight { + from { + right: -300px; + } + to { + right: 10px; + } +} + +.toast-notification.hide { + animation: slideOutRight 0.5s ease forwards; +} + +@keyframes slideOutRight { + from { + right: 10px; + } + to { + right: -300px; + } +} + +@keyframes slideDown { + from { + bottom: 10px; + } + to { + bottom: 0; + } +} diff --git a/ui/media/css/modifier-thumbnails.css b/ui/media/css/modifier-thumbnails.css index 9b462e57..02b91fce 100644 --- a/ui/media/css/modifier-thumbnails.css +++ b/ui/media/css/modifier-thumbnails.css @@ -1,14 +1,16 @@ .modifier-card { + position: relative; + box-sizing: content-box; /* fixes border misalignment */ box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); transition: 0.1s; border-radius: 7px; margin: 3pt 3pt; float: left; - width: 8em; - height: 11.5em; + width: 6em; + height: 9.5em; display: grid; grid-template-columns: 1fr; - grid-template-rows: 8em 3.5em; + grid-template-rows: 6em 3.5em; gap: 0px 0px; grid-auto-flow: row; grid-template-areas: @@ -16,82 +18,71 @@ "modifier-card-container"; border: 2px solid rgba(255, 255, 255, .05); cursor: pointer; -} -.modifier-card-size_5 { - width: 18em; - grid-template-rows: 18em 3.5em; - height: 21.5em; -} -.modifier-card-size_5 .modifier-card-image-overlay { - font-size: 8em; -} -.modifier-card-size_4 { - width: 14em; - grid-template-rows: 14em 3.5em; - height: 17.5em; -} -.modifier-card-size_4 .modifier-card-image-overlay { - font-size: 7em; + z-index: 2; } .modifier-card-size_3 { - width: 11em; - grid-template-rows: 11em 3.5em; - height: 14.5em; -} -.modifier-card-size_3 .modifier-card-image-overlay { - font-size: 6em; -} -.modifier-card-size_2 { width: 10em; grid-template-rows: 10em 3.5em; height: 13.5em; } -.modifier-card-size_2 .modifier-card-image-overlay { +.modifier-card-size_3 .modifier-card-image-overlay { font-size: 6em; } -.modifier-card-size_1 { +.modifier-card-size_3 .modifier-card-label { + font-size: 1.2em; +} +.modifier-card-size_2 { width: 9em; grid-template-rows: 9em 3.5em; height: 12.5em; } -.modifier-card-size_1 .modifier-card-image-overlay { +.modifier-card-size_2 .modifier-card-image-overlay { font-size: 5em; } -.modifier-card-size_-1 { +.modifier-card-size_2 .modifier-card-label { + font-size: 1.1em; +} +.modifier-card-size_1 { width: 7em; grid-template-rows: 7em 3.5em; height: 10.5em; } -.modifier-card-size_-1 .modifier-card-image-overlay { +.modifier-card-size_1 .modifier-card-image-overlay { font-size: 4em; } -.modifier-card-size_-2 { - width: 6em; - grid-template-rows: 6em 3.5em; - height: 9.5em; -} -.modifier-card-size_-2 .modifier-card-image-overlay { - font-size: 3em; -} -.modifier-card-size_-3 { +.modifier-card-size_-1 { width: 5em; grid-template-rows: 5em 3.5em; height: 8.5em; } -.modifier-card-size_-3 .modifier-card-image-overlay { +.modifier-card-size_-1 .modifier-card-image-overlay { font-size: 3em; } -.modifier-card-size_-3 .modifier-card-label { - font-size: 0.8em; +.modifier-card-size_-1 .modifier-card-label { + font-size: 0.9em; +} +.modifier-card-size_-2 { + width: 4em; + grid-template-rows: 3.5em 3em; + height: 6.5em; +} +.modifier-card-size_-2 .modifier-card-image-overlay { + font-size: 2em; +} +.modifier-card-size_-2 .modifier-card-label { + font-size: 0.7em; } .modifier-card-tiny { - width: 6em; - height: 9.5em; - grid-template-rows: 6em 3.5em; + width: 5em; + grid-template-rows: 5em 3.5em; + height: 8.5em; } .modifier-card-tiny .modifier-card-image-overlay { font-size: 4em; } +.modifier-card-tiny .modifier-card-label { + font-size: 0.9em; +} .modifier-card:hover { transform: scale(1.05); box-shadow: 0 5px 16px 5px rgba(0, 0, 0, 0.25); @@ -115,6 +106,7 @@ } .modifier-card-image-container * { position: absolute; + text-align: center; } .modifier-card-container { text-align: center; @@ -131,6 +123,7 @@ .modifier-card-label { padding: 4px; word-break: break-word; + text-transform: capitalize; } .modifier-card-image-overlay { width: inherit; @@ -140,7 +133,7 @@ position: absolute; border-radius: 5px 5px 0 0; opacity: 0; - font-size: 5em; + font-size: 4em; font-weight: 900; color: rgb(255 255 255 / 50%); display: flex; @@ -153,6 +146,9 @@ position: absolute; z-index: 3; } +.modifier-card-active .modifier-card-overlay { + background-color: rgb(169 78 241 / 40%); +} .modifier-card:hover > .modifier-card-image-container .modifier-card-image-overlay { opacity: 1; } @@ -171,53 +167,24 @@ border: 2px solid rgb(179 82 255 / 94%); box-shadow: 0 0px 10px 0 rgb(170 0 229 / 58%); } -.tooltip { - position: relative; - display: inline-block; -} -.tooltip .tooltip-text { - visibility: hidden; - width: 120px; - background: rgb(101,97,181); - background: linear-gradient(180deg, rgba(101,97,181,1) 0%, rgba(47,45,85,1) 100%); - color: #fff; - text-align: center; - border-radius: 6px; - padding: 5px; - position: absolute; - z-index: 1; - top: 105%; - left: 39%; - margin-left: -60px; - opacity: 0; - transition: opacity 0.3s; - border: 2px solid rgb(90 100 177 / 94%); - box-shadow: 0px 10px 20px 5px rgb(11 0 58 / 55%); - width: 10em; -} -.tooltip .tooltip-text::after { - content: ""; - position: absolute; - top: -0.9em; - left: 50%; - margin-left: -5px; - border-width: 5px; - border-style: solid; - border-color: transparent transparent rgb(90 100 177 / 94%) transparent; -} -.tooltip:hover .tooltip-text { - visibility: visible; - opacity: 1; -} #modifier-card-size-slider { width: 6em; margin-bottom: 0.5em; vertical-align: middle; } -#modifier-settings-btn { - float: right; -} #modifier-settings-config textarea { width: 90%; height: 150px; +} +.modifier-card .hidden { + display: none; +} +.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .modifier-card-label { + font-size: 0.7em; +} +.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .long-label { + display: block; +} +.support-long-label .modifier-card-overlay:hover ~ .modifier-card-container .regular-label { + display: none; } \ No newline at end of file diff --git a/ui/media/css/plugins.css b/ui/media/css/plugins.css new file mode 100644 index 00000000..2b8bf370 --- /dev/null +++ b/ui/media/css/plugins.css @@ -0,0 +1,288 @@ +.plugins-table { + display: flex; + flex-direction: column; + gap: 1px; +} + +.plugins-table > div { + background: var(--background-color2); + display: flex; + padding: 0px 4px; +} + +.plugins-table > div > div { + padding: 10px; + display: flex; + align-items: center; + justify-content: center; +} + +.plugins-table small { + color: rgb(153, 153, 153); +} + +.plugins-table > div > div:nth-child(1) { + font-size: 20px; + width: 45px; +} + +.plugins-table > div > div:nth-child(2) { + flex: 1; + flex-direction: column; + text-align: left; + justify-content: center; + align-items: start; + gap: 4px; +} + +.plugins-table > div > div:nth-child(3) { + text-align: right; +} + +.plugins-table > div:first-child { + border-radius: 12px 12px 0px 0px; +} + +.plugins-table > div:last-child { + border-radius: 0px 0px 12px 12px; +} + +.notifications-table { + display: flex; + flex-direction: column; + gap: 1px; +} + +.notifications-table > div { + background: var(--background-color2); + display: flex; + padding: 0px 4px; +} + +.notifications-table > div > div { + padding: 10px; + display: flex; + align-items: center; + justify-content: center; +} + +.notifications-table small { + color: rgb(153, 153, 153); +} + +.notifications-table > div > div:nth-child(1) { + flex: 1; + flex-direction: column; + text-align: left; + justify-content: center; + align-items: start; + gap: 4px; +} + +.notifications-table > div > div:nth-child(2) { + width: auto; +} + +.notifications-table > div:first-child { + border-radius: 12px 12px 0px 0px; +} + +.notifications-table > div:last-child { + border-radius: 0px 0px 12px 12px; +} + +.notification-error { + color: red; +} + +DIV.no-notification { + padding-top: 16px; + font-style: italic; +} + +.plugin-manager-intro { + margin: 0 0 16px 0; +} + +#plugin-filter { + box-sizing: border-box; + width: 100%; + margin: 4px 0 6px 0; + padding: 10px; +} + +#refresh-plugins { + box-sizing: border-box; + width: 100%; + padding: 0px; +} + +#refresh-plugins a { + cursor: pointer; +} + +#refresh-plugins a:active { + transition-duration: 0.1s; + position: relative; + top: 1px; + left: 1px; +} + +.plugin-installed-locally { + font-style: italic; + font-size: small; +} + +.plugin-source { + font-size: x-small; +} + +.plugin-warning { + color: orange; + font-size: smaller; +} + +.plugin-warning.hide { + display: none; +} + +.plugin-warning ul { + list-style: square; + margin: 0 0 8px 16px; + padding: 0; +} + +.plugin-warning li { + margin-left: 8px; + padding: 0; +} + +/* MODAL DIALOG */ +#pluginDialog-input-dialog { + position: fixed; + z-index: 1000; + top: 0; + left: 0; + width: 100%; + height: 100%; + display: none; +} + +.pluginDialog-dialog-overlay { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(32, 33, 36, 50%); +} + +.pluginDialog-dialog-box { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 80%; + max-width: 600px; + background: var(--background-color2); + border: solid 1px var(--background-color3); + border-radius: 6px; + box-shadow: 0px 0px 30px black; +} + +.pluginDialog-dialog-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px; +} + +.pluginDialog-dialog-header h2 { + margin: 0; +} + +.pluginDialog-dialog-close-button { + font-size: 24px; + font-weight: bold; + line-height: 1; + border: none; + background-color: transparent; + cursor: pointer; +} + +.pluginDialog-dialog-close-button:hover { + color: #555; +} + +.pluginDialog-dialog-content { + padding: 0 16px 0 16px; +} + +.pluginDialog-dialog-content textarea { + width: 100%; + height: 300px; + border-radius: var(--input-border-radius); + padding: 4px; + accent-color: var(--accent-color); + background: var(--input-background-color); + border: var(--input-border-size) solid var(--input-border-color); + color: var(--input-text-color); + font-size: 9pt; + resize: none; +} + +.pluginDialog-dialog-buttons { + display: flex; + justify-content: flex-end; + padding: 16px; +} + +.pluginDialog-dialog-buttons button { + margin-left: 8px; + padding: 8px 16px; + font-size: 16px; + border-radius: 4px; + /*background: var(--accent-color);*/ + /*border: var(--primary-button-border);*/ + /*color: rgb(255, 221, 255);*/ + background-color: #3071a9; + border: none; + cursor: pointer; +} + +.pluginDialog-dialog-buttons button:hover { + /*background: hsl(var(--accent-hue), 100%, 50%);*/ + background-color: #428bca; +} + +/* NOTIFICATION CENTER */ +#plugin-notification-button { + float: right; + margin-top: 30px; +} + +#plugin-notification-button:hover { + background: unset; +} + +#plugin-notification-button:active { + transition-duration: 0.1s; + position: relative; + top: 1px; + left: 1px; +} + +.plugin-notification-pill { + background-color: red; + border-radius: 50%; + color: white; + font-size: 10px; + font-weight: bold; + height: 12px; + line-height: 12px; + position: relative; + right: -8px; + text-align: center; + top: -20px; + width: 12px; +} diff --git a/ui/media/css/searchable-models.css b/ui/media/css/searchable-models.css index 06d24acb..5eecd1e0 100644 --- a/ui/media/css/searchable-models.css +++ b/ui/media/css/searchable-models.css @@ -58,7 +58,7 @@ font-size: 10pt; font-weight: normal; transition: none; - transition:property: none; + transition-property: none; cursor: default; } diff --git a/ui/media/css/themes.css b/ui/media/css/themes.css index 053199f8..e9eca84f 100644 --- a/ui/media/css/themes.css +++ b/ui/media/css/themes.css @@ -33,7 +33,7 @@ --input-height: 18px; --tertiary-background-color: hsl(var(--main-hue), var(--main-saturation), calc(var(--value-base) + (2 * var(--value-step)))); --tertiary-border-color: hsl(var(--main-hue), var(--main-saturation), calc(var(--value-base) + (3 * var(--value-step)))); - --tertiary-color: var(--input-text-color) + --tertiary-color: var(--input-text-color); /* Main theme color, hex color fallback. */ --theme-color-fallback: #673AB6; diff --git a/ui/media/js/auto-save.js b/ui/media/js/auto-save.js index 32d9ad1e..bbcbf9a5 100644 --- a/ui/media/js/auto-save.js +++ b/ui/media/js/auto-save.js @@ -13,6 +13,7 @@ const SETTINGS_IDS_LIST = [ "num_outputs_total", "num_outputs_parallel", "stable_diffusion_model", + "clip_skip", "vae_model", "hypernetwork_model", "lora_model", @@ -24,6 +25,7 @@ const SETTINGS_IDS_LIST = [ "prompt_strength", "hypernetwork_strength", "lora_alpha", + "tiling", "output_format", "output_quality", "output_lossless", @@ -33,6 +35,7 @@ const SETTINGS_IDS_LIST = [ "gfpgan_model", "use_upscale", "upscale_amount", + "latent_upscaler_steps", "block_nsfw", "show_only_filtered_image", "upscale_model", @@ -52,27 +55,27 @@ const SETTINGS_IDS_LIST = [ "auto_scroll", "zip_toggle", "tree_toggle", - "json_toggle" + "json_toggle", ] -const IGNORE_BY_DEFAULT = [ - "prompt" -] +const IGNORE_BY_DEFAULT = ["prompt"] -const SETTINGS_SECTIONS = [ // gets the "keys" property filled in with an ordered list of settings in this section via initSettings - { id: "editor-inputs", name: "Prompt" }, +const SETTINGS_SECTIONS = [ + // gets the "keys" property filled in with an ordered list of settings in this section via initSettings + { id: "editor-inputs", name: "Prompt" }, { id: "editor-settings", name: "Image Settings" }, { id: "system-settings", name: "System Settings" }, - { id: "container", name: "Other" } + { id: "container", name: "Other" }, ] async function initSettings() { - SETTINGS_IDS_LIST.forEach(id => { + SETTINGS_IDS_LIST.forEach((id) => { var element = document.getElementById(id) if (!element) { console.error(`Missing settings element ${id}`) } - if (id in SETTINGS) { // don't create it again + if (id in SETTINGS) { + // don't create it again return } SETTINGS[id] = { @@ -81,28 +84,28 @@ async function initSettings() { label: getSettingLabel(element), default: getSetting(element), value: getSetting(element), - ignore: IGNORE_BY_DEFAULT.includes(id) + ignore: IGNORE_BY_DEFAULT.includes(id), } element.addEventListener("input", settingChangeHandler) element.addEventListener("change", settingChangeHandler) }) var unsorted_settings_ids = [...SETTINGS_IDS_LIST] - SETTINGS_SECTIONS.forEach(section => { + SETTINGS_SECTIONS.forEach((section) => { var name = section.name var element = document.getElementById(section.id) - var unsorted_ids = unsorted_settings_ids.map(id => `#${id}`).join(",") - var children = unsorted_ids == "" ? [] : Array.from(element.querySelectorAll(unsorted_ids)); + var unsorted_ids = unsorted_settings_ids.map((id) => `#${id}`).join(",") + var children = unsorted_ids == "" ? [] : Array.from(element.querySelectorAll(unsorted_ids)) section.keys = [] - children.forEach(e => { + children.forEach((e) => { section.keys.push(e.id) }) - unsorted_settings_ids = unsorted_settings_ids.filter(id => children.find(e => e.id == id) == undefined) + unsorted_settings_ids = unsorted_settings_ids.filter((id) => children.find((e) => e.id == id) == undefined) }) loadSettings() } function getSetting(element) { - if (element.dataset && 'path' in element.dataset) { + if (element.dataset && "path" in element.dataset) { return element.dataset.path } if (typeof element === "string" || element instanceof String) { @@ -114,7 +117,7 @@ function getSetting(element) { return element.value } function setSetting(element, value) { - if (element.dataset && 'path' in element.dataset) { + if (element.dataset && "path" in element.dataset) { element.dataset.path = value return // no need to dispatch any event here because the models are not loaded yet } @@ -127,8 +130,7 @@ function setSetting(element, value) { } if (element.type == "checkbox") { element.checked = value - } - else { + } else { element.value = value } element.dispatchEvent(new Event("input")) @@ -136,11 +138,11 @@ function setSetting(element, value) { } function saveSettings() { - var saved_settings = Object.values(SETTINGS).map(setting => { + var saved_settings = Object.values(SETTINGS).map((setting) => { return { key: setting.key, value: setting.value, - ignore: setting.ignore + ignore: setting.ignore, } }) localStorage.setItem(SETTINGS_KEY, JSON.stringify(saved_settings)) @@ -151,16 +153,16 @@ function loadSettings() { var saved_settings_text = localStorage.getItem(SETTINGS_KEY) if (saved_settings_text) { var saved_settings = JSON.parse(saved_settings_text) - if (saved_settings.find(s => s.key == "auto_save_settings")?.value == false) { + if (saved_settings.find((s) => s.key == "auto_save_settings")?.value == false) { setSetting("auto_save_settings", false) return } CURRENTLY_LOADING_SETTINGS = true - saved_settings.forEach(saved_setting => { + saved_settings.forEach((saved_setting) => { var setting = SETTINGS[saved_setting.key] if (!setting) { - console.warn(`Attempted to load setting ${saved_setting.key}, but no setting found`); - return null; + console.warn(`Attempted to load setting ${saved_setting.key}, but no setting found`) + return null } setting.ignore = saved_setting.ignore if (!setting.ignore) { @@ -169,10 +171,25 @@ function loadSettings() { } }) CURRENTLY_LOADING_SETTINGS = false - } - else { + } else if (localStorage.length < 2) { + // localStorage is too short for OldSettings + // So this is likely the first time Easy Diffusion is running. + // Initialize vram_usage_level based on the available VRAM + function initGPUProfile(event) { + if ( "detail" in event + && "active" in event.detail + && "cuda:0" in event.detail.active + && event.detail.active["cuda:0"].mem_total <4.5 ) + { + vramUsageLevelField.value = "low" + vramUsageLevelField.dispatchEvent(new Event("change")) + } + document.removeEventListener("system_info_update", initGPUProfile) + } + document.addEventListener("system_info_update", initGPUProfile) + } else { CURRENTLY_LOADING_SETTINGS = true - tryLoadOldSettings(); + tryLoadOldSettings() CURRENTLY_LOADING_SETTINGS = false saveSettings() } @@ -180,9 +197,9 @@ function loadSettings() { function loadDefaultSettingsSection(section_id) { CURRENTLY_LOADING_SETTINGS = true - var section = SETTINGS_SECTIONS.find(s => s.id == section_id); - section.keys.forEach(key => { - var setting = SETTINGS[key]; + var section = SETTINGS_SECTIONS.find((s) => s.id == section_id) + section.keys.forEach((key) => { + var setting = SETTINGS[key] setting.value = setting.default setSetting(setting.element, setting.value) }) @@ -218,10 +235,10 @@ function getSettingLabel(element) { function fillSaveSettingsConfigTable() { saveSettingsConfigTable.textContent = "" - SETTINGS_SECTIONS.forEach(section => { + SETTINGS_SECTIONS.forEach((section) => { var section_row = `${section.name}` saveSettingsConfigTable.insertAdjacentHTML("beforeend", section_row) - section.keys.forEach(key => { + section.keys.forEach((key) => { var setting = SETTINGS[key] var element = setting.element var checkbox_id = `shouldsave_${element.id}` @@ -234,7 +251,7 @@ function fillSaveSettingsConfigTable() { var newrow = `(${value})` saveSettingsConfigTable.insertAdjacentHTML("beforeend", newrow) var checkbox = document.getElementById(checkbox_id) - checkbox.addEventListener("input", event => { + checkbox.addEventListener("input", (event) => { setting.ignore = !checkbox.checked saveSettings() }) @@ -245,9 +262,6 @@ function fillSaveSettingsConfigTable() { // configureSettingsSaveBtn - - - var autoSaveSettings = document.getElementById("auto_save_settings") var configSettingsButton = document.createElement("button") configSettingsButton.textContent = "Configure" @@ -256,33 +270,32 @@ autoSaveSettings.insertAdjacentElement("beforebegin", configSettingsButton) autoSaveSettings.addEventListener("change", () => { configSettingsButton.style.display = autoSaveSettings.checked ? "block" : "none" }) -configSettingsButton.addEventListener('click', () => { +configSettingsButton.addEventListener("click", () => { fillSaveSettingsConfigTable() saveSettingsConfigOverlay.classList.add("active") }) -resetImageSettingsButton.addEventListener('click', event => { - loadDefaultSettingsSection("editor-settings"); +resetImageSettingsButton.addEventListener("click", (event) => { + loadDefaultSettingsSection("editor-settings") event.stopPropagation() }) - function tryLoadOldSettings() { console.log("Loading old user settings") // load v1 auto-save.js settings var old_map = { - "guidance_scale_slider": "guidance_scale", - "prompt_strength_slider": "prompt_strength" + guidance_scale_slider: "guidance_scale", + prompt_strength_slider: "prompt_strength", } var settings_key_v1 = "user_settings" var saved_settings_text = localStorage.getItem(settings_key_v1) if (saved_settings_text) { var saved_settings = JSON.parse(saved_settings_text) - Object.keys(saved_settings.should_save).forEach(key => { + Object.keys(saved_settings.should_save).forEach((key) => { key = key in old_map ? old_map[key] : key if (!(key in SETTINGS)) return SETTINGS[key].ignore = !saved_settings.should_save[key] - }); - Object.keys(saved_settings.values).forEach(key => { + }) + Object.keys(saved_settings.values).forEach((key) => { key = key in old_map ? old_map[key] : key if (!(key in SETTINGS)) return var setting = SETTINGS[key] @@ -290,38 +303,42 @@ function tryLoadOldSettings() { setting.value = saved_settings.values[key] setSetting(setting.element, setting.value) } - }); + }) localStorage.removeItem(settings_key_v1) } // load old individually stored items - var individual_settings_map = { // maps old localStorage-key to new SETTINGS-key - "soundEnabled": "sound_toggle", - "saveToDisk": "save_to_disk", - "useCPU": "use_cpu", - "diskPath": "diskPath", - "useFaceCorrection": "use_face_correction", - "useUpscaling": "use_upscale", - "showOnlyFilteredImage": "show_only_filtered_image", - "streamImageProgress": "stream_image_progress", - "outputFormat": "output_format", - "autoSaveSettings": "auto_save_settings", - }; - Object.keys(individual_settings_map).forEach(localStorageKey => { - var localStorageValue = localStorage.getItem(localStorageKey); + var individual_settings_map = { + // maps old localStorage-key to new SETTINGS-key + soundEnabled: "sound_toggle", + saveToDisk: "save_to_disk", + useCPU: "use_cpu", + diskPath: "diskPath", + useFaceCorrection: "use_face_correction", + useUpscaling: "use_upscale", + showOnlyFilteredImage: "show_only_filtered_image", + streamImageProgress: "stream_image_progress", + outputFormat: "output_format", + autoSaveSettings: "auto_save_settings", + } + Object.keys(individual_settings_map).forEach((localStorageKey) => { + var localStorageValue = localStorage.getItem(localStorageKey) if (localStorageValue !== null) { let key = individual_settings_map[localStorageKey] var setting = SETTINGS[key] if (!setting) { - console.warn(`Attempted to map old setting ${key}, but no setting found`); - return null; + console.warn(`Attempted to map old setting ${key}, but no setting found`) + return null } - if (setting.element.type == "checkbox" && (typeof localStorageValue === "string" || localStorageValue instanceof String)) { + if ( + setting.element.type == "checkbox" && + (typeof localStorageValue === "string" || localStorageValue instanceof String) + ) { localStorageValue = localStorageValue == "true" } setting.value = localStorageValue setSetting(setting.element, setting.value) - localStorage.removeItem(localStorageKey); + localStorage.removeItem(localStorageKey) } }) } diff --git a/ui/media/js/dnd.js b/ui/media/js/dnd.js index 98c5e26a..4e50b638 100644 --- a/ui/media/js/dnd.js +++ b/ui/media/js/dnd.js @@ -1,25 +1,25 @@ "use strict" // Opt in to a restricted variant of JavaScript const EXT_REGEX = /(?:\.([^.]+))?$/ -const TEXT_EXTENSIONS = ['txt', 'json'] -const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'bmp', 'tiff', 'tif', 'tga', 'webp'] +const TEXT_EXTENSIONS = ["txt", "json"] +const IMAGE_EXTENSIONS = ["jpg", "jpeg", "png", "bmp", "tiff", "tif", "tga", "webp"] function parseBoolean(stringValue) { - if (typeof stringValue === 'boolean') { + if (typeof stringValue === "boolean") { return stringValue } - if (typeof stringValue === 'number') { + if (typeof stringValue === "number") { return stringValue !== 0 } - if (typeof stringValue !== 'string') { + if (typeof stringValue !== "string") { return false } - switch(stringValue?.toLowerCase()?.trim()) { + switch (stringValue?.toLowerCase()?.trim()) { case "true": case "yes": case "on": case "1": - return true; + return true case "false": case "no": @@ -28,67 +28,77 @@ function parseBoolean(stringValue) { case "none": case null: case undefined: - return false; + return false } try { - return Boolean(JSON.parse(stringValue)); + return Boolean(JSON.parse(stringValue)) } catch { return Boolean(stringValue) } } +// keep in sync with `ui/easydiffusion/utils/save_utils.py` const TASK_MAPPING = { - prompt: { name: 'Prompt', + prompt: { + name: "Prompt", setUI: (prompt) => { promptField.value = prompt }, readUI: () => promptField.value, - parse: (val) => val + parse: (val) => val, }, - negative_prompt: { name: 'Negative Prompt', + negative_prompt: { + name: "Negative Prompt", setUI: (negative_prompt) => { negativePromptField.value = negative_prompt }, readUI: () => negativePromptField.value, - parse: (val) => val + parse: (val) => val, }, - active_tags: { name: "Image Modifiers", + active_tags: { + name: "Image Modifiers", setUI: (active_tags) => { refreshModifiersState(active_tags) }, - readUI: () => activeTags.map(x => x.name), - parse: (val) => val + readUI: () => activeTags.map((x) => x.name), + parse: (val) => val, }, - inactive_tags: { name: "Inactive Image Modifiers", + inactive_tags: { + name: "Inactive Image Modifiers", setUI: (inactive_tags) => { refreshInactiveTags(inactive_tags) }, - readUI: () => activeTags.filter(tag => tag.inactive === true).map(x => x.name), - parse: (val) => val + readUI: () => activeTags.filter((tag) => tag.inactive === true).map((x) => x.name), + parse: (val) => val, }, - width: { name: 'Width', + width: { + name: "Width", setUI: (width) => { const oldVal = widthField.value widthField.value = width if (!widthField.value) { widthField.value = oldVal } + widthField.dispatchEvent(new Event("change")) }, readUI: () => parseInt(widthField.value), - parse: (val) => parseInt(val) + parse: (val) => parseInt(val), }, - height: { name: 'Height', + height: { + name: "Height", setUI: (height) => { const oldVal = heightField.value heightField.value = height if (!heightField.value) { heightField.value = oldVal } + heightField.dispatchEvent(new Event("change")) }, readUI: () => parseInt(heightField.value), - parse: (val) => parseInt(val) + parse: (val) => parseInt(val), }, - seed: { name: 'Seed', + seed: { + name: "Seed", setUI: (seed) => { if (!seed) { randomSeedField.checked = true @@ -97,89 +107,108 @@ const TASK_MAPPING = { return } randomSeedField.checked = false - randomSeedField.dispatchEvent(new Event('change')) // let plugins know that the state of the random seed toggle changed + randomSeedField.dispatchEvent(new Event("change")) // let plugins know that the state of the random seed toggle changed seedField.disabled = false seedField.value = seed }, readUI: () => parseInt(seedField.value), // just return the value the user is seeing in the UI - parse: (val) => parseInt(val) + parse: (val) => parseInt(val), }, - num_inference_steps: { name: 'Steps', + num_inference_steps: { + name: "Steps", setUI: (num_inference_steps) => { numInferenceStepsField.value = num_inference_steps }, readUI: () => parseInt(numInferenceStepsField.value), - parse: (val) => parseInt(val) + parse: (val) => parseInt(val), }, - guidance_scale: { name: 'Guidance Scale', + guidance_scale: { + name: "Guidance Scale", setUI: (guidance_scale) => { guidanceScaleField.value = guidance_scale updateGuidanceScaleSlider() }, readUI: () => parseFloat(guidanceScaleField.value), - parse: (val) => parseFloat(val) + parse: (val) => parseFloat(val), }, - prompt_strength: { name: 'Prompt Strength', + prompt_strength: { + name: "Prompt Strength", setUI: (prompt_strength) => { promptStrengthField.value = prompt_strength updatePromptStrengthSlider() }, readUI: () => parseFloat(promptStrengthField.value), - parse: (val) => parseFloat(val) + parse: (val) => parseFloat(val), }, - init_image: { name: 'Initial Image', + init_image: { + name: "Initial Image", setUI: (init_image) => { initImagePreview.src = init_image }, readUI: () => initImagePreview.src, - parse: (val) => val + parse: (val) => val, }, - mask: { name: 'Mask', + mask: { + name: "Mask", setUI: (mask) => { - setTimeout(() => { // add a delay to insure this happens AFTER the main image loads (which reloads the inpainter) + setTimeout(() => { + // add a delay to insure this happens AFTER the main image loads (which reloads the inpainter) imageInpainter.setImg(mask) }, 250) maskSetting.checked = Boolean(mask) }, readUI: () => (maskSetting.checked ? imageInpainter.getImg() : undefined), - parse: (val) => val + parse: (val) => val, }, - preserve_init_image_color_profile: { name: 'Preserve Color Profile', + preserve_init_image_color_profile: { + name: "Preserve Color Profile", setUI: (preserve_init_image_color_profile) => { applyColorCorrectionField.checked = parseBoolean(preserve_init_image_color_profile) }, readUI: () => applyColorCorrectionField.checked, - parse: (val) => parseBoolean(val) + parse: (val) => parseBoolean(val), }, - - use_face_correction: { name: 'Use Face Correction', + + use_face_correction: { + name: "Use Face Correction", setUI: (use_face_correction) => { const oldVal = gfpganModelField.value - gfpganModelField.value = getModelPath(use_face_correction, ['.pth']) - if (gfpganModelField.value) { // Is a valid value for the field. - useFaceCorrectionField.checked = true - gfpganModelField.disabled = false - } else { // Not a valid value, restore the old value and disable the filter. + console.log("use face correction", use_face_correction) + if (use_face_correction == null || use_face_correction == "None") { gfpganModelField.disabled = true - gfpganModelField.value = oldVal useFaceCorrectionField.checked = false + } else { + gfpganModelField.value = getModelPath(use_face_correction, [".pth"]) + if (gfpganModelField.value) { + // Is a valid value for the field. + useFaceCorrectionField.checked = true + gfpganModelField.disabled = false + } else { + // Not a valid value, restore the old value and disable the filter. + gfpganModelField.disabled = true + gfpganModelField.value = oldVal + useFaceCorrectionField.checked = false + } } //useFaceCorrectionField.checked = parseBoolean(use_face_correction) }, readUI: () => (useFaceCorrectionField.checked ? gfpganModelField.value : undefined), - parse: (val) => val + parse: (val) => val, }, - use_upscale: { name: 'Use Upscaling', + use_upscale: { + name: "Use Upscaling", setUI: (use_upscale) => { const oldVal = upscaleModelField.value - upscaleModelField.value = getModelPath(use_upscale, ['.pth']) - if (upscaleModelField.value) { // Is a valid value for the field. + upscaleModelField.value = getModelPath(use_upscale, [".pth"]) + if (upscaleModelField.value) { + // Is a valid value for the field. useUpscalingField.checked = true upscaleModelField.disabled = false upscaleAmountField.disabled = false - } else { // Not a valid value, restore the old value and disable the filter. + } else { + // Not a valid value, restore the old value and disable the filter. upscaleModelField.disabled = true upscaleAmountField.disabled = true upscaleModelField.value = oldVal @@ -187,27 +216,38 @@ const TASK_MAPPING = { } }, readUI: () => (useUpscalingField.checked ? upscaleModelField.value : undefined), - parse: (val) => val + parse: (val) => val, }, - upscale_amount: { name: 'Upscale By', + upscale_amount: { + name: "Upscale By", setUI: (upscale_amount) => { upscaleAmountField.value = upscale_amount }, readUI: () => upscaleAmountField.value, - parse: (val) => val + parse: (val) => val, }, - sampler_name: { name: 'Sampler', + latent_upscaler_steps: { + name: "Latent Upscaler Steps", + setUI: (latent_upscaler_steps) => { + latentUpscalerStepsField.value = latent_upscaler_steps + }, + readUI: () => latentUpscalerStepsField.value, + parse: (val) => val, + }, + sampler_name: { + name: "Sampler", setUI: (sampler_name) => { samplerField.value = sampler_name }, readUI: () => samplerField.value, - parse: (val) => val + parse: (val) => val, }, - use_stable_diffusion_model: { name: 'Stable Diffusion model', + use_stable_diffusion_model: { + name: "Stable Diffusion model", setUI: (use_stable_diffusion_model) => { const oldVal = stableDiffusionModelField.value - use_stable_diffusion_model = getModelPath(use_stable_diffusion_model, ['.ckpt', '.safetensors']) + use_stable_diffusion_model = getModelPath(use_stable_diffusion_model, [".ckpt", ".safetensors"]) stableDiffusionModelField.value = use_stable_diffusion_model if (!stableDiffusionModelField.value) { @@ -215,118 +255,162 @@ const TASK_MAPPING = { } }, readUI: () => stableDiffusionModelField.value, - parse: (val) => val + parse: (val) => val, }, - use_vae_model: { name: 'VAE model', + clip_skip: { + name: "Clip Skip", + setUI: (value) => { + clip_skip.checked = value + }, + readUI: () => clip_skip.checked, + parse: (val) => Boolean(val), + }, + tiling: { + name: "Tiling", + setUI: (val) => { + tilingField.value = val + }, + readUI: () => tilingField.value, + parse: (val) => val, + }, + use_vae_model: { + name: "VAE model", setUI: (use_vae_model) => { const oldVal = vaeModelField.value - use_vae_model = (use_vae_model === undefined || use_vae_model === null || use_vae_model === 'None' ? '' : use_vae_model) + use_vae_model = + use_vae_model === undefined || use_vae_model === null || use_vae_model === "None" ? "" : use_vae_model - if (use_vae_model !== '') { - use_vae_model = getModelPath(use_vae_model, ['.vae.pt', '.ckpt']) - use_vae_model = use_vae_model !== '' ? use_vae_model : oldVal + if (use_vae_model !== "") { + use_vae_model = getModelPath(use_vae_model, [".vae.pt", ".ckpt"]) + use_vae_model = use_vae_model !== "" ? use_vae_model : oldVal } vaeModelField.value = use_vae_model }, readUI: () => vaeModelField.value, - parse: (val) => val + parse: (val) => val, }, - use_lora_model: { name: 'LoRA model', + use_lora_model: { + name: "LoRA model", setUI: (use_lora_model) => { const oldVal = loraModelField.value - use_lora_model = (use_lora_model === undefined || use_lora_model === null || use_lora_model === 'None' ? '' : use_lora_model) + use_lora_model = + use_lora_model === undefined || use_lora_model === null || use_lora_model === "None" + ? "" + : use_lora_model - if (use_lora_model !== '') { - use_lora_model = getModelPath(use_lora_model, ['.ckpt', '.safetensors']) - use_lora_model = use_lora_model !== '' ? use_lora_model : oldVal + if (use_lora_model !== "") { + use_lora_model = getModelPath(use_lora_model, [".ckpt", ".safetensors"]) + use_lora_model = use_lora_model !== "" ? use_lora_model : oldVal } loraModelField.value = use_lora_model }, readUI: () => loraModelField.value, - parse: (val) => val + parse: (val) => val, }, - use_hypernetwork_model: { name: 'Hypernetwork model', + lora_alpha: { + name: "LoRA Strength", + setUI: (lora_alpha) => { + loraAlphaField.value = lora_alpha + updateLoraAlphaSlider() + }, + readUI: () => parseFloat(loraAlphaField.value), + parse: (val) => parseFloat(val), + }, + use_hypernetwork_model: { + name: "Hypernetwork model", setUI: (use_hypernetwork_model) => { const oldVal = hypernetworkModelField.value - use_hypernetwork_model = (use_hypernetwork_model === undefined || use_hypernetwork_model === null || use_hypernetwork_model === 'None' ? '' : use_hypernetwork_model) + use_hypernetwork_model = + use_hypernetwork_model === undefined || + use_hypernetwork_model === null || + use_hypernetwork_model === "None" + ? "" + : use_hypernetwork_model - if (use_hypernetwork_model !== '') { - use_hypernetwork_model = getModelPath(use_hypernetwork_model, ['.pt']) - use_hypernetwork_model = use_hypernetwork_model !== '' ? use_hypernetwork_model : oldVal + if (use_hypernetwork_model !== "") { + use_hypernetwork_model = getModelPath(use_hypernetwork_model, [".pt"]) + use_hypernetwork_model = use_hypernetwork_model !== "" ? use_hypernetwork_model : oldVal } hypernetworkModelField.value = use_hypernetwork_model - hypernetworkModelField.dispatchEvent(new Event('change')) + hypernetworkModelField.dispatchEvent(new Event("change")) }, readUI: () => hypernetworkModelField.value, - parse: (val) => val + parse: (val) => val, }, - hypernetwork_strength: { name: 'Hypernetwork Strength', + hypernetwork_strength: { + name: "Hypernetwork Strength", setUI: (hypernetwork_strength) => { hypernetworkStrengthField.value = hypernetwork_strength updateHypernetworkStrengthSlider() }, readUI: () => parseFloat(hypernetworkStrengthField.value), - parse: (val) => parseFloat(val) + parse: (val) => parseFloat(val), }, - num_outputs: { name: 'Parallel Images', + num_outputs: { + name: "Parallel Images", setUI: (num_outputs) => { numOutputsParallelField.value = num_outputs }, readUI: () => parseInt(numOutputsParallelField.value), - parse: (val) => val + parse: (val) => val, }, - use_cpu: { name: 'Use CPU', + use_cpu: { + name: "Use CPU", setUI: (use_cpu) => { useCPUField.checked = use_cpu }, readUI: () => useCPUField.checked, - parse: (val) => val + parse: (val) => val, }, - stream_image_progress: { name: 'Stream Image Progress', + stream_image_progress: { + name: "Stream Image Progress", setUI: (stream_image_progress) => { - streamImageProgressField.checked = (parseInt(numOutputsTotalField.value) > 50 ? false : stream_image_progress) + streamImageProgressField.checked = parseInt(numOutputsTotalField.value) > 50 ? false : stream_image_progress }, readUI: () => streamImageProgressField.checked, - parse: (val) => Boolean(val) + parse: (val) => Boolean(val), }, - show_only_filtered_image: { name: 'Show only the corrected/upscaled image', + show_only_filtered_image: { + name: "Show only the corrected/upscaled image", setUI: (show_only_filtered_image) => { showOnlyFilteredImageField.checked = show_only_filtered_image }, readUI: () => showOnlyFilteredImageField.checked, - parse: (val) => Boolean(val) + parse: (val) => Boolean(val), }, - output_format: { name: 'Output Format', + output_format: { + name: "Output Format", setUI: (output_format) => { outputFormatField.value = output_format }, readUI: () => outputFormatField.value, - parse: (val) => val + parse: (val) => val, }, - save_to_disk_path: { name: 'Save to disk path', + save_to_disk_path: { + name: "Save to disk path", setUI: (save_to_disk_path) => { saveToDiskField.checked = Boolean(save_to_disk_path) diskPathField.value = save_to_disk_path }, readUI: () => diskPathField.value, - parse: (val) => val - } + parse: (val) => val, + }, } function restoreTaskToUI(task, fieldsToSkip) { fieldsToSkip = fieldsToSkip || [] - if ('numOutputsTotal' in task) { + if ("numOutputsTotal" in task) { numOutputsTotalField.value = task.numOutputsTotal } - if ('seed' in task) { + if ("seed" in task) { randomSeedField.checked = false seedField.value = task.seed } - if (!('reqBody' in task)) { + if (!("reqBody" in task)) { return } for (const key in TASK_MAPPING) { @@ -336,26 +420,32 @@ function restoreTaskToUI(task, fieldsToSkip) { } // properly reset fields not present in the task - if (!('use_hypernetwork_model' in task.reqBody)) { + if (!("use_hypernetwork_model" in task.reqBody)) { hypernetworkModelField.value = "" hypernetworkModelField.dispatchEvent(new Event("change")) } + if (!("use_lora_model" in task.reqBody)) { + loraModelField.value = "" + loraModelField.dispatchEvent(new Event("change")) + } + // restore the original prompt if provided (e.g. use settings), fallback to prompt as needed (e.g. copy/paste or d&d) promptField.value = task.reqBody.original_prompt - if (!('original_prompt' in task.reqBody)) { + if (!("original_prompt" in task.reqBody)) { promptField.value = task.reqBody.prompt } - + promptField.dispatchEvent(new Event("input")) + // properly reset checkboxes - if (!('use_face_correction' in task.reqBody)) { + if (!("use_face_correction" in task.reqBody)) { useFaceCorrectionField.checked = false gfpganModelField.disabled = true } - if (!('use_upscale' in task.reqBody)) { + if (!("use_upscale" in task.reqBody)) { useUpscalingField.checked = false } - if (!('mask' in task.reqBody) && maskSetting.checked) { + if (!("mask" in task.reqBody) && maskSetting.checked) { maskSetting.checked = false maskSetting.dispatchEvent(new Event("click")) } @@ -366,15 +456,18 @@ function restoreTaskToUI(task, fieldsToSkip) { if (IMAGE_REGEX.test(initImagePreview.src) && task.reqBody.init_image == undefined) { // hide source image initImageClearBtn.dispatchEvent(new Event("click")) - } - else if (task.reqBody.init_image !== undefined) { + } else if (task.reqBody.init_image !== undefined) { // listen for inpainter loading event, which happens AFTER the main image loads (which reloads the inpainter) - initImagePreview.addEventListener('load', function() { - if (Boolean(task.reqBody.mask)) { - imageInpainter.setImg(task.reqBody.mask) - maskSetting.checked = true - } - }, { once: true }) + initImagePreview.addEventListener( + "load", + function() { + if (Boolean(task.reqBody.mask)) { + imageInpainter.setImg(task.reqBody.mask) + maskSetting.checked = true + } + }, + { once: true } + ) initImagePreview.src = task.reqBody.init_image } } @@ -384,28 +477,26 @@ function readUI() { reqBody[key] = TASK_MAPPING[key].readUI() } return { - 'numOutputsTotal': parseInt(numOutputsTotalField.value), - 'seed': TASK_MAPPING['seed'].readUI(), - 'reqBody': reqBody + numOutputsTotal: parseInt(numOutputsTotalField.value), + seed: TASK_MAPPING["seed"].readUI(), + reqBody: reqBody, } } -function getModelPath(filename, extensions) -{ +function getModelPath(filename, extensions) { if (typeof filename !== "string") { return } - + let pathIdx - if (filename.includes('/models/stable-diffusion/')) { - pathIdx = filename.indexOf('/models/stable-diffusion/') + 25 // Linux, Mac paths - } - else if (filename.includes('\\models\\stable-diffusion\\')) { - pathIdx = filename.indexOf('\\models\\stable-diffusion\\') + 25 // Linux, Mac paths + if (filename.includes("/models/stable-diffusion/")) { + pathIdx = filename.indexOf("/models/stable-diffusion/") + 25 // Linux, Mac paths + } else if (filename.includes("\\models\\stable-diffusion\\")) { + pathIdx = filename.indexOf("\\models\\stable-diffusion\\") + 25 // Linux, Mac paths } if (pathIdx >= 0) { filename = filename.slice(pathIdx) } - extensions.forEach(ext => { + extensions.forEach((ext) => { if (filename.endsWith(ext)) { filename = filename.slice(0, filename.length - ext.length) } @@ -414,26 +505,26 @@ function getModelPath(filename, extensions) } const TASK_TEXT_MAPPING = { - prompt: 'Prompt', - width: 'Width', - height: 'Height', - seed: 'Seed', - num_inference_steps: 'Steps', - guidance_scale: 'Guidance Scale', - prompt_strength: 'Prompt Strength', - use_face_correction: 'Use Face Correction', - use_upscale: 'Use Upscaling', - upscale_amount: 'Upscale By', - sampler_name: 'Sampler', - negative_prompt: 'Negative Prompt', - use_stable_diffusion_model: 'Stable Diffusion model', - use_hypernetwork_model: 'Hypernetwork model', - hypernetwork_strength: 'Hypernetwork Strength' + prompt: "Prompt", + width: "Width", + height: "Height", + seed: "Seed", + num_inference_steps: "Steps", + guidance_scale: "Guidance Scale", + prompt_strength: "Prompt Strength", + use_face_correction: "Use Face Correction", + use_upscale: "Use Upscaling", + upscale_amount: "Upscale By", + sampler_name: "Sampler", + negative_prompt: "Negative Prompt", + use_stable_diffusion_model: "Stable Diffusion model", + use_hypernetwork_model: "Hypernetwork model", + hypernetwork_strength: "Hypernetwork Strength", } function parseTaskFromText(str) { const taskReqBody = {} - const lines = str.split('\n') + const lines = str.split("\n") if (lines.length === 0) { return } @@ -441,14 +532,14 @@ function parseTaskFromText(str) { // Prompt let knownKeyOnFirstLine = false for (let key in TASK_TEXT_MAPPING) { - if (lines[0].startsWith(TASK_TEXT_MAPPING[key] + ':')) { + if (lines[0].startsWith(TASK_TEXT_MAPPING[key] + ":")) { knownKeyOnFirstLine = true break } } if (!knownKeyOnFirstLine) { taskReqBody.prompt = lines[0] - console.log('Prompt:', taskReqBody.prompt) + console.log("Prompt:", taskReqBody.prompt) } for (const key in TASK_TEXT_MAPPING) { @@ -456,18 +547,18 @@ function parseTaskFromText(str) { continue } - const name = TASK_TEXT_MAPPING[key]; + const name = TASK_TEXT_MAPPING[key] let val = undefined - const reName = new RegExp(`${name}\\ *:\\ *(.*)(?:\\r\\n|\\r|\\n)*`, 'igm') - const match = reName.exec(str); + const reName = new RegExp(`${name}\\ *:\\ *(.*)(?:\\r\\n|\\r|\\n)*`, "igm") + const match = reName.exec(str) if (match) { str = str.slice(0, match.index) + str.slice(match.index + match[0].length) val = match[1] } if (val !== undefined) { taskReqBody[key] = TASK_MAPPING[key].parse(val.trim()) - console.log(TASK_MAPPING[key].name + ':', taskReqBody[key]) + console.log(TASK_MAPPING[key].name + ":", taskReqBody[key]) if (!str) { break } @@ -477,18 +568,19 @@ function parseTaskFromText(str) { return undefined } const task = { reqBody: taskReqBody } - if ('seed' in taskReqBody) { + if ("seed" in taskReqBody) { task.seed = taskReqBody.seed } return task } async function parseContent(text) { - text = text.trim(); - if (text.startsWith('{') && text.endsWith('}')) { + text = text.trim() + if (text.startsWith("{") && text.endsWith("}")) { try { const task = JSON.parse(text) - if (!('reqBody' in task)) { // support the format saved to the disk, by the UI + if (!("reqBody" in task)) { + // support the format saved to the disk, by the UI task.reqBody = Object.assign({}, task) } restoreTaskToUI(task) @@ -500,7 +592,8 @@ async function parseContent(text) { } // Normal txt file. const task = parseTaskFromText(text) - if (text.toLowerCase().includes('seed:') && task) { // only parse valid task content + if (text.toLowerCase().includes("seed:") && task) { + // only parse valid task content restoreTaskToUI(task) return true } else { @@ -517,21 +610,25 @@ async function readFile(file, i) { } function dropHandler(ev) { - console.log('Content dropped...') + console.log("Content dropped...") let items = [] - if (ev?.dataTransfer?.items) { // Use DataTransferItemList interface + if (ev?.dataTransfer?.items) { + // Use DataTransferItemList interface items = Array.from(ev.dataTransfer.items) - items = items.filter(item => item.kind === 'file') - items = items.map(item => item.getAsFile()) - } else if (ev?.dataTransfer?.files) { // Use DataTransfer interface + items = items.filter((item) => item.kind === "file") + items = items.map((item) => item.getAsFile()) + } else if (ev?.dataTransfer?.files) { + // Use DataTransfer interface items = Array.from(ev.dataTransfer.files) } - items.forEach(item => {item.file_ext = EXT_REGEX.exec(item.name.toLowerCase())[1]}) + items.forEach((item) => { + item.file_ext = EXT_REGEX.exec(item.name.toLowerCase())[1] + }) - let text_items = items.filter(item => TEXT_EXTENSIONS.includes(item.file_ext)) - let image_items = items.filter(item => IMAGE_EXTENSIONS.includes(item.file_ext)) + let text_items = items.filter((item) => TEXT_EXTENSIONS.includes(item.file_ext)) + let image_items = items.filter((item) => IMAGE_EXTENSIONS.includes(item.file_ext)) if (image_items.length > 0 && ev.target == initImageSelector) { return // let the event bubble up, so that the Init Image filepicker can receive this @@ -541,7 +638,7 @@ function dropHandler(ev) { text_items.forEach(readFile) } function dragOverHandler(ev) { - console.log('Content in drop zone') + console.log("Content in drop zone") // Prevent default behavior (Prevent file/content from being opened) ev.preventDefault() @@ -549,73 +646,72 @@ function dragOverHandler(ev) { ev.dataTransfer.dropEffect = "copy" let img = new Image() - img.src = '//' + location.host + '/media/images/favicon-32x32.png' + img.src = "//" + location.host + "/media/images/favicon-32x32.png" ev.dataTransfer.setDragImage(img, 16, 16) } document.addEventListener("drop", dropHandler) document.addEventListener("dragover", dragOverHandler) -const TASK_REQ_NO_EXPORT = [ - "use_cpu", - "save_to_disk_path" -] -const resetSettings = document.getElementById('reset-image-settings') +const TASK_REQ_NO_EXPORT = ["use_cpu", "save_to_disk_path"] +const resetSettings = document.getElementById("reset-image-settings") -function checkReadTextClipboardPermission (result) { +function checkReadTextClipboardPermission(result) { if (result.state != "granted" && result.state != "prompt") { return } // PASTE ICON - const pasteIcon = document.createElement('i') - pasteIcon.className = 'fa-solid fa-paste section-button' + const pasteIcon = document.createElement("i") + pasteIcon.className = "fa-solid fa-paste section-button" pasteIcon.innerHTML = `Paste Image Settings` - pasteIcon.addEventListener('click', async (event) => { + pasteIcon.addEventListener("click", async (event) => { event.stopPropagation() // Add css class 'active' - pasteIcon.classList.add('active') + pasteIcon.classList.add("active") // In 350 ms remove the 'active' class - asyncDelay(350).then(() => pasteIcon.classList.remove('active')) + asyncDelay(350).then(() => pasteIcon.classList.remove("active")) // Retrieve clipboard content and try to parse it - const text = await navigator.clipboard.readText(); + const text = await navigator.clipboard.readText() await parseContent(text) }) resetSettings.parentNode.insertBefore(pasteIcon, resetSettings) } -navigator.permissions.query({ name: "clipboard-read" }).then(checkReadTextClipboardPermission, (reason) => console.log('clipboard-read is not available. %o', reason)) +navigator.permissions + .query({ name: "clipboard-read" }) + .then(checkReadTextClipboardPermission, (reason) => console.log("clipboard-read is not available. %o", reason)) -document.addEventListener('paste', async (event) => { +document.addEventListener("paste", async (event) => { if (event.target) { const targetTag = event.target.tagName.toLowerCase() // Disable when targeting input elements. - if (targetTag === 'input' || targetTag === 'textarea') { + if (targetTag === "input" || targetTag === "textarea") { return } } - const paste = (event.clipboardData || window.clipboardData).getData('text') + const paste = (event.clipboardData || window.clipboardData).getData("text") const selection = window.getSelection() - if (selection.toString().trim().length <= 0 && await parseContent(paste)) { + if (paste != "" && selection.toString().trim().length <= 0 && (await parseContent(paste))) { event.preventDefault() return } }) // Adds a copy and a paste icon if the browser grants permission to write to clipboard. -function checkWriteToClipboardPermission (result) { +function checkWriteToClipboardPermission(result) { if (result.state != "granted" && result.state != "prompt") { return } // COPY ICON - const copyIcon = document.createElement('i') - copyIcon.className = 'fa-solid fa-clipboard section-button' + const copyIcon = document.createElement("i") + copyIcon.className = "fa-solid fa-clipboard section-button" copyIcon.innerHTML = `Copy Image Settings` - copyIcon.addEventListener('click', (event) => { + copyIcon.addEventListener("click", (event) => { event.stopPropagation() // Add css class 'active' - copyIcon.classList.add('active') + copyIcon.classList.add("active") // In 350 ms remove the 'active' class - asyncDelay(350).then(() => copyIcon.classList.remove('active')) + asyncDelay(350).then(() => copyIcon.classList.remove("active")) const uiState = readUI() TASK_REQ_NO_EXPORT.forEach((key) => delete uiState.reqBody[key]) if (uiState.reqBody.init_image && !IMAGE_REGEX.test(uiState.reqBody.init_image)) { @@ -628,8 +724,8 @@ function checkWriteToClipboardPermission (result) { } // Determine which access we have to the clipboard. Clipboard access is only available on localhost or via TLS. navigator.permissions.query({ name: "clipboard-write" }).then(checkWriteToClipboardPermission, (e) => { - if (e instanceof TypeError && typeof navigator?.clipboard?.writeText === 'function') { + if (e instanceof TypeError && typeof navigator?.clipboard?.writeText === "function") { // Fix for firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1560373 - checkWriteToClipboardPermission({state:"granted"}) + checkWriteToClipboardPermission({ state: "granted" }) } }) diff --git a/ui/media/js/engine.js b/ui/media/js/engine.js index 02871b23..f3ce0551 100644 --- a/ui/media/js/engine.js +++ b/ui/media/js/engine.js @@ -1,6 +1,7 @@ /** SD-UI Backend control and classes. */ -(function () { "use strict"; +;(function() { + "use strict" const RETRY_DELAY_IF_BUFFER_IS_EMPTY = 1000 // ms const RETRY_DELAY_IF_SERVER_IS_BUSY = 30 * 1000 // ms, status_code 503, already a task running const RETRY_DELAY_ON_ERROR = 4000 // ms @@ -14,25 +15,28 @@ * Allows closing the connection while the server buffers more data. */ class ChunkedStreamReader { - #bufferedString = '' // Data received waiting to be read. + #bufferedString = "" // Data received waiting to be read. #url #fetchOptions #response - constructor(url, initialContent='', options={}) { - if (typeof url !== 'string' && !(url instanceof String)) { - throw new Error('url is not a string.') + constructor(url, initialContent = "", options = {}) { + if (typeof url !== "string" && !(url instanceof String)) { + throw new Error("url is not a string.") } - if (typeof initialContent !== 'undefined' && typeof initialContent !== 'string') { - throw new Error('initialContent is not a string.') + if (typeof initialContent !== "undefined" && typeof initialContent !== "string") { + throw new Error("initialContent is not a string.") } this.#bufferedString = initialContent this.#url = url - this.#fetchOptions = Object.assign({ - headers: { - 'Content-Type': 'application/json' - } - }, options) + this.#fetchOptions = Object.assign( + { + headers: { + "Content-Type": "application/json", + }, + }, + options + ) this.onNext = undefined } @@ -53,7 +57,7 @@ } parse(value) { - if (typeof value === 'undefined') { + if (typeof value === "undefined") { return } if (!isArrayOrTypedArray(value)) { @@ -62,7 +66,7 @@ if (value.length === 0) { return value } - if (typeof this.textDecoder === 'undefined') { + if (typeof this.textDecoder === "undefined") { this.textDecoder = new TextDecoder() } return [this.textDecoder.decode(value)] @@ -73,8 +77,8 @@ onError(response) { throw new Error(response.statusText) } - onNext({value, done}, response) { - return {value, done} + onNext({ value, done }, response) { + return { value, done } } async *[Symbol.asyncIterator]() { @@ -93,9 +97,9 @@ continue } // Request status indicate failure - console.warn('Stream %o stopped unexpectedly.', this.#response) + console.warn("Stream %o stopped unexpectedly.", this.#response) value = await Promise.resolve(this.onError(this.#response)) - if (typeof value === 'boolean' && value) { + if (typeof value === "boolean" && value) { continue } return value @@ -106,8 +110,10 @@ const readState = await reader.read() value = this.parse(readState.value) if (value) { - for(let sVal of value) { - ({value: sVal, done} = await Promise.resolve(this.onNext({value:sVal, done:readState.done}))) + for (let sVal of value) { + ;({ value: sVal, done } = await Promise.resolve( + this.onNext({ value: sVal, done: readState.done }) + )) yield sVal if (done) { return this.onComplete(sVal) @@ -117,12 +123,12 @@ if (done) { return } - } while(value && !done) + } while (value && !done) } while (!done && (this.#response.ok || this.#response.status === 425)) } *readStreamAsJSON(jsonStr, throwOnError) { - if (typeof jsonStr !== 'string') { - throw new Error('jsonStr is not a string.') + if (typeof jsonStr !== "string") { + throw new Error("jsonStr is not a string.") } do { if (this.#bufferedString.length > 0) { @@ -132,19 +138,19 @@ } else { jsonStr = this.#bufferedString } - this.#bufferedString = '' + this.#bufferedString = "" } if (!jsonStr) { return } // Find next delimiter - let lastChunkIdx = jsonStr.indexOf('}{') + let lastChunkIdx = jsonStr.indexOf("}{") if (lastChunkIdx >= 0) { this.#bufferedString = jsonStr.substring(0, lastChunkIdx + 1) jsonStr = jsonStr.substring(lastChunkIdx + 1) } else { this.#bufferedString = jsonStr - jsonStr = '' + jsonStr = "" } if (this.#bufferedString.length <= 0) { return @@ -153,10 +159,11 @@ // this results in having to parse JSON like {"step": 1}{"step": 2}{"step": 3}{"ste... // which is obviously invalid and can happen at any point while rendering. // So we need to extract only the next {} section - try { // Try to parse + try { + // Try to parse const jsonObj = JSON.parse(this.#bufferedString) this.#bufferedString = jsonStr - jsonStr = '' + jsonStr = "" yield jsonObj } catch (e) { if (throwOnError) { @@ -168,18 +175,19 @@ } throw e } - } while (this.#bufferedString.length > 0 && this.#bufferedString.indexOf('}') >= 0) + } while (this.#bufferedString.length > 0 && this.#bufferedString.indexOf("}") >= 0) } } - const EVENT_IDLE = 'idle' - const EVENT_STATUS_CHANGED = 'statusChange' - const EVENT_UNHANDLED_REJECTION = 'unhandledRejection' - const EVENT_TASK_QUEUED = 'taskQueued' - const EVENT_TASK_START = 'taskStart' - const EVENT_TASK_END = 'taskEnd' - const EVENT_TASK_ERROR = 'task_error' - const EVENT_UNEXPECTED_RESPONSE = 'unexpectedResponse' + const EVENT_IDLE = "idle" + const EVENT_STATUS_CHANGED = "statusChange" + const EVENT_UNHANDLED_REJECTION = "unhandledRejection" + const EVENT_TASK_QUEUED = "taskQueued" + const EVENT_TASK_START = "taskStart" + const EVENT_TASK_END = "taskEnd" + const EVENT_TASK_ERROR = "task_error" + const EVENT_PING = "ping" + const EVENT_UNEXPECTED_RESPONSE = "unexpectedResponse" const EVENTS_TYPES = [ EVENT_IDLE, EVENT_STATUS_CHANGED, @@ -189,6 +197,7 @@ EVENT_TASK_START, EVENT_TASK_END, EVENT_TASK_ERROR, + EVENT_PING, EVENT_UNEXPECTED_RESPONSE, ] @@ -196,79 +205,82 @@ const eventSource = new GenericEventSource(EVENTS_TYPES) function setServerStatus(msgType, msg) { - return eventSource.fireEvent(EVENT_STATUS_CHANGED, {type: msgType, message: msg}) + return eventSource.fireEvent(EVENT_STATUS_CHANGED, { type: msgType, message: msg }) } const ServerStates = { - init: 'Init', - loadingModel: 'LoadingModel', - online: 'Online', - rendering: 'Rendering', - unavailable: 'Unavailable', + init: "Init", + loadingModel: "LoadingModel", + online: "Online", + rendering: "Rendering", + unavailable: "Unavailable", } Object.freeze(ServerStates) let sessionId = Date.now() - let serverState = {'status': ServerStates.unavailable, 'time': Date.now()} + let serverState = { status: ServerStates.unavailable, time: Date.now() } async function healthCheck() { - if (Date.now() < serverState.time + (HEALTH_PING_INTERVAL / 2) && isServerAvailable()) { + if (Date.now() < serverState.time + HEALTH_PING_INTERVAL / 2 && isServerAvailable()) { // Ping confirmed online less than half of HEALTH_PING_INTERVAL ago. return true } if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) { - console.warn('WARNING! SERVER_STATE_VALIDITY_DURATION has elapsed since the last Ping completed.') + console.warn("WARNING! SERVER_STATE_VALIDITY_DURATION has elapsed since the last Ping completed.") } try { let res = undefined - if (typeof sessionId !== 'undefined') { - res = await fetch('/ping?session_id=' + sessionId) + if (typeof sessionId !== "undefined") { + res = await fetch("/ping?session_id=" + sessionId) } else { - res = await fetch('/ping') + res = await fetch("/ping") } serverState = await res.json() - if (typeof serverState !== 'object' || typeof serverState.status !== 'string') { + if (typeof serverState !== "object" || typeof serverState.status !== "string") { console.error(`Server reply didn't contain a state value.`) - serverState = {'status': ServerStates.unavailable, 'time': Date.now()} - setServerStatus('error', 'offline') + serverState = { status: ServerStates.unavailable, time: Date.now() } + setServerStatus("error", "offline") return false } + // Set status - switch(serverState.status) { + switch (serverState.status) { case ServerStates.init: // Wait for init to complete before updating status. break case ServerStates.online: - setServerStatus('online', 'ready') + setServerStatus("online", "ready") break case ServerStates.loadingModel: - setServerStatus('busy', 'loading..') + setServerStatus("busy", "loading..") break case ServerStates.rendering: - setServerStatus('busy', 'rendering..') + setServerStatus("busy", "rendering..") break - default: // Unavailable - console.error('Ping received an unexpected server status. Status: %s', serverState.status) - setServerStatus('error', serverState.status.toLowerCase()) + default: + // Unavailable + console.error("Ping received an unexpected server status. Status: %s", serverState.status) + setServerStatus("error", serverState.status.toLowerCase()) break } serverState.time = Date.now() + await eventSource.fireEvent(EVENT_PING, serverState) return true } catch (e) { console.error(e) - serverState = {'status': ServerStates.unavailable, 'time': Date.now()} - setServerStatus('error', 'offline') + serverState = { status: ServerStates.unavailable, time: Date.now() } + setServerStatus("error", "offline") } return false } function isServerAvailable() { - if (typeof serverState !== 'object') { - console.error('serverState not set to a value. Connection to server could be lost...') + if (typeof serverState !== "object") { + console.error("serverState not set to a value. Connection to server could be lost...") return false } if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) { - console.warn('SERVER_STATE_VALIDITY_DURATION elapsed. Connection to server could be lost...') + console.warn("SERVER_STATE_VALIDITY_DURATION elapsed. Connection to server could be lost...") return false } switch (serverState.status) { @@ -277,51 +289,54 @@ case ServerStates.online: return true default: - console.warn('Unexpected server status. Server could be unavailable... Status: %s', serverState.status) + console.warn("Unexpected server status. Server could be unavailable... Status: %s", serverState.status) return false } } async function waitUntil(isReadyFn, delay, timeout) { - if (typeof delay === 'number') { + if (typeof delay === "number") { const msDelay = delay delay = () => asyncDelay(msDelay) } - if (typeof delay !== 'function') { - throw new Error('delay is not a number or a function.') + if (typeof delay !== "function") { + throw new Error("delay is not a number or a function.") } - if (typeof timeout !== 'undefined' && typeof timeout !== 'number') { - throw new Error('timeout is not a number.') + if (typeof timeout !== "undefined" && typeof timeout !== "number") { + throw new Error("timeout is not a number.") } - if (typeof timeout === 'undefined' || timeout < 0) { + if (typeof timeout === "undefined" || timeout < 0) { timeout = Number.MAX_SAFE_INTEGER } timeout = Date.now() + timeout - while (timeout > Date.now() - && Date.now() < serverState.time + SERVER_STATE_VALIDITY_DURATION - && !Boolean(await Promise.resolve(isReadyFn())) + while ( + timeout > Date.now() && + Date.now() < serverState.time + SERVER_STATE_VALIDITY_DURATION && + !Boolean(await Promise.resolve(isReadyFn())) ) { await delay() - if (!isServerAvailable()) { // Can fail if ping got frozen/suspended... - if (await healthCheck() && isServerAvailable()) { // Force a recheck of server status before failure... + if (!isServerAvailable()) { + // Can fail if ping got frozen/suspended... + if ((await healthCheck()) && isServerAvailable()) { + // Force a recheck of server status before failure... continue // Continue waiting if last healthCheck confirmed the server is still alive. } - throw new Error('Connection with server lost.') + throw new Error("Connection with server lost.") } } if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) { - console.warn('SERVER_STATE_VALIDITY_DURATION elapsed. Released waitUntil on stale server state.') + console.warn("SERVER_STATE_VALIDITY_DURATION elapsed. Released waitUntil on stale server state.") } } const TaskStatus = { - init: 'init', - pending: 'pending', // Queued locally, not yet posted to server - waiting: 'waiting', // Waiting to run on server - processing: 'processing', - stopped: 'stopped', - completed: 'completed', - failed: 'failed', + init: "init", + pending: "pending", // Queued locally, not yet posted to server + waiting: "waiting", // Waiting to run on server + processing: "processing", + stopped: "stopped", + completed: "completed", + failed: "failed", } Object.freeze(TaskStatus) @@ -345,12 +360,15 @@ #id = undefined #exception = undefined - constructor(options={}) { + constructor(options = {}) { this._reqBody = Object.assign({}, options) - if (typeof this._reqBody.session_id === 'undefined') { + if (typeof this._reqBody.session_id === "undefined") { this._reqBody.session_id = sessionId - } else if (this._reqBody.session_id !== SD.sessionId && String(this._reqBody.session_id) !== String(SD.sessionId)) { - throw new Error('Use SD.sessionId to set the request session_id.') + } else if ( + this._reqBody.session_id !== SD.sessionId && + String(this._reqBody.session_id) !== String(SD.sessionId) + ) { + throw new Error("Use SD.sessionId to set the request session_id.") } this._reqBody.session_id = String(this._reqBody.session_id) } @@ -359,8 +377,8 @@ return this.#id } _setId(id) { - if (typeof this.#id !== 'undefined') { - throw new Error('The task ID can only be set once.') + if (typeof this.#id !== "undefined") { + throw new Error("The task ID can only be set once.") } this.#id = id } @@ -372,32 +390,32 @@ if (this.isCompleted || this.isStopped || this.hasFailed) { return } - if (typeof exception !== 'undefined') { - if (typeof exception === 'string') { + if (typeof exception !== "undefined") { + if (typeof exception === "string") { exception = new Error(exception) } - if (typeof exception !== 'object') { - throw new Error('exception is not an object.') + if (typeof exception !== "object") { + throw new Error("exception is not an object.") } if (!(exception instanceof Error)) { - throw new Error('exception is not an Error or a string.') + throw new Error("exception is not an Error or a string.") } } - const res = await fetch('/image/stop?task=' + this.id) + const res = await fetch("/image/stop?task=" + this.id) if (!res.ok) { - console.log('Stop response:', res) + console.log("Stop response:", res) throw new Error(res.statusText) } task_queue.delete(this) this.#exception = exception - this.#status = (exception ? TaskStatus.failed : TaskStatus.stopped) + this.#status = exception ? TaskStatus.failed : TaskStatus.stopped } get reqBody() { if (this.#status === TaskStatus.init) { return this._reqBody } - console.warn('Task reqBody cannot be changed after the init state.') + console.warn("Task reqBody cannot be changed after the init state.") return Object.assign({}, this._reqBody) } @@ -436,29 +454,29 @@ * @returns the response from the render request. * @memberof Task */ - async post(url, timeout=-1) { - if(this.status !== TaskStatus.init && this.status !== TaskStatus.pending) { + async post(url, timeout = -1) { + if (this.status !== TaskStatus.init && this.status !== TaskStatus.pending) { throw new Error(`Task status ${this.status} is not valid for post.`) } this._setStatus(TaskStatus.pending) Object.freeze(this._reqBody) - const abortSignal = (timeout >= 0 ? AbortSignal.timeout(timeout) : undefined) + const abortSignal = timeout >= 0 ? AbortSignal.timeout(timeout) : undefined let res = undefined try { this.checkReqBody() do { abortSignal?.throwIfAborted() res = await fetch(url, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json' + "Content-Type": "application/json", }, body: JSON.stringify(this._reqBody), - signal: abortSignal + signal: abortSignal, }) // status_code 503, already a task running. - } while (res.status === 503 && await asyncDelay(RETRY_DELAY_IF_SERVER_IS_BUSY)) + } while (res.status === 503 && (await asyncDelay(RETRY_DELAY_IF_SERVER_IS_BUSY))) } catch (err) { this.abort(err) throw err @@ -479,20 +497,20 @@ if (!value || value.length <= 0) { return } - return reader.readStreamAsJSON(value.join('')) + return reader.readStreamAsJSON(value.join("")) } - reader.onNext = function({done, value}) { + reader.onNext = function({ done, value }) { // By default is completed when the return value has a status defined. - if (typeof value === 'object' && 'status' in value) { + if (typeof value === "object" && "status" in value) { done = true } - return {done, value} + return { done, value } } return reader } _setReader(reader) { - if (typeof this.#reader !== 'undefined') { - throw new Error('The task reader can only be set once.') + if (typeof this.#reader !== "undefined") { + throw new Error("The task reader can only be set once.") } this.#reader = reader } @@ -501,25 +519,26 @@ return this.#reader } if (!this.streamUrl) { - throw new Error('The task has no stream Url defined.') + throw new Error("The task has no stream Url defined.") } this.#reader = Task.getReader(this.streamUrl) const task = this const onNext = this.#reader.onNext - this.#reader.onNext = function({done, value}) { - if (value && typeof value === 'object') { - if (task.status === TaskStatus.init - || task.status === TaskStatus.pending - || task.status === TaskStatus.waiting + this.#reader.onNext = function({ done, value }) { + if (value && typeof value === "object") { + if ( + task.status === TaskStatus.init || + task.status === TaskStatus.pending || + task.status === TaskStatus.waiting ) { task._setStatus(TaskStatus.processing) } - if ('step' in value && 'total_steps' in value) { + if ("step" in value && "total_steps" in value) { task.step = value.step task.total_steps = value.total_steps } } - return onNext.call(this, {done, value}) + return onNext.call(this, { done, value }) } this.#reader.onComplete = function(value) { task.result = value @@ -536,12 +555,12 @@ return this.#reader } - async waitUntil({timeout=-1, callback, status, signal}) { + async waitUntil({ timeout = -1, callback, status, signal }) { const currentIdx = TASK_STATUS_ORDER.indexOf(this.#status) if (currentIdx <= 0) { return false } - const stIdx = (status ? TASK_STATUS_ORDER.indexOf(status) : currentIdx + 1) + const stIdx = status ? TASK_STATUS_ORDER.indexOf(status) : currentIdx + 1 if (stIdx >= 0 && stIdx <= currentIdx) { return true } @@ -552,26 +571,34 @@ return false } const task = this - switch(this.#status) { + switch (this.#status) { case TaskStatus.pending: case TaskStatus.waiting: // Wait for server status to include this task. await waitUntil( async () => { - if (task.#id && typeof serverState.tasks === 'object' && Object.keys(serverState.tasks).includes(String(task.#id))) { + if ( + task.#id && + typeof serverState.tasks === "object" && + Object.keys(serverState.tasks).includes(String(task.#id)) + ) { return true } - if (await Promise.resolve(callback?.call(task)) || signal?.aborted) { + if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) { return true } }, TASK_STATE_SERVER_UPDATE_DELAY, - timeout, + timeout ) - if (this.#id && typeof serverState.tasks === 'object' && Object.keys(serverState.tasks).includes(String(task.#id))) { + if ( + this.#id && + typeof serverState.tasks === "object" && + Object.keys(serverState.tasks).includes(String(task.#id)) + ) { this._setStatus(TaskStatus.waiting) } - if (await Promise.resolve(callback?.call(this)) || signal?.aborted) { + if ((await Promise.resolve(callback?.call(this))) || signal?.aborted) { return false } if (stIdx >= 0 && stIdx <= TASK_STATUS_ORDER.indexOf(TaskStatus.waiting)) { @@ -580,21 +607,25 @@ // Wait for task to start on server. await waitUntil( async () => { - if (typeof serverState.tasks !== 'object' || serverState.tasks[String(task.#id)] !== 'pending') { + if ( + typeof serverState.tasks !== "object" || + serverState.tasks[String(task.#id)] !== "pending" + ) { return true } - if (await Promise.resolve(callback?.call(task)) || signal?.aborted) { + if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) { return true } }, TASK_STATE_SERVER_UPDATE_DELAY, - timeout, + timeout ) - const state = (typeof serverState.tasks === 'object' ? serverState.tasks[String(task.#id)] : undefined) - if (state === 'running' || state === 'buffer' || state === 'completed') { + const state = + typeof serverState.tasks === "object" ? serverState.tasks[String(task.#id)] : undefined + if (state === "running" || state === "buffer" || state === "completed") { this._setStatus(TaskStatus.processing) } - if (await Promise.resolve(callback?.call(task)) || signal?.aborted) { + if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) { return false } if (stIdx >= 0 && stIdx <= TASK_STATUS_ORDER.indexOf(TaskStatus.processing)) { @@ -603,15 +634,18 @@ case TaskStatus.processing: await waitUntil( async () => { - if (typeof serverState.tasks !== 'object' || serverState.tasks[String(task.#id)] !== 'running') { + if ( + typeof serverState.tasks !== "object" || + serverState.tasks[String(task.#id)] !== "running" + ) { return true } - if (await Promise.resolve(callback?.call(task)) || signal?.aborted) { + if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) { return true } }, TASK_STATE_SERVER_UPDATE_DELAY, - timeout, + timeout ) await Promise.resolve(callback?.call(this)) default: @@ -625,22 +659,22 @@ } this._setStatus(TaskStatus.pending) task_queue.set(this, promiseGenerator) - await eventSource.fireEvent(EVENT_TASK_QUEUED, {task:this}) + await eventSource.fireEvent(EVENT_TASK_QUEUED, { task: this }) await Task.enqueue(promiseGenerator, ...args) - await this.waitUntil({status: TaskStatus.completed}) + await this.waitUntil({ status: TaskStatus.completed }) if (this.exception) { throw this.exception } return this.result } static async enqueue(promiseGenerator, ...args) { - if (typeof promiseGenerator === 'undefined') { - throw new Error('To enqueue a concurrent task, a *Promise Generator is needed but undefined was found.') + if (typeof promiseGenerator === "undefined") { + throw new Error("To enqueue a concurrent task, a *Promise Generator is needed but undefined was found.") } //if (Symbol.asyncIterator in result || Symbol.iterator in result) { - //concurrent_generators.set(result, Promise.resolve(args)) - if (typeof promiseGenerator === 'function') { - concurrent_generators.set(asGenerator({callback: promiseGenerator}), Promise.resolve(args)) + //concurrent_generators.set(result, Promise.resolve(args)) + if (typeof promiseGenerator === "function") { + concurrent_generators.set(asGenerator({ callback: promiseGenerator }), Promise.resolve(args)) } else { concurrent_generators.set(promiseGenerator, Promise.resolve(args)) } @@ -649,23 +683,23 @@ } static enqueueNew(task, classCtor, progressCallback) { if (task.status !== TaskStatus.init) { - throw new Error('Task has an invalid status to add to queue.') + throw new Error("Task has an invalid status to add to queue.") } if (!(task instanceof classCtor)) { - throw new Error('Task is not a instance of classCtor.') + throw new Error("Task is not a instance of classCtor.") } let promiseGenerator = undefined - if (typeof progressCallback === 'undefined') { + if (typeof progressCallback === "undefined") { promiseGenerator = classCtor.start(task) - } else if (typeof progressCallback === 'function') { + } else if (typeof progressCallback === "function") { promiseGenerator = classCtor.start(task, progressCallback) } else { - throw new Error('progressCallback is not a function.') + throw new Error("progressCallback is not a function.") } return Task.prototype.enqueue.call(task, promiseGenerator) } - static async run(promiseGenerator, {callback, signal, timeout=-1}={}) { + static async run(promiseGenerator, { callback, signal, timeout = -1 } = {}) { let value = undefined let done = undefined if (timeout < 0) { @@ -673,20 +707,20 @@ } timeout = Date.now() + timeout do { - ({value, done} = await Promise.resolve(promiseGenerator.next(value))) + ;({ value, done } = await Promise.resolve(promiseGenerator.next(value))) if (value instanceof Promise) { value = await value } if (callback) { - ({value, done} = await Promise.resolve(callback.call(promiseGenerator, {value, done}))) + ;({ value, done } = await Promise.resolve(callback.call(promiseGenerator, { value, done }))) } if (value instanceof Promise) { value = await value } - } while(!done && !signal?.aborted && timeout > Date.now()) + } while (!done && !signal?.aborted && timeout > Date.now()) return value } - static async *asGenerator({callback, generator, signal, timeout=-1}={}) { + static async *asGenerator({ callback, generator, signal, timeout = -1 } = {}) { let value = undefined let done = undefined if (timeout < 0) { @@ -694,106 +728,115 @@ } timeout = Date.now() + timeout do { - ({value, done} = await Promise.resolve(generator.next(value))) + ;({ value, done } = await Promise.resolve(generator.next(value))) if (value instanceof Promise) { value = await value } if (callback) { - ({value, done} = await Promise.resolve(callback.call(generator, {value, done}))) + ;({ value, done } = await Promise.resolve(callback.call(generator, { value, done }))) if (value instanceof Promise) { value = await value } } value = yield value - } while(!done && !signal?.aborted && timeout > Date.now()) + } while (!done && !signal?.aborted && timeout > Date.now()) return value } } const TASK_REQUIRED = { - "session_id": 'string', - "prompt": 'string', - "negative_prompt": 'string', - "width": 'number', - "height": 'number', - "seed": 'number', + session_id: "string", + prompt: "string", + negative_prompt: "string", + width: "number", + height: "number", + seed: "number", - "sampler_name": 'string', - "use_stable_diffusion_model": 'string', - "num_inference_steps": 'number', - "guidance_scale": 'number', + sampler_name: "string", + use_stable_diffusion_model: "string", + clip_skip: "boolean", + num_inference_steps: "number", + guidance_scale: "number", - "num_outputs": 'number', - "stream_progress_updates": 'boolean', - "stream_image_progress": 'boolean', - "show_only_filtered_image": 'boolean', - "output_format": 'string', - "output_quality": 'number', + num_outputs: "number", + stream_progress_updates: "boolean", + stream_image_progress: "boolean", + show_only_filtered_image: "boolean", + output_format: "string", + output_quality: "number", } const TASK_DEFAULTS = { - "sampler_name": "plms", - "use_stable_diffusion_model": "sd-v1-4", - "num_inference_steps": 50, - "guidance_scale": 7.5, - "negative_prompt": "", + sampler_name: "plms", + use_stable_diffusion_model: "sd-v1-4", + clip_skip: false, + num_inference_steps: 50, + guidance_scale: 7.5, + negative_prompt: "", - "num_outputs": 1, - "stream_progress_updates": true, - "stream_image_progress": true, - "show_only_filtered_image": true, - "block_nsfw": false, - "output_format": "png", - "output_quality": 75, - "output_lossless": false, + num_outputs: 1, + stream_progress_updates: true, + stream_image_progress: true, + show_only_filtered_image: true, + block_nsfw: false, + output_format: "png", + output_quality: 75, + output_lossless: false, } const TASK_OPTIONAL = { - "device": 'string', - "init_image": 'string', - "mask": 'string', - "save_to_disk_path": 'string', - "use_face_correction": 'string', - "use_upscale": 'string', - "use_vae_model": 'string', - "use_hypernetwork_model": 'string', - "hypernetwork_strength": 'number', - "output_lossless": 'boolean', + device: "string", + init_image: "string", + mask: "string", + save_to_disk_path: "string", + use_face_correction: "string", + use_upscale: "string", + use_vae_model: "string", + use_hypernetwork_model: "string", + hypernetwork_strength: "number", + output_lossless: "boolean", + tiling: "string", } - // Higer values will result in... + // Higher values will result in... // pytorch_lightning/utilities/seed.py:60: UserWarning: X is not in bounds, numpy accepts from 0 to 4294967295 const MAX_SEED_VALUE = 4294967295 class RenderTask extends Task { - constructor(options={}) { + constructor(options = {}) { super(options) - if (typeof this._reqBody.seed === 'undefined') { + if (typeof this._reqBody.seed === "undefined") { this._reqBody.seed = Math.floor(Math.random() * (MAX_SEED_VALUE + 1)) } - if (typeof typeof this._reqBody.seed === 'number' && (this._reqBody.seed > MAX_SEED_VALUE || this._reqBody.seed < 0)) { + if ( + typeof typeof this._reqBody.seed === "number" && + (this._reqBody.seed > MAX_SEED_VALUE || this._reqBody.seed < 0) + ) { throw new Error(`seed must be in range 0 to ${MAX_SEED_VALUE}.`) } - if ('use_cpu' in this._reqBody) { + if ("use_cpu" in this._reqBody) { if (this._reqBody.use_cpu) { - this._reqBody.device = 'cpu' + this._reqBody.device = "cpu" } delete this._reqBody.use_cpu } if (this._reqBody.init_image) { - if (typeof this._reqBody.prompt_strength === 'undefined') { + if (typeof this._reqBody.prompt_strength === "undefined") { this._reqBody.prompt_strength = 0.8 - } else if (typeof this._reqBody.prompt_strength !== 'number') { - throw new Error(`prompt_strength need to be of type number but ${typeof this._reqBody.prompt_strength} was found.`) + } else if (typeof this._reqBody.prompt_strength !== "number") { + throw new Error( + `prompt_strength need to be of type number but ${typeof this._reqBody + .prompt_strength} was found.` + ) } } - if ('modifiers' in this._reqBody) { + if ("modifiers" in this._reqBody) { if (Array.isArray(this._reqBody.modifiers) && this._reqBody.modifiers.length > 0) { this._reqBody.modifiers = this._reqBody.modifiers.filter((val) => val.trim()) if (this._reqBody.modifiers.length > 0) { - this._reqBody.prompt = `${this._reqBody.prompt}, ${this._reqBody.modifiers.join(', ')}` + this._reqBody.prompt = `${this._reqBody.prompt}, ${this._reqBody.modifiers.join(", ")}` } } - if (typeof this._reqBody.modifiers === 'string' && this._reqBody.modifiers.length > 0) { + if (typeof this._reqBody.modifiers === "string" && this._reqBody.modifiers.length > 0) { this._reqBody.modifiers = this._reqBody.modifiers.trim() if (this._reqBody.modifiers.length > 0) { this._reqBody.prompt = `${this._reqBody.prompt}, ${this._reqBody.modifiers}` @@ -806,13 +849,15 @@ checkReqBody() { for (const key in TASK_DEFAULTS) { - if (typeof this._reqBody[key] === 'undefined') { + if (typeof this._reqBody[key] === "undefined") { this._reqBody[key] = TASK_DEFAULTS[key] } } for (const key in TASK_REQUIRED) { if (typeof this._reqBody[key] !== TASK_REQUIRED[key]) { - throw new Error(`${key} need to be of type ${TASK_REQUIRED[key]} but ${typeof this._reqBody[key]} was found.`) + throw new Error( + `${key} need to be of type ${TASK_REQUIRED[key]} but ${typeof this._reqBody[key]} was found.` + ) } } for (const key in this._reqBody) { @@ -826,7 +871,11 @@ continue } if (typeof this._reqBody[key] !== TASK_OPTIONAL[key]) { - throw new Error(`${key} need to be of type ${TASK_OPTIONAL[key]} but ${typeof this._reqBody[key]} was found.`) + throw new Error( + `${key} need to be of type ${TASK_OPTIONAL[key]} but ${typeof this._reqBody[ + key + ]} was found.` + ) } } } @@ -837,23 +886,26 @@ * @returns the response from the render request. * @memberof Task */ - async post(timeout=-1) { - performance.mark('make-render-request') - if (performance.getEntriesByName('click-makeImage', 'mark').length > 0) { - performance.measure('diff', 'click-makeImage', 'make-render-request') - console.log('delay between clicking and making the server request:', performance.getEntriesByName('diff', 'measure')[0].duration + ' ms') + async post(timeout = -1) { + performance.mark("make-render-request") + if (performance.getEntriesByName("click-makeImage", "mark").length > 0) { + performance.measure("diff", "click-makeImage", "make-render-request") + console.log( + "delay between clicking and making the server request:", + performance.getEntriesByName("diff", "measure")[0].duration + " ms" + ) } - let jsonResponse = await super.post('/render', timeout) - if (typeof jsonResponse?.task !== 'number') { - console.warn('Endpoint error response: ', jsonResponse) - const event = Object.assign({task:this}, jsonResponse) + let jsonResponse = await super.post("/render", timeout) + if (typeof jsonResponse?.task !== "number") { + console.warn("Endpoint error response: ", jsonResponse) + const event = Object.assign({ task: this }, jsonResponse) await eventSource.fireEvent(EVENT_UNEXPECTED_RESPONSE, event) - if ('continueWith' in event) { + if ("continueWith" in event) { jsonResponse = await Promise.resolve(event.continueWith) } - if (typeof jsonResponse?.task !== 'number') { - const err = new Error(jsonResponse?.detail || 'Endpoint response does not contains a task ID.') + if (typeof jsonResponse?.task !== "number") { + const err = new Error(jsonResponse?.detail || "Endpoint response does not contains a task ID.") this.abort(err) throw err } @@ -870,29 +922,32 @@ return Task.enqueueNew(this, RenderTask, progressCallback) } *start(progressCallback) { - if (typeof progressCallback !== 'undefined' && typeof progressCallback !== 'function') { - throw new Error('progressCallback is not a function. progressCallback type: ' + typeof progressCallback) + if (typeof progressCallback !== "undefined" && typeof progressCallback !== "function") { + throw new Error("progressCallback is not a function. progressCallback type: " + typeof progressCallback) } if (this.isStopped) { return } this._setStatus(TaskStatus.pending) - progressCallback?.call(this, {reqBody: this._reqBody}) + progressCallback?.call(this, { reqBody: this._reqBody }) Object.freeze(this._reqBody) // Post task request to backend let renderRequest = undefined try { renderRequest = yield this.post() - yield progressCallback?.call(this, {renderResponse: renderRequest}) + yield progressCallback?.call(this, { renderResponse: renderRequest }) } catch (e) { yield progressCallback?.call(this, { detail: e.message }) throw e } - try { // Wait for task to start on server. + try { + // Wait for task to start on server. yield this.waitUntil({ - callback: function() { return progressCallback?.call(this, {}) }, + callback: function() { + return progressCallback?.call(this, {}) + }, status: TaskStatus.processing, }) } catch (e) { @@ -900,41 +955,39 @@ throw e } // Update class status and callback. - const taskState = (typeof serverState.tasks === 'object' ? serverState.tasks[String(this.id)] : undefined) - switch(taskState) { - case 'pending': // Session has pending tasks. - console.error('Server %o render request %o is still waiting.', serverState, renderRequest) + const taskState = typeof serverState.tasks === "object" ? serverState.tasks[String(this.id)] : undefined + switch (taskState) { + case "pending": // Session has pending tasks. + console.error("Server %o render request %o is still waiting.", serverState, renderRequest) //Only update status if not already set by waitUntil - if (this.status === TaskStatus.init - || this.status === TaskStatus.pending - ) { + if (this.status === TaskStatus.init || this.status === TaskStatus.pending) { // Set status as Waiting in backend. this._setStatus(TaskStatus.waiting) } break - case 'running': - case 'buffer': + case "running": + case "buffer": // Normal expected messages. this._setStatus(TaskStatus.processing) break - case 'completed': + case "completed": if (this.isPending) { // Set state to processing until we read the reply this._setStatus(TaskStatus.processing) } - console.warn('Server %o render request %o completed unexpectedly', serverState, renderRequest) + console.warn("Server %o render request %o completed unexpectedly", serverState, renderRequest) break // Continue anyway to try to read cached result. - case 'error': + case "error": this._setStatus(TaskStatus.failed) - console.error('Server %o render request %o has failed', serverState, renderRequest) + console.error("Server %o render request %o has failed", serverState, renderRequest) break // Still valid, Update UI with error message - case 'stopped': + case "stopped": this._setStatus(TaskStatus.stopped) - console.log('Server %o render request %o was stopped', serverState, renderRequest) + console.log("Server %o render request %o was stopped", serverState, renderRequest) return false default: if (!progressCallback) { - const err = new Error('Unexpected server task state: ' + taskState || 'Undefined') + const err = new Error("Unexpected server task state: " + taskState || "Undefined") this.abort(err) throw err } @@ -967,17 +1020,17 @@ let done = undefined yield progressCallback?.call(this, { stream: streamGenerator }) do { - ({value, done} = yield streamGenerator.next()) - if (typeof value !== 'object') { + ;({ value, done } = yield streamGenerator.next()) + if (typeof value !== "object") { continue } yield progressCallback?.call(this, { update: value }) - } while(!done) + } while (!done) return value } static start(task, progressCallback) { - if (typeof task !== 'object') { - throw new Error ('task is not an object. task type: ' + typeof task) + if (typeof task !== "object") { + throw new Error("task is not an object. task type: " + typeof task) } if (!(task instanceof Task)) { if (task.reqBody) { @@ -994,15 +1047,14 @@ } } class FilterTask extends Task { - constructor(options={}) { - } + constructor(options = {}) {} /** Send current task to server. * @param {*} [timeout=-1] Optional timeout value in ms * @returns the response from the render request. * @memberof Task */ - async post(timeout=-1) { - let jsonResponse = await super.post('/filter', timeout) + async post(timeout = -1) { + let jsonResponse = await super.post("/filter", timeout) //this._setId(jsonResponse.task) this._setStatus(TaskStatus.waiting) } @@ -1010,16 +1062,16 @@ return Task.enqueueNew(this, FilterTask, progressCallback) } *start(progressCallback) { - if (typeof progressCallback !== 'undefined' && typeof progressCallback !== 'function') { - throw new Error('progressCallback is not a function. progressCallback type: ' + typeof progressCallback) + if (typeof progressCallback !== "undefined" && typeof progressCallback !== "function") { + throw new Error("progressCallback is not a function. progressCallback type: " + typeof progressCallback) } if (this.isStopped) { return } } static start(task, progressCallback) { - if (typeof task !== 'object') { - throw new Error ('task is not an object. task type: ' + typeof task) + if (typeof task !== "object") { + throw new Error("task is not an object. task type: " + typeof task) } if (!(task instanceof Task)) { if (task.reqBody) { @@ -1036,26 +1088,30 @@ } } - const getSystemInfo = debounce(async function() { - let systemInfo = { - devices: { - all: {}, - active: {}, - }, - hosts: [] - } - try { - const res = await fetch('/get/system_info') - if (!res.ok) { - console.error('Invalid response fetching devices', res.statusText) - return systemInfo + const getSystemInfo = debounce( + async function() { + let systemInfo = { + devices: { + all: {}, + active: {}, + }, + hosts: [], } - systemInfo = await res.json() - } catch (e) { - console.error('error fetching system info', e) - } - return systemInfo - }, 250, true) + try { + const res = await fetch("/get/system_info") + if (!res.ok) { + console.error("Invalid response fetching devices", res.statusText) + return systemInfo + } + systemInfo = await res.json() + } catch (e) { + console.error("error fetching system info", e) + } + return systemInfo + }, + 250, + true + ) async function getDevices() { let systemInfo = getSystemInfo() return systemInfo.devices @@ -1067,26 +1123,26 @@ async function getModels() { let models = { - 'stable-diffusion': [], - 'vae': [], + "stable-diffusion": [], + vae: [], } try { - const res = await fetch('/get/models') + const res = await fetch("/get/models") if (!res.ok) { - console.error('Invalid response fetching models', res.statusText) + console.error("Invalid response fetching models", res.statusText) return models } models = await res.json() - console.log('get models response', models) + console.log("get models response", models) } catch (e) { - console.log('get models error', e) + console.log("get models error", e) } return models } function getServerCapacity() { let activeDevicesCount = Object.keys(serverState?.devices?.active || {}).length - if (typeof window === "object" && window.document.visibilityState === 'hidden') { + if (typeof window === "object" && window.document.visibilityState === "hidden") { activeDevicesCount = 1 + activeDevicesCount } return activeDevicesCount @@ -1094,11 +1150,11 @@ let idleEventPromise = undefined function continueTasks() { - if (typeof navigator?.scheduling?.isInputPending === 'function') { + if (typeof navigator?.scheduling?.isInputPending === "function") { const inputPendingOptions = { // Report mouse/pointer move events when queue is empty. // Delay idle after mouse moves stops. - includeContinuous: Boolean(task_queue.size <= 0 && concurrent_generators.size <= 0) + includeContinuous: Boolean(task_queue.size <= 0 && concurrent_generators.size <= 0), } if (navigator.scheduling.isInputPending(inputPendingOptions)) { // Browser/User still active. @@ -1108,7 +1164,9 @@ const serverCapacity = getServerCapacity() if (task_queue.size <= 0 && concurrent_generators.size <= 0) { if (!idleEventPromise?.isPending) { - idleEventPromise = makeQuerablePromise(eventSource.fireEvent(EVENT_IDLE, {capacity: serverCapacity, idle: true})) + idleEventPromise = makeQuerablePromise( + eventSource.fireEvent(EVENT_IDLE, { capacity: serverCapacity, idle: true }) + ) } // Calling idle could result in task being added to queue. // if (task_queue.size <= 0 && concurrent_generators.size <= 0) { @@ -1117,7 +1175,9 @@ } if (task_queue.size < serverCapacity) { if (!idleEventPromise?.isPending) { - idleEventPromise = makeQuerablePromise(eventSource.fireEvent(EVENT_IDLE, {capacity: serverCapacity - task_queue.size})) + idleEventPromise = makeQuerablePromise( + eventSource.fireEvent(EVENT_IDLE, { capacity: serverCapacity - task_queue.size }) + ) } } const completedTasks = [] @@ -1128,25 +1188,25 @@ let value = promise.resolvedValue?.value || promise.resolvedValue if (promise.isRejected) { console.error(promise.rejectReason) - const event = {generator, reason: promise.rejectReason} + const event = { generator, reason: promise.rejectReason } eventSource.fireEvent(EVENT_UNHANDLED_REJECTION, event) - if ('continueWith' in event) { + if ("continueWith" in event) { value = Promise.resolve(event.continueWith) } else { concurrent_generators.delete(generator) - completedTasks.push({generator, promise}) + completedTasks.push({ generator, promise }) continue } } if (value instanceof Promise) { - promise = makeQuerablePromise(value.then((val) => ({done: promise.resolvedValue?.done, value: val}))) + promise = makeQuerablePromise(value.then((val) => ({ done: promise.resolvedValue?.done, value: val }))) concurrent_generators.set(generator, promise) continue } weak_results.set(generator, value) if (promise.resolvedValue?.done) { concurrent_generators.delete(generator) - completedTasks.push({generator, promise}) + completedTasks.push({ generator, promise }) continue } @@ -1161,12 +1221,16 @@ for (let [task, generator] of task_queue.entries()) { const cTsk = completedTasks.find((item) => item.generator === generator) if (cTsk?.promise?.rejectReason || task.hasFailed) { - eventSource.fireEvent(EVENT_TASK_ERROR, {task, generator, reason: cTsk?.promise?.rejectReason || task.exception }) + eventSource.fireEvent(EVENT_TASK_ERROR, { + task, + generator, + reason: cTsk?.promise?.rejectReason || task.exception, + }) task_queue.delete(task) continue } if (task.isCompleted || task.isStopped || cTsk) { - const eventEndArgs = {task, generator} + const eventEndArgs = { task, generator } if (task.isStopped) { eventEndArgs.stopped = true } @@ -1178,13 +1242,13 @@ break } if (!generator) { - if (typeof task.start === 'function') { + if (typeof task.start === "function") { generator = task.start() } } else if (concurrent_generators.has(generator)) { continue } - const event = {task, generator}; + const event = { task, generator } const beforeStart = eventSource.fireEvent(EVENT_TASK_START, event) // optional beforeStart promise to wait on before starting task. const promise = makeQuerablePromise(beforeStart.then(() => Promise.resolve(event.beforeStart))) concurrent_generators.set(event.generator, promise) @@ -1206,16 +1270,16 @@ taskPromise = makeQuerablePromise(taskPromise.resolvedValue) continue } - if (typeof navigator?.scheduling?.isInputPending === 'function' && navigator.scheduling.isInputPending()) { + if (typeof navigator?.scheduling?.isInputPending === "function" && navigator.scheduling.isInputPending()) { return } const continuePromise = continueTasks().catch(async function(err) { console.error(err) - await eventSource.fireEvent(EVENT_UNHANDLED_REJECTION, {reason: err}) + await eventSource.fireEvent(EVENT_UNHANDLED_REJECTION, { reason: err }) await asyncDelay(RETRY_DELAY_ON_ERROR) }) taskPromise = makeQuerablePromise(continuePromise) - } while(taskPromise?.isResolved) + } while (taskPromise?.isResolved) } const SD = { @@ -1227,8 +1291,8 @@ FilterTask, Events: EVENTS_TYPES, - init: async function(options={}) { - if ('events' in options) { + init: async function(options = {}) { + if ("events" in options) { for (const key in options.events) { eventSource.addEventListener(key, options.events[key]) } @@ -1257,7 +1321,7 @@ render: (...args) => RenderTask.run(...args), filter: (...args) => FilterTask.run(...args), waitUntil, - }; + } Object.defineProperties(SD, { serverState: { @@ -1276,7 +1340,7 @@ configurable: false, get: () => sessionId, set: (val) => { - if (typeof val === 'undefined') { + if (typeof val === "undefined") { throw new Error("Can't set sessionId to undefined.") } sessionId = val @@ -1296,18 +1360,19 @@ configurable: false, get: () => SD, }, - sessionId: { //TODO Remove in the future in favor of SD.sessionId + sessionId: { + //TODO Remove in the future in favor of SD.sessionId configurable: false, get: () => { - console.warn('Deprecated window.sessionId has been replaced with SD.sessionId.') + console.warn("Deprecated window.sessionId has been replaced with SD.sessionId.") console.trace() return SD.sessionId }, set: (val) => { - console.warn('Deprecated window.sessionId has been replaced with SD.sessionId.') + console.warn("Deprecated window.sessionId has been replaced with SD.sessionId.") console.trace() SD.sessionId = val - } - } + }, + }, }) })() diff --git a/ui/media/js/image-editor.js b/ui/media/js/image-editor.js index 8c246eab..e7de9f2b 100644 --- a/ui/media/js/image-editor.js +++ b/ui/media/js/image-editor.js @@ -3,758 +3,796 @@ var editorControlsLeft = document.getElementById("image-editor-controls-left") const IMAGE_EDITOR_MAX_SIZE = 800 const IMAGE_EDITOR_BUTTONS = [ - { - name: "Cancel", - icon: "fa-regular fa-circle-xmark", - handler: editor => { - editor.hide() - } - }, - { - name: "Save", - icon: "fa-solid fa-floppy-disk", - handler: editor => { - editor.saveImage() - } - } + { + name: "Cancel", + icon: "fa-regular fa-circle-xmark", + handler: (editor) => { + editor.hide() + }, + }, + { + name: "Save", + icon: "fa-solid fa-floppy-disk", + handler: (editor) => { + editor.saveImage() + }, + }, ] const defaultToolBegin = (editor, ctx, x, y, is_overlay = false) => { - ctx.beginPath() - ctx.moveTo(x, y) + ctx.beginPath() + ctx.moveTo(x, y) } const defaultToolMove = (editor, ctx, x, y, is_overlay = false) => { - ctx.lineTo(x, y) - if (is_overlay) { - ctx.clearRect(0, 0, editor.width, editor.height) - ctx.stroke() - } + ctx.lineTo(x, y) + if (is_overlay) { + ctx.clearRect(0, 0, editor.width, editor.height) + ctx.stroke() + } } const defaultToolEnd = (editor, ctx, x, y, is_overlay = false) => { - ctx.stroke() - if (is_overlay) { - ctx.clearRect(0, 0, editor.width, editor.height) - } + ctx.stroke() + if (is_overlay) { + ctx.clearRect(0, 0, editor.width, editor.height) + } } const toolDoNothing = (editor, ctx, x, y, is_overlay = false) => {} const IMAGE_EDITOR_TOOLS = [ - { - id: "draw", - name: "Draw", - icon: "fa-solid fa-pencil", - cursor: "url(/media/images/fa-pencil.svg) 0 24, pointer", - begin: defaultToolBegin, - move: defaultToolMove, - end: defaultToolEnd - }, - { - id: "erase", - name: "Erase", - icon: "fa-solid fa-eraser", - cursor: "url(/media/images/fa-eraser.svg) 0 14, pointer", - begin: defaultToolBegin, - move: (editor, ctx, x, y, is_overlay = false) => { - ctx.lineTo(x, y) - if (is_overlay) { - ctx.clearRect(0, 0, editor.width, editor.height) - ctx.globalCompositeOperation = "source-over" - ctx.globalAlpha = 1 - ctx.filter = "none" - ctx.drawImage(editor.canvas_current, 0, 0) - editor.setBrush(editor.layers.overlay) - ctx.stroke() - editor.canvas_current.style.opacity = 0 - } - }, - end: (editor, ctx, x, y, is_overlay = false) => { - ctx.stroke() - if (is_overlay) { - ctx.clearRect(0, 0, editor.width, editor.height) - editor.canvas_current.style.opacity = "" - } - }, - setBrush: (editor, layer) => { - layer.ctx.globalCompositeOperation = "destination-out" - } - }, - { - id: "fill", - name: "Fill", - icon: "fa-solid fa-fill", - cursor: "url(/media/images/fa-fill.svg) 20 6, pointer", - begin: (editor, ctx, x, y, is_overlay = false) => { - if (!is_overlay) { - var color = hexToRgb(ctx.fillStyle) - color.a = parseInt(ctx.globalAlpha * 255) // layer.ctx.globalAlpha - flood_fill(editor, ctx, parseInt(x), parseInt(y), color) - } - }, - move: toolDoNothing, - end: toolDoNothing - }, - { - id: "colorpicker", - name: "Picker", - icon: "fa-solid fa-eye-dropper", - cursor: "url(/media/images/fa-eye-dropper.svg) 0 24, pointer", - begin: (editor, ctx, x, y, is_overlay = false) => { - if (!is_overlay) { - var img_rgb = editor.layers.background.ctx.getImageData(x, y, 1, 1).data - var drawn_rgb = editor.ctx_current.getImageData(x, y, 1, 1).data - var drawn_opacity = drawn_rgb[3] / 255 - editor.custom_color_input.value = rgbToHex({ - r: (drawn_rgb[0] * drawn_opacity) + (img_rgb[0] * (1 - drawn_opacity)), - g: (drawn_rgb[1] * drawn_opacity) + (img_rgb[1] * (1 - drawn_opacity)), - b: (drawn_rgb[2] * drawn_opacity) + (img_rgb[2] * (1 - drawn_opacity)), - }) - editor.custom_color_input.dispatchEvent(new Event("change")) - } - }, - move: toolDoNothing, - end: toolDoNothing - } + { + id: "draw", + name: "Draw", + icon: "fa-solid fa-pencil", + cursor: "url(/media/images/fa-pencil.svg) 0 24, pointer", + begin: defaultToolBegin, + move: defaultToolMove, + end: defaultToolEnd, + }, + { + id: "erase", + name: "Erase", + icon: "fa-solid fa-eraser", + cursor: "url(/media/images/fa-eraser.svg) 0 14, pointer", + begin: defaultToolBegin, + move: (editor, ctx, x, y, is_overlay = false) => { + ctx.lineTo(x, y) + if (is_overlay) { + ctx.clearRect(0, 0, editor.width, editor.height) + ctx.globalCompositeOperation = "source-over" + ctx.globalAlpha = 1 + ctx.filter = "none" + ctx.drawImage(editor.canvas_current, 0, 0) + editor.setBrush(editor.layers.overlay) + ctx.stroke() + editor.canvas_current.style.opacity = 0 + } + }, + end: (editor, ctx, x, y, is_overlay = false) => { + ctx.stroke() + if (is_overlay) { + ctx.clearRect(0, 0, editor.width, editor.height) + editor.canvas_current.style.opacity = "" + } + }, + setBrush: (editor, layer) => { + layer.ctx.globalCompositeOperation = "destination-out" + }, + }, + { + id: "fill", + name: "Fill", + icon: "fa-solid fa-fill", + cursor: "url(/media/images/fa-fill.svg) 20 6, pointer", + begin: (editor, ctx, x, y, is_overlay = false) => { + if (!is_overlay) { + var color = hexToRgb(ctx.fillStyle) + color.a = parseInt(ctx.globalAlpha * 255) // layer.ctx.globalAlpha + flood_fill(editor, ctx, parseInt(x), parseInt(y), color) + } + }, + move: toolDoNothing, + end: toolDoNothing, + }, + { + id: "colorpicker", + name: "Picker", + icon: "fa-solid fa-eye-dropper", + cursor: "url(/media/images/fa-eye-dropper.svg) 0 24, pointer", + begin: (editor, ctx, x, y, is_overlay = false) => { + if (!is_overlay) { + var img_rgb = editor.layers.background.ctx.getImageData(x, y, 1, 1).data + var drawn_rgb = editor.ctx_current.getImageData(x, y, 1, 1).data + var drawn_opacity = drawn_rgb[3] / 255 + editor.custom_color_input.value = rgbToHex({ + r: drawn_rgb[0] * drawn_opacity + img_rgb[0] * (1 - drawn_opacity), + g: drawn_rgb[1] * drawn_opacity + img_rgb[1] * (1 - drawn_opacity), + b: drawn_rgb[2] * drawn_opacity + img_rgb[2] * (1 - drawn_opacity), + }) + editor.custom_color_input.dispatchEvent(new Event("change")) + } + }, + move: toolDoNothing, + end: toolDoNothing, + }, ] const IMAGE_EDITOR_ACTIONS = [ - { - id: "load_mask", - name: "Load mask from file", - className: "load_mask", - icon: "fa-regular fa-folder-open", - handler: (editor) => { - let el = document.createElement('input') - el.setAttribute("type", "file") - el.addEventListener("change", function() { - if (this.files.length === 0) { - return - } + { + id: "load_mask", + name: "Load mask from file", + className: "load_mask", + icon: "fa-regular fa-folder-open", + handler: (editor) => { + let el = document.createElement("input") + el.setAttribute("type", "file") + el.addEventListener("change", function() { + if (this.files.length === 0) { + return + } - let reader = new FileReader() - let file = this.files[0] + let reader = new FileReader() + let file = this.files[0] - reader.addEventListener('load', function(event) { - let maskData = reader.result + reader.addEventListener("load", function(event) { + let maskData = reader.result - editor.layers.drawing.ctx.clearRect(0, 0, editor.width, editor.height) - var image = new Image() - image.onload = () => { - editor.layers.drawing.ctx.drawImage(image, 0, 0, editor.width, editor.height) - } - image.src = maskData - }) + editor.layers.drawing.ctx.clearRect(0, 0, editor.width, editor.height) + var image = new Image() + image.onload = () => { + editor.layers.drawing.ctx.drawImage(image, 0, 0, editor.width, editor.height) + } + image.src = maskData + }) - if (file) { - reader.readAsDataURL(file) - } - }) + if (file) { + reader.readAsDataURL(file) + } + }) - el.click() - }, - trackHistory: true - }, - { - id: "fill_all", - name: "Fill all", - icon: "fa-solid fa-paint-roller", - handler: (editor) => { - editor.ctx_current.globalCompositeOperation = "source-over" - editor.ctx_current.rect(0, 0, editor.width, editor.height) - editor.ctx_current.fill() - editor.setBrush() - }, - trackHistory: true - }, - { - id: "clear", - name: "Clear", - icon: "fa-solid fa-xmark", - handler: (editor) => { - editor.ctx_current.clearRect(0, 0, editor.width, editor.height) - imageEditor.setImage(null, editor.width, editor.height) // properly reset the drawing canvas - }, - trackHistory: true - }, - { - id: "undo", - name: "Undo", - icon: "fa-solid fa-rotate-left", - handler: (editor) => { - editor.history.undo() - }, - trackHistory: false - }, - { - id: "redo", - name: "Redo", - icon: "fa-solid fa-rotate-right", - handler: (editor) => { - editor.history.redo() - }, - trackHistory: false - } + el.click() + }, + trackHistory: true, + }, + { + id: "fill_all", + name: "Fill all", + icon: "fa-solid fa-paint-roller", + handler: (editor) => { + editor.ctx_current.globalCompositeOperation = "source-over" + editor.ctx_current.rect(0, 0, editor.width, editor.height) + editor.ctx_current.fill() + editor.setBrush() + }, + trackHistory: true, + }, + { + id: "clear", + name: "Clear", + icon: "fa-solid fa-xmark", + handler: (editor) => { + editor.ctx_current.clearRect(0, 0, editor.width, editor.height) + imageEditor.setImage(null, editor.width, editor.height) // properly reset the drawing canvas + }, + trackHistory: true, + }, + { + id: "undo", + name: "Undo", + icon: "fa-solid fa-rotate-left", + handler: (editor) => { + editor.history.undo() + }, + trackHistory: false, + }, + { + id: "redo", + name: "Redo", + icon: "fa-solid fa-rotate-right", + handler: (editor) => { + editor.history.redo() + }, + trackHistory: false, + }, ] var IMAGE_EDITOR_SECTIONS = [ - { - name: "tool", - title: "Tool", - default: "draw", - options: Array.from(IMAGE_EDITOR_TOOLS.map(t => t.id)), - initElement: (element, option) => { - var tool_info = IMAGE_EDITOR_TOOLS.find(t => t.id == option) - element.className = "image-editor-button button" - var sub_element = document.createElement("div") - var icon = document.createElement("i") - tool_info.icon.split(" ").forEach(c => icon.classList.add(c)) - sub_element.appendChild(icon) - sub_element.append(tool_info.name) - element.appendChild(sub_element) - } - }, - { - name: "color", - title: "Color", - default: "#f1c232", - options: [ - "custom", - "#ea9999", "#e06666", "#cc0000", "#990000", "#660000", - "#f9cb9c", "#f6b26b", "#e69138", "#b45f06", "#783f04", - "#ffe599", "#ffd966", "#f1c232", "#bf9000", "#7f6000", - "#b6d7a8", "#93c47d", "#6aa84f", "#38761d", "#274e13", - "#a4c2f4", "#6d9eeb", "#3c78d8", "#1155cc", "#1c4587", - "#b4a7d6", "#8e7cc3", "#674ea7", "#351c75", "#20124d", - "#d5a6bd", "#c27ba0", "#a64d79", "#741b47", "#4c1130", - "#ffffff", "#c0c0c0", "#838383", "#525252", "#000000", - ], - initElement: (element, option) => { - if (option == "custom") { - var input = document.createElement("input") - input.type = "color" - element.appendChild(input) - var span = document.createElement("span") - span.textContent = "Custom" - span.onclick = function(e) { - input.click() - } - element.appendChild(span) - } - else { - element.style.background = option - } - }, - getCustom: editor => { - var input = editor.popup.querySelector(".image_editor_color input") - return input.value - } - }, - { - name: "brush_size", - title: "Brush Size", - default: 48, - options: [ 6, 12, 16, 24, 30, 40, 48, 64 ], - initElement: (element, option) => { - element.parentElement.style.flex = option - element.style.width = option + "px" - element.style.height = option + "px" - element.style['margin-right'] = '2px' - element.style["border-radius"] = (option / 2).toFixed() + "px" - } - }, - { - name: "opacity", - title: "Opacity", - default: 0, - options: [ 0, 0.2, 0.4, 0.6, 0.8 ], - initElement: (element, option) => { - element.style.background = `repeating-conic-gradient(rgba(0, 0, 0, ${option}) 0% 25%, rgba(255, 255, 255, ${option}) 0% 50%) 50% / 10px 10px` - } - }, - { - name: "sharpness", - title: "Sharpness", - default: 0, - options: [ 0, 0.05, 0.1, 0.2, 0.3 ], - initElement: (element, option) => { - var size = 32 - var blur_amount = parseInt(option * size) - var sub_element = document.createElement("div") - sub_element.style.background = `var(--background-color3)` - sub_element.style.filter = `blur(${blur_amount}px)` - sub_element.style.width = `${size - 2}px` - sub_element.style.height = `${size - 2}px` - sub_element.style['border-radius'] = `${size}px` - element.style.background = "none" - element.appendChild(sub_element) - } - } + { + name: "tool", + title: "Tool", + default: "draw", + options: Array.from(IMAGE_EDITOR_TOOLS.map((t) => t.id)), + initElement: (element, option) => { + var tool_info = IMAGE_EDITOR_TOOLS.find((t) => t.id == option) + element.className = "image-editor-button button" + var sub_element = document.createElement("div") + var icon = document.createElement("i") + tool_info.icon.split(" ").forEach((c) => icon.classList.add(c)) + sub_element.appendChild(icon) + sub_element.append(tool_info.name) + element.appendChild(sub_element) + }, + }, + { + name: "color", + title: "Color", + default: "#f1c232", + options: [ + "custom", + "#ea9999", + "#e06666", + "#cc0000", + "#990000", + "#660000", + "#f9cb9c", + "#f6b26b", + "#e69138", + "#b45f06", + "#783f04", + "#ffe599", + "#ffd966", + "#f1c232", + "#bf9000", + "#7f6000", + "#b6d7a8", + "#93c47d", + "#6aa84f", + "#38761d", + "#274e13", + "#a4c2f4", + "#6d9eeb", + "#3c78d8", + "#1155cc", + "#1c4587", + "#b4a7d6", + "#8e7cc3", + "#674ea7", + "#351c75", + "#20124d", + "#d5a6bd", + "#c27ba0", + "#a64d79", + "#741b47", + "#4c1130", + "#ffffff", + "#c0c0c0", + "#838383", + "#525252", + "#000000", + ], + initElement: (element, option) => { + if (option == "custom") { + var input = document.createElement("input") + input.type = "color" + element.appendChild(input) + var span = document.createElement("span") + span.textContent = "Custom" + span.onclick = function(e) { + input.click() + } + element.appendChild(span) + } else { + element.style.background = option + } + }, + getCustom: (editor) => { + var input = editor.popup.querySelector(".image_editor_color input") + return input.value + }, + }, + { + name: "brush_size", + title: "Brush Size", + default: 48, + options: [6, 12, 16, 24, 30, 40, 48, 64], + initElement: (element, option) => { + element.parentElement.style.flex = option + element.style.width = option + "px" + element.style.height = option + "px" + element.style["margin-right"] = "2px" + element.style["border-radius"] = (option / 2).toFixed() + "px" + }, + }, + { + name: "opacity", + title: "Opacity", + default: 0, + options: [0, 0.2, 0.4, 0.6, 0.8], + initElement: (element, option) => { + element.style.background = `repeating-conic-gradient(rgba(0, 0, 0, ${option}) 0% 25%, rgba(255, 255, 255, ${option}) 0% 50%) 50% / 10px 10px` + }, + }, + { + name: "sharpness", + title: "Sharpness", + default: 0, + options: [0, 0.05, 0.1, 0.2, 0.3], + initElement: (element, option) => { + var size = 32 + var blur_amount = parseInt(option * size) + var sub_element = document.createElement("div") + sub_element.style.background = `var(--background-color3)` + sub_element.style.filter = `blur(${blur_amount}px)` + sub_element.style.width = `${size - 2}px` + sub_element.style.height = `${size - 2}px` + sub_element.style["border-radius"] = `${size}px` + element.style.background = "none" + element.appendChild(sub_element) + }, + }, ] class EditorHistory { - constructor(editor) { - this.editor = editor - this.events = [] // stack of all events (actions/edits) - this.current_edit = null - this.rewind_index = 0 // how many events back into the history we've rewound to. (current state is just after event at index 'length - this.rewind_index - 1') - } - push(event) { - // probably add something here eventually to save state every x events - if (this.rewind_index != 0) { - this.events = this.events.slice(0, 0 - this.rewind_index) - this.rewind_index = 0 - } - var snapshot_frequency = 20 // (every x edits, take a snapshot of the current drawing state, for faster rewinding) - if (this.events.length > 0 && this.events.length % snapshot_frequency == 0) { - event.snapshot = this.editor.layers.drawing.ctx.getImageData(0, 0, this.editor.width, this.editor.height) - } - this.events.push(event) - } - pushAction(action) { - this.push({ - type: "action", - id: action - }); - } - editBegin(x, y) { - this.current_edit = { - type: "edit", - id: this.editor.getOptionValue("tool"), - options: Object.assign({}, this.editor.options), - points: [ { x: x, y: y } ] - } - } - editMove(x, y) { - if (this.current_edit) { - this.current_edit.points.push({ x: x, y: y }) - } - } - editEnd(x, y) { - if (this.current_edit) { - this.push(this.current_edit) - this.current_edit = null - } - } - clear() { - this.events = [] - } - undo() { - this.rewindTo(this.rewind_index + 1) - } - redo() { - this.rewindTo(this.rewind_index - 1) - } - rewindTo(new_rewind_index) { - if (new_rewind_index < 0 || new_rewind_index > this.events.length) { - return; // do nothing if target index is out of bounds - } + constructor(editor) { + this.editor = editor + this.events = [] // stack of all events (actions/edits) + this.current_edit = null + this.rewind_index = 0 // how many events back into the history we've rewound to. (current state is just after event at index 'length - this.rewind_index - 1') + } + push(event) { + // probably add something here eventually to save state every x events + if (this.rewind_index != 0) { + this.events = this.events.slice(0, 0 - this.rewind_index) + this.rewind_index = 0 + } + var snapshot_frequency = 20 // (every x edits, take a snapshot of the current drawing state, for faster rewinding) + if (this.events.length > 0 && this.events.length % snapshot_frequency == 0) { + event.snapshot = this.editor.layers.drawing.ctx.getImageData(0, 0, this.editor.width, this.editor.height) + } + this.events.push(event) + } + pushAction(action) { + this.push({ + type: "action", + id: action, + }) + } + editBegin(x, y) { + this.current_edit = { + type: "edit", + id: this.editor.getOptionValue("tool"), + options: Object.assign({}, this.editor.options), + points: [{ x: x, y: y }], + } + } + editMove(x, y) { + if (this.current_edit) { + this.current_edit.points.push({ x: x, y: y }) + } + } + editEnd(x, y) { + if (this.current_edit) { + this.push(this.current_edit) + this.current_edit = null + } + } + clear() { + this.events = [] + } + undo() { + this.rewindTo(this.rewind_index + 1) + } + redo() { + this.rewindTo(this.rewind_index - 1) + } + rewindTo(new_rewind_index) { + if (new_rewind_index < 0 || new_rewind_index > this.events.length) { + return // do nothing if target index is out of bounds + } - var ctx = this.editor.layers.drawing.ctx - ctx.clearRect(0, 0, this.editor.width, this.editor.height) + var ctx = this.editor.layers.drawing.ctx + ctx.clearRect(0, 0, this.editor.width, this.editor.height) - var target_index = this.events.length - 1 - new_rewind_index - var snapshot_index = target_index - while (snapshot_index > -1) { - if (this.events[snapshot_index].snapshot) { - break - } - snapshot_index-- - } + var target_index = this.events.length - 1 - new_rewind_index + var snapshot_index = target_index + while (snapshot_index > -1) { + if (this.events[snapshot_index].snapshot) { + break + } + snapshot_index-- + } - if (snapshot_index != -1) { - ctx.putImageData(this.events[snapshot_index].snapshot, 0, 0); - } + if (snapshot_index != -1) { + ctx.putImageData(this.events[snapshot_index].snapshot, 0, 0) + } - for (var i = (snapshot_index + 1); i <= target_index; i++) { - var event = this.events[i] - if (event.type == "action") { - var action = IMAGE_EDITOR_ACTIONS.find(a => a.id == event.id) - action.handler(this.editor) - } - else if (event.type == "edit") { - var tool = IMAGE_EDITOR_TOOLS.find(t => t.id == event.id) - this.editor.setBrush(this.editor.layers.drawing, event.options) + for (var i = snapshot_index + 1; i <= target_index; i++) { + var event = this.events[i] + if (event.type == "action") { + var action = IMAGE_EDITOR_ACTIONS.find((a) => a.id == event.id) + action.handler(this.editor) + } else if (event.type == "edit") { + var tool = IMAGE_EDITOR_TOOLS.find((t) => t.id == event.id) + this.editor.setBrush(this.editor.layers.drawing, event.options) - var first_point = event.points[0] - tool.begin(this.editor, ctx, first_point.x, first_point.y) - for (var point_i = 1; point_i < event.points.length; point_i++) { - tool.move(this.editor, ctx, event.points[point_i].x, event.points[point_i].y) - } - var last_point = event.points[event.points.length - 1] - tool.end(this.editor, ctx, last_point.x, last_point.y) - } - } + var first_point = event.points[0] + tool.begin(this.editor, ctx, first_point.x, first_point.y) + for (var point_i = 1; point_i < event.points.length; point_i++) { + tool.move(this.editor, ctx, event.points[point_i].x, event.points[point_i].y) + } + var last_point = event.points[event.points.length - 1] + tool.end(this.editor, ctx, last_point.x, last_point.y) + } + } - // re-set brush to current settings - this.editor.setBrush(this.editor.layers.drawing) + // re-set brush to current settings + this.editor.setBrush(this.editor.layers.drawing) - this.rewind_index = new_rewind_index - } + this.rewind_index = new_rewind_index + } } class ImageEditor { - constructor(popup, inpainter = false) { - this.inpainter = inpainter - this.popup = popup - this.history = new EditorHistory(this) - if (inpainter) { - this.popup.classList.add("inpainter") - } - this.drawing = false - this.temp_previous_tool = null // used for the ctrl-colorpicker functionality - this.container = popup.querySelector(".editor-controls-center > div") - this.layers = {} - var layer_names = [ - "background", - "drawing", - "overlay" - ] - layer_names.forEach(name => { - let canvas = document.createElement("canvas") - canvas.className = `editor-canvas-${name}` - this.container.appendChild(canvas) - this.layers[name] = { - name: name, - canvas: canvas, - ctx: canvas.getContext("2d") - } - }) + constructor(popup, inpainter = false) { + this.inpainter = inpainter + this.popup = popup + this.history = new EditorHistory(this) + if (inpainter) { + this.popup.classList.add("inpainter") + } + this.drawing = false + this.temp_previous_tool = null // used for the ctrl-colorpicker functionality + this.container = popup.querySelector(".editor-controls-center > div") + this.layers = {} + var layer_names = ["background", "drawing", "overlay"] + layer_names.forEach((name) => { + let canvas = document.createElement("canvas") + canvas.className = `editor-canvas-${name}` + this.container.appendChild(canvas) + this.layers[name] = { + name: name, + canvas: canvas, + ctx: canvas.getContext("2d"), + } + }) - // add mouse handlers - this.container.addEventListener("mousedown", this.mouseHandler.bind(this)) - this.container.addEventListener("mouseup", this.mouseHandler.bind(this)) - this.container.addEventListener("mousemove", this.mouseHandler.bind(this)) - this.container.addEventListener("mouseout", this.mouseHandler.bind(this)) - this.container.addEventListener("mouseenter", this.mouseHandler.bind(this)) + // add mouse handlers + this.container.addEventListener("mousedown", this.mouseHandler.bind(this)) + this.container.addEventListener("mouseup", this.mouseHandler.bind(this)) + this.container.addEventListener("mousemove", this.mouseHandler.bind(this)) + this.container.addEventListener("mouseout", this.mouseHandler.bind(this)) + this.container.addEventListener("mouseenter", this.mouseHandler.bind(this)) - this.container.addEventListener("touchstart", this.mouseHandler.bind(this)) - this.container.addEventListener("touchmove", this.mouseHandler.bind(this)) - this.container.addEventListener("touchcancel", this.mouseHandler.bind(this)) - this.container.addEventListener("touchend", this.mouseHandler.bind(this)) + this.container.addEventListener("touchstart", this.mouseHandler.bind(this)) + this.container.addEventListener("touchmove", this.mouseHandler.bind(this)) + this.container.addEventListener("touchcancel", this.mouseHandler.bind(this)) + this.container.addEventListener("touchend", this.mouseHandler.bind(this)) - // initialize editor controls - this.options = {} - this.optionElements = {} - IMAGE_EDITOR_SECTIONS.forEach(section => { - section.id = `image_editor_${section.name}` - var sectionElement = document.createElement("div") - sectionElement.className = section.id - - var title = document.createElement("h4") - title.innerText = section.title - sectionElement.appendChild(title) - - var optionsContainer = document.createElement("div") - optionsContainer.classList.add("editor-options-container") - - this.optionElements[section.name] = [] - section.options.forEach((option, index) => { - var optionHolder = document.createElement("div") - var optionElement = document.createElement("div") - optionHolder.appendChild(optionElement) - section.initElement(optionElement, option) - optionElement.addEventListener("click", target => this.selectOption(section.name, index)) - optionsContainer.appendChild(optionHolder) - this.optionElements[section.name].push(optionElement) - }) - this.selectOption(section.name, section.options.indexOf(section.default)) - - sectionElement.appendChild(optionsContainer) - - this.popup.querySelector(".editor-controls-left").appendChild(sectionElement) - }) + // initialize editor controls + this.options = {} + this.optionElements = {} + IMAGE_EDITOR_SECTIONS.forEach((section) => { + section.id = `image_editor_${section.name}` + var sectionElement = document.createElement("div") + sectionElement.className = section.id - this.custom_color_input = this.popup.querySelector(`input[type="color"]`) - this.custom_color_input.addEventListener("change", () => { - this.custom_color_input.parentElement.style.background = this.custom_color_input.value - this.selectOption("color", 0) - }) + var title = document.createElement("h4") + title.innerText = section.title + sectionElement.appendChild(title) - if (this.inpainter) { - this.selectOption("color", IMAGE_EDITOR_SECTIONS.find(s => s.name == "color").options.indexOf("#ffffff")) - this.selectOption("opacity", IMAGE_EDITOR_SECTIONS.find(s => s.name == "opacity").options.indexOf(0.4)) - } + var optionsContainer = document.createElement("div") + optionsContainer.classList.add("editor-options-container") - // initialize the right-side controls - var buttonContainer = document.createElement("div") - IMAGE_EDITOR_BUTTONS.forEach(button => { - var element = document.createElement("div") - var icon = document.createElement("i") - element.className = "image-editor-button button" - icon.className = button.icon - element.appendChild(icon) - element.append(button.name) - buttonContainer.appendChild(element) - element.addEventListener("click", event => button.handler(this)) - }) - var actionsContainer = document.createElement("div") - var actionsTitle = document.createElement("h4") - actionsTitle.textContent = "Actions" - actionsContainer.appendChild(actionsTitle); - IMAGE_EDITOR_ACTIONS.forEach(action => { - var element = document.createElement("div") - var icon = document.createElement("i") - element.className = "image-editor-button button" - if (action.className) { - element.className += " " + action.className - } - icon.className = action.icon - element.appendChild(icon) - element.append(action.name) - actionsContainer.appendChild(element) - element.addEventListener("click", event => this.runAction(action.id)) - }) - this.popup.querySelector(".editor-controls-right").appendChild(actionsContainer) - this.popup.querySelector(".editor-controls-right").appendChild(buttonContainer) + this.optionElements[section.name] = [] + section.options.forEach((option, index) => { + var optionHolder = document.createElement("div") + var optionElement = document.createElement("div") + optionHolder.appendChild(optionElement) + section.initElement(optionElement, option) + optionElement.addEventListener("click", (target) => this.selectOption(section.name, index)) + optionsContainer.appendChild(optionHolder) + this.optionElements[section.name].push(optionElement) + }) + this.selectOption(section.name, section.options.indexOf(section.default)) - this.keyHandlerBound = this.keyHandler.bind(this) + sectionElement.appendChild(optionsContainer) - this.setSize(512, 512) - } - show() { - this.popup.classList.add("active") - document.addEventListener("keydown", this.keyHandlerBound) - document.addEventListener("keyup", this.keyHandlerBound) - } - hide() { - this.popup.classList.remove("active") - document.removeEventListener("keydown", this.keyHandlerBound) - document.removeEventListener("keyup", this.keyHandlerBound) - } - setSize(width, height) { - if (width == this.width && height == this.height) { - return - } + this.popup.querySelector(".editor-controls-left").appendChild(sectionElement) + }) - if (width > height) { - var max_size = Math.min(parseInt(window.innerWidth * 0.9), width, 768) - var multiplier = max_size / width - width = (multiplier * width).toFixed() - height = (multiplier * height).toFixed() - } - else { - var max_size = Math.min(parseInt(window.innerHeight * 0.9), height, 768) - var multiplier = max_size / height - width = (multiplier * width).toFixed() - height = (multiplier * height).toFixed() - } - this.width = parseInt(width) - this.height = parseInt(height) - - this.container.style.width = width + "px" - this.container.style.height = height + "px" - - Object.values(this.layers).forEach(layer => { - layer.canvas.width = width - layer.canvas.height = height - }) + this.custom_color_input = this.popup.querySelector(`input[type="color"]`) + this.custom_color_input.addEventListener("change", () => { + this.custom_color_input.parentElement.style.background = this.custom_color_input.value + this.selectOption("color", 0) + }) - if (this.inpainter) { - this.saveImage() // We've reset the size of the image so inpainting is different - } - this.setBrush() - this.history.clear() - } - get tool() { - var tool_id = this.getOptionValue("tool") - return IMAGE_EDITOR_TOOLS.find(t => t.id == tool_id); - } - loadTool() { - this.drawing = false - this.container.style.cursor = this.tool.cursor; - } - setImage(url, width, height) { - this.setSize(width, height) - this.layers.background.ctx.clearRect(0, 0, this.width, this.height) - if (!(url && this.inpainter)) { - this.layers.drawing.ctx.clearRect(0, 0, this.width, this.height) - } - if (url) { - var image = new Image() - image.onload = () => { - this.layers.background.ctx.drawImage(image, 0, 0, this.width, this.height) - } - image.src = url - } - else { - this.layers.background.ctx.fillStyle = "#ffffff" - this.layers.background.ctx.beginPath() - this.layers.background.ctx.rect(0, 0, this.width, this.height) - this.layers.background.ctx.fill() - } - this.history.clear() - } - saveImage() { - if (!this.inpainter) { - // This is not an inpainter, so save the image as the new img2img input - this.layers.background.ctx.drawImage(this.layers.drawing.canvas, 0, 0, this.width, this.height) - var base64 = this.layers.background.canvas.toDataURL() - initImagePreview.src = base64 // this will trigger the rest of the app to use it - } - else { - // This is an inpainter, so make sure the toggle is set accordingly - var is_blank = !this.layers.drawing.ctx - .getImageData(0, 0, this.width, this.height).data - .some(channel => channel !== 0) - maskSetting.checked = !is_blank - } - this.hide() - } - getImg() { // a drop-in replacement of the drawingboard version - return this.layers.drawing.canvas.toDataURL() - } - setImg(dataUrl) { // a drop-in replacement of the drawingboard version - var image = new Image() - image.onload = () => { - var ctx = this.layers.drawing.ctx; - ctx.clearRect(0, 0, this.width, this.height) - ctx.globalCompositeOperation = "source-over" - ctx.globalAlpha = 1 - ctx.filter = "none" - ctx.drawImage(image, 0, 0, this.width, this.height) - this.setBrush(this.layers.drawing) - } - image.src = dataUrl - } - runAction(action_id) { - var action = IMAGE_EDITOR_ACTIONS.find(a => a.id == action_id) - if (action.trackHistory) { - this.history.pushAction(action_id) - } - action.handler(this) - } - setBrush(layer = null, options = null) { - if (options == null) { - options = this.options - } - if (layer) { - layer.ctx.lineCap = "round" - layer.ctx.lineJoin = "round" - layer.ctx.lineWidth = options.brush_size - layer.ctx.fillStyle = options.color - layer.ctx.strokeStyle = options.color - var sharpness = parseInt(options.sharpness * options.brush_size) - layer.ctx.filter = sharpness == 0 ? `none` : `blur(${sharpness}px)` - layer.ctx.globalAlpha = (1 - options.opacity) - layer.ctx.globalCompositeOperation = "source-over" - var tool = IMAGE_EDITOR_TOOLS.find(t => t.id == options.tool) - if (tool && tool.setBrush) { - tool.setBrush(editor, layer) - } - } - else { - Object.values([ "drawing", "overlay" ]).map(name => this.layers[name]).forEach(l => { - this.setBrush(l) - }) - } - } - get ctx_overlay() { - return this.layers.overlay.ctx - } - get ctx_current() { // the idea is this will help support having custom layers and editing each one - return this.layers.drawing.ctx - } - get canvas_current() { - return this.layers.drawing.canvas - } - keyHandler(event) { // handles keybinds like ctrl+z, ctrl+y - if (!this.popup.classList.contains("active")) { - document.removeEventListener("keydown", this.keyHandlerBound) - document.removeEventListener("keyup", this.keyHandlerBound) - return // this catches if something else closes the window but doesnt properly unbind the key handler - } + if (this.inpainter) { + this.selectOption("color", IMAGE_EDITOR_SECTIONS.find((s) => s.name == "color").options.indexOf("#ffffff")) + this.selectOption("opacity", IMAGE_EDITOR_SECTIONS.find((s) => s.name == "opacity").options.indexOf(0.4)) + } - // keybindings - if (event.type == "keydown") { - if ((event.key == "z" || event.key == "Z") && event.ctrlKey) { - if (!event.shiftKey) { - this.history.undo() - } - else { - this.history.redo() - } - } - if (event.key == "y" && event.ctrlKey) { - this.history.redo() - } - if (event.key === "Escape") { - this.hide() - } - } - - // dropper ctrl holding handler stuff - var dropper_active = this.temp_previous_tool != null; - if (dropper_active && !event.ctrlKey) { - this.selectOption("tool", IMAGE_EDITOR_TOOLS.findIndex(t => t.id == this.temp_previous_tool)) - this.temp_previous_tool = null - } - else if (!dropper_active && event.ctrlKey) { - this.temp_previous_tool = this.getOptionValue("tool") - this.selectOption("tool", IMAGE_EDITOR_TOOLS.findIndex(t => t.id == "colorpicker")) - } - } - mouseHandler(event) { - var bbox = this.layers.overlay.canvas.getBoundingClientRect() - var x = (event.clientX || 0) - bbox.left - var y = (event.clientY || 0) - bbox.top - var type = event.type; - var touchmap = { - touchstart: "mousedown", - touchmove: "mousemove", - touchend: "mouseup", - touchcancel: "mouseup" - } - if (type in touchmap) { - type = touchmap[type] - if (event.touches && event.touches[0]) { - var touch = event.touches[0] - var x = (touch.clientX || 0) - bbox.left - var y = (touch.clientY || 0) - bbox.top - } - } - event.preventDefault() - // do drawing-related stuff - if (type == "mousedown" || (type == "mouseenter" && event.buttons == 1)) { - this.drawing = true - this.tool.begin(this, this.ctx_current, x, y) - this.tool.begin(this, this.ctx_overlay, x, y, true) - this.history.editBegin(x, y) - } - if (type == "mouseup" || type == "mousemove") { - if (this.drawing) { - if (x > 0 && y > 0) { - this.tool.move(this, this.ctx_current, x, y) - this.tool.move(this, this.ctx_overlay, x, y, true) - this.history.editMove(x, y) - } - } - } - if (type == "mouseup" || type == "mouseout") { - if (this.drawing) { - this.drawing = false - this.tool.end(this, this.ctx_current, x, y) - this.tool.end(this, this.ctx_overlay, x, y, true) - this.history.editEnd(x, y) - } - } - } - getOptionValue(section_name) { - var section = IMAGE_EDITOR_SECTIONS.find(s => s.name == section_name) - return this.options && section_name in this.options ? this.options[section_name] : section.default - } - selectOption(section_name, option_index) { - var section = IMAGE_EDITOR_SECTIONS.find(s => s.name == section_name) - var value = section.options[option_index] - this.options[section_name] = value == "custom" ? section.getCustom(this) : value - - this.optionElements[section_name].forEach(element => element.classList.remove("active")) - this.optionElements[section_name][option_index].classList.add("active") - - // change the editor - this.setBrush() - if (section.name == "tool") { - this.loadTool() - } - } + // initialize the right-side controls + var buttonContainer = document.createElement("div") + IMAGE_EDITOR_BUTTONS.forEach((button) => { + var element = document.createElement("div") + var icon = document.createElement("i") + element.className = "image-editor-button button" + icon.className = button.icon + element.appendChild(icon) + element.append(button.name) + buttonContainer.appendChild(element) + element.addEventListener("click", (event) => button.handler(this)) + }) + var actionsContainer = document.createElement("div") + var actionsTitle = document.createElement("h4") + actionsTitle.textContent = "Actions" + actionsContainer.appendChild(actionsTitle) + IMAGE_EDITOR_ACTIONS.forEach((action) => { + var element = document.createElement("div") + var icon = document.createElement("i") + element.className = "image-editor-button button" + if (action.className) { + element.className += " " + action.className + } + icon.className = action.icon + element.appendChild(icon) + element.append(action.name) + actionsContainer.appendChild(element) + element.addEventListener("click", (event) => this.runAction(action.id)) + }) + this.popup.querySelector(".editor-controls-right").appendChild(actionsContainer) + this.popup.querySelector(".editor-controls-right").appendChild(buttonContainer) + + this.keyHandlerBound = this.keyHandler.bind(this) + + this.setSize(512, 512) + } + show() { + this.popup.classList.add("active") + document.addEventListener("keydown", this.keyHandlerBound, true) + document.addEventListener("keyup", this.keyHandlerBound, true) + } + hide() { + this.popup.classList.remove("active") + document.removeEventListener("keydown", this.keyHandlerBound, true) + document.removeEventListener("keyup", this.keyHandlerBound, true) + } + setSize(width, height) { + if (width == this.width && height == this.height) { + return + } + + if (width > height) { + var max_size = Math.min(parseInt(window.innerWidth * 0.9), width, 768) + var multiplier = max_size / width + width = (multiplier * width).toFixed() + height = (multiplier * height).toFixed() + } else { + var max_size = Math.min(parseInt(window.innerHeight * 0.9), height, 768) + var multiplier = max_size / height + width = (multiplier * width).toFixed() + height = (multiplier * height).toFixed() + } + this.width = parseInt(width) + this.height = parseInt(height) + + this.container.style.width = width + "px" + this.container.style.height = height + "px" + + Object.values(this.layers).forEach((layer) => { + layer.canvas.width = width + layer.canvas.height = height + }) + + if (this.inpainter) { + this.saveImage() // We've reset the size of the image so inpainting is different + } + this.setBrush() + this.history.clear() + } + get tool() { + var tool_id = this.getOptionValue("tool") + return IMAGE_EDITOR_TOOLS.find((t) => t.id == tool_id) + } + loadTool() { + this.drawing = false + this.container.style.cursor = this.tool.cursor + } + setImage(url, width, height) { + this.setSize(width, height) + this.layers.background.ctx.clearRect(0, 0, this.width, this.height) + if (!(url && this.inpainter)) { + this.layers.drawing.ctx.clearRect(0, 0, this.width, this.height) + } + if (url) { + var image = new Image() + image.onload = () => { + this.layers.background.ctx.drawImage(image, 0, 0, this.width, this.height) + } + image.src = url + } else { + this.layers.background.ctx.fillStyle = "#ffffff" + this.layers.background.ctx.beginPath() + this.layers.background.ctx.rect(0, 0, this.width, this.height) + this.layers.background.ctx.fill() + } + this.history.clear() + } + saveImage() { + if (!this.inpainter) { + // This is not an inpainter, so save the image as the new img2img input + this.layers.background.ctx.drawImage(this.layers.drawing.canvas, 0, 0, this.width, this.height) + var base64 = this.layers.background.canvas.toDataURL() + initImagePreview.src = base64 // this will trigger the rest of the app to use it + } else { + // This is an inpainter, so make sure the toggle is set accordingly + var is_blank = !this.layers.drawing.ctx + .getImageData(0, 0, this.width, this.height) + .data.some((channel) => channel !== 0) + maskSetting.checked = !is_blank + } + this.hide() + } + getImg() { + // a drop-in replacement of the drawingboard version + return this.layers.drawing.canvas.toDataURL() + } + setImg(dataUrl) { + // a drop-in replacement of the drawingboard version + var image = new Image() + image.onload = () => { + var ctx = this.layers.drawing.ctx + ctx.clearRect(0, 0, this.width, this.height) + ctx.globalCompositeOperation = "source-over" + ctx.globalAlpha = 1 + ctx.filter = "none" + ctx.drawImage(image, 0, 0, this.width, this.height) + this.setBrush(this.layers.drawing) + } + image.src = dataUrl + } + runAction(action_id) { + var action = IMAGE_EDITOR_ACTIONS.find((a) => a.id == action_id) + if (action.trackHistory) { + this.history.pushAction(action_id) + } + action.handler(this) + } + setBrush(layer = null, options = null) { + if (options == null) { + options = this.options + } + if (layer) { + layer.ctx.lineCap = "round" + layer.ctx.lineJoin = "round" + layer.ctx.lineWidth = options.brush_size + layer.ctx.fillStyle = options.color + layer.ctx.strokeStyle = options.color + var sharpness = parseInt(options.sharpness * options.brush_size) + layer.ctx.filter = sharpness == 0 ? `none` : `blur(${sharpness}px)` + layer.ctx.globalAlpha = 1 - options.opacity + layer.ctx.globalCompositeOperation = "source-over" + var tool = IMAGE_EDITOR_TOOLS.find((t) => t.id == options.tool) + if (tool && tool.setBrush) { + tool.setBrush(editor, layer) + } + } else { + Object.values(["drawing", "overlay"]) + .map((name) => this.layers[name]) + .forEach((l) => { + this.setBrush(l) + }) + } + } + get ctx_overlay() { + return this.layers.overlay.ctx + } + get ctx_current() { + // the idea is this will help support having custom layers and editing each one + return this.layers.drawing.ctx + } + get canvas_current() { + return this.layers.drawing.canvas + } + keyHandler(event) { + // handles keybinds like ctrl+z, ctrl+y + if (!this.popup.classList.contains("active")) { + document.removeEventListener("keydown", this.keyHandlerBound) + document.removeEventListener("keyup", this.keyHandlerBound) + return // this catches if something else closes the window but doesnt properly unbind the key handler + } + + // keybindings + if (event.type == "keydown") { + if ((event.key == "z" || event.key == "Z") && event.ctrlKey) { + if (!event.shiftKey) { + this.history.undo() + } else { + this.history.redo() + } + event.stopPropagation() + event.preventDefault() + } + if (event.key == "y" && event.ctrlKey) { + this.history.redo() + event.stopPropagation() + event.preventDefault() + } + if (event.key === "Escape") { + this.hide() + event.stopPropagation() + event.preventDefault() + } + } + + // dropper ctrl holding handler stuff + var dropper_active = this.temp_previous_tool != null + if (dropper_active && !event.ctrlKey) { + this.selectOption( + "tool", + IMAGE_EDITOR_TOOLS.findIndex((t) => t.id == this.temp_previous_tool) + ) + this.temp_previous_tool = null + } else if (!dropper_active && event.ctrlKey) { + this.temp_previous_tool = this.getOptionValue("tool") + this.selectOption( + "tool", + IMAGE_EDITOR_TOOLS.findIndex((t) => t.id == "colorpicker") + ) + } + } + mouseHandler(event) { + var bbox = this.layers.overlay.canvas.getBoundingClientRect() + var x = (event.clientX || 0) - bbox.left + var y = (event.clientY || 0) - bbox.top + var type = event.type + var touchmap = { + touchstart: "mousedown", + touchmove: "mousemove", + touchend: "mouseup", + touchcancel: "mouseup", + } + if (type in touchmap) { + type = touchmap[type] + if (event.touches && event.touches[0]) { + var touch = event.touches[0] + var x = (touch.clientX || 0) - bbox.left + var y = (touch.clientY || 0) - bbox.top + } + } + event.preventDefault() + // do drawing-related stuff + if (type == "mousedown" || (type == "mouseenter" && event.buttons == 1)) { + this.drawing = true + this.tool.begin(this, this.ctx_current, x, y) + this.tool.begin(this, this.ctx_overlay, x, y, true) + this.history.editBegin(x, y) + } + if (type == "mouseup" || type == "mousemove") { + if (this.drawing) { + if (x > 0 && y > 0) { + this.tool.move(this, this.ctx_current, x, y) + this.tool.move(this, this.ctx_overlay, x, y, true) + this.history.editMove(x, y) + } + } + } + if (type == "mouseup" || type == "mouseout") { + if (this.drawing) { + this.drawing = false + this.tool.end(this, this.ctx_current, x, y) + this.tool.end(this, this.ctx_overlay, x, y, true) + this.history.editEnd(x, y) + } + } + } + getOptionValue(section_name) { + var section = IMAGE_EDITOR_SECTIONS.find((s) => s.name == section_name) + return this.options && section_name in this.options ? this.options[section_name] : section.default + } + selectOption(section_name, option_index) { + var section = IMAGE_EDITOR_SECTIONS.find((s) => s.name == section_name) + var value = section.options[option_index] + this.options[section_name] = value == "custom" ? section.getCustom(this) : value + + this.optionElements[section_name].forEach((element) => element.classList.remove("active")) + this.optionElements[section_name][option_index].classList.add("active") + + // change the editor + this.setBrush() + if (section.name == "tool") { + this.loadTool() + } + } } const imageEditor = new ImageEditor(document.getElementById("image-editor")) @@ -764,114 +802,127 @@ imageEditor.setImage(null, 512, 512) imageInpainter.setImage(null, 512, 512) document.getElementById("init_image_button_draw").addEventListener("click", () => { - imageEditor.show() + imageEditor.show() }) document.getElementById("init_image_button_inpaint").addEventListener("click", () => { - imageInpainter.show() + imageInpainter.show() }) img2imgUnload() // no init image when the app starts - function rgbToHex(rgb) { - function componentToHex(c) { - var hex = parseInt(c).toString(16) - return hex.length == 1 ? "0" + hex : hex - } - return "#" + componentToHex(rgb.r) + componentToHex(rgb.g) + componentToHex(rgb.b) + function componentToHex(c) { + var hex = parseInt(c).toString(16) + return hex.length == 1 ? "0" + hex : hex + } + return "#" + componentToHex(rgb.r) + componentToHex(rgb.g) + componentToHex(rgb.b) } function hexToRgb(hex) { - var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : null; + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) + return result + ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16), + } + : null } function pixelCompare(int1, int2) { - return Math.abs(int1 - int2) < 4 + return Math.abs(int1 - int2) < 4 } // adapted from https://ben.akrin.com/canvas_fill/fill_04.html +// May 2023 - look at using a library instead of custom code: https://github.com/shaneosullivan/example-canvas-fill function flood_fill(editor, the_canvas_context, x, y, color) { - pixel_stack = [{x:x, y:y}] ; - pixels = the_canvas_context.getImageData( 0, 0, editor.width, editor.height ) ; - var linear_cords = ( y * editor.width + x ) * 4 ; - var original_color = {r:pixels.data[linear_cords], - g:pixels.data[linear_cords+1], - b:pixels.data[linear_cords+2], - a:pixels.data[linear_cords+3]} ; - - var opacity = color.a / 255; - var new_color = { - r: parseInt((color.r * opacity) + (original_color.r * (1 - opacity))), - g: parseInt((color.g * opacity) + (original_color.g * (1 - opacity))), - b: parseInt((color.b * opacity) + (original_color.b * (1 - opacity))) - } + pixel_stack = [{ x: x, y: y }] + pixels = the_canvas_context.getImageData(0, 0, editor.width, editor.height) + var linear_cords = (y * editor.width + x) * 4 + var original_color = { + r: pixels.data[linear_cords], + g: pixels.data[linear_cords + 1], + b: pixels.data[linear_cords + 2], + a: pixels.data[linear_cords + 3], + } - if ((pixelCompare(new_color.r, original_color.r) && - pixelCompare(new_color.g, original_color.g) && - pixelCompare(new_color.b, original_color.b))) - { - return; // This color is already the color we want, so do nothing - } - var max_stack_size = editor.width * editor.height; - while( pixel_stack.length > 0 && pixel_stack.length < max_stack_size ) { - new_pixel = pixel_stack.shift() ; - x = new_pixel.x ; - y = new_pixel.y ; - - linear_cords = ( y * editor.width + x ) * 4 ; - while( y-->=0 && - (pixelCompare(pixels.data[linear_cords], original_color.r) && - pixelCompare(pixels.data[linear_cords+1], original_color.g) && - pixelCompare(pixels.data[linear_cords+2], original_color.b))) { - linear_cords -= editor.width * 4 ; - } - linear_cords += editor.width * 4 ; - y++ ; + var opacity = color.a / 255 + var new_color = { + r: parseInt(color.r * opacity + original_color.r * (1 - opacity)), + g: parseInt(color.g * opacity + original_color.g * (1 - opacity)), + b: parseInt(color.b * opacity + original_color.b * (1 - opacity)), + } - var reached_left = false ; - var reached_right = false ; - while( y++ 0 && pixel_stack.length < max_stack_size) { + new_pixel = pixel_stack.shift() + x = new_pixel.x + y = new_pixel.y - if( x>0 ) { - if( pixelCompare(pixels.data[linear_cords-4], original_color.r) && - pixelCompare(pixels.data[linear_cords-4+1], original_color.g) && - pixelCompare(pixels.data[linear_cords-4+2], original_color.b)) { - if( !reached_left ) { - pixel_stack.push( {x:x-1, y:y} ) ; - reached_left = true ; - } - } else if( reached_left ) { - reached_left = false ; - } - } - - if( x= 0 && + pixelCompare(pixels.data[linear_cords], original_color.r) && + pixelCompare(pixels.data[linear_cords + 1], original_color.g) && + pixelCompare(pixels.data[linear_cords + 2], original_color.b) + ) { + linear_cords -= editor.width * 4 + } + linear_cords += editor.width * 4 + y++ + + var reached_left = false + var reached_right = false + while ( + y++ < editor.height && + pixelCompare(pixels.data[linear_cords], original_color.r) && + pixelCompare(pixels.data[linear_cords + 1], original_color.g) && + pixelCompare(pixels.data[linear_cords + 2], original_color.b) + ) { + pixels.data[linear_cords] = new_color.r + pixels.data[linear_cords + 1] = new_color.g + pixels.data[linear_cords + 2] = new_color.b + pixels.data[linear_cords + 3] = 255 + + if (x > 0) { + if ( + pixelCompare(pixels.data[linear_cords - 4], original_color.r) && + pixelCompare(pixels.data[linear_cords - 4 + 1], original_color.g) && + pixelCompare(pixels.data[linear_cords - 4 + 2], original_color.b) + ) { + if (!reached_left) { + pixel_stack.push({ x: x - 1, y: y }) + reached_left = true + } + } else if (reached_left) { + reached_left = false + } + } + + if (x < editor.width - 1) { + if ( + pixelCompare(pixels.data[linear_cords + 4], original_color.r) && + pixelCompare(pixels.data[linear_cords + 4 + 1], original_color.g) && + pixelCompare(pixels.data[linear_cords + 4 + 2], original_color.b) + ) { + if (!reached_right) { + pixel_stack.push({ x: x + 1, y: y }) + reached_right = true + } + } else if (reached_right) { + reached_right = false + } + } + + linear_cords += editor.width * 4 + } + } + the_canvas_context.putImageData(pixels, 0, 0) } diff --git a/ui/media/js/image-modal.js b/ui/media/js/image-modal.js index 498c5f24..28c1eaf2 100644 --- a/ui/media/js/image-modal.js +++ b/ui/media/js/image-modal.js @@ -1,44 +1,45 @@ "use strict" +/** + * @typedef {object} ImageModalRequest + * @property {string} src + * @property {ImageModalRequest | () => ImageModalRequest | undefined} previous + * @property {ImageModalRequest | () => ImageModalRequest | undefined} next + */ + +/** + * @type {(() => (string | ImageModalRequest) | string | ImageModalRequest) => {}} + */ const imageModal = (function() { - const zoomElem = createElement( - 'i', - undefined, - ['fa-solid', 'tertiaryButton'], - ) + const backElem = createElement("i", undefined, ["fa-solid", "fa-arrow-left", "tertiaryButton"]) - const closeElem = createElement( - 'i', - undefined, - ['fa-solid', 'fa-xmark', 'tertiaryButton'], - ) + const forwardElem = createElement("i", undefined, ["fa-solid", "fa-arrow-right", "tertiaryButton"]) - const menuBarElem = createElement('div', undefined, 'menu-bar', [zoomElem, closeElem]) + const zoomElem = createElement("i", undefined, ["fa-solid", "tertiaryButton"]) - const imageContainer = createElement('div', undefined, 'image-wrapper') + const closeElem = createElement("i", undefined, ["fa-solid", "fa-xmark", "tertiaryButton"]) - const backdrop = createElement('div', undefined, 'backdrop') + const menuBarElem = createElement("div", undefined, "menu-bar", [backElem, forwardElem, zoomElem, closeElem]) - const modalContainer = createElement('div', undefined, 'content', [menuBarElem, imageContainer]) + const imageContainer = createElement("div", undefined, "image-wrapper") - const modalElem = createElement( - 'div', - { id: 'viewFullSizeImgModal' }, - ['popup'], - [backdrop, modalContainer], - ) + const backdrop = createElement("div", undefined, "backdrop") + + const modalContainer = createElement("div", undefined, "content", [menuBarElem, imageContainer]) + + const modalElem = createElement("div", { id: "viewFullSizeImgModal" }, ["popup"], [backdrop, modalContainer]) document.body.appendChild(modalElem) const setZoomLevel = (value) => { - const img = imageContainer.querySelector('img') + const img = imageContainer.querySelector("img") if (value) { - zoomElem.classList.remove('fa-magnifying-glass-plus') - zoomElem.classList.add('fa-magnifying-glass-minus') + zoomElem.classList.remove("fa-magnifying-glass-plus") + zoomElem.classList.add("fa-magnifying-glass-minus") if (img) { - img.classList.remove('natural-zoom') + img.classList.remove("natural-zoom") - let zoomLevel = typeof value === 'number' ? value : img.dataset.zoomLevel + let zoomLevel = typeof value === "number" ? value : img.dataset.zoomLevel if (!zoomLevel) { zoomLevel = 100 } @@ -48,34 +49,164 @@ const imageModal = (function() { img.height = img.naturalHeight * (+zoomLevel / 100) } } else { - zoomElem.classList.remove('fa-magnifying-glass-minus') - zoomElem.classList.add('fa-magnifying-glass-plus') + zoomElem.classList.remove("fa-magnifying-glass-minus") + zoomElem.classList.add("fa-magnifying-glass-plus") if (img) { - img.classList.add('natural-zoom') - img.removeAttribute('width') - img.removeAttribute('height') + img.classList.add("natural-zoom") + img.removeAttribute("width") + img.removeAttribute("height") } } } - zoomElem.addEventListener( - 'click', - () => setZoomLevel(imageContainer.querySelector('img')?.classList?.contains('natural-zoom')), + zoomElem.addEventListener("click", () => + setZoomLevel(imageContainer.querySelector("img")?.classList?.contains("natural-zoom")) ) - const close = () => { - imageContainer.innerHTML = '' - modalElem.classList.remove('active') - document.body.style.overflow = 'initial' + const initialState = () => ({ + previous: undefined, + next: undefined, + + start: { + x: 0, + y: 0, + }, + + scroll: { + x: 0, + y: 0, + }, + }) + + const state = initialState() + + // Allow grabbing the image to scroll + const stopGrabbing = (e) => { + if(imageContainer.classList.contains("grabbing")) { + imageContainer.classList.remove("grabbing") + e?.preventDefault() + console.log(`stopGrabbing()`, e) + } } - window.addEventListener('keydown', (e) => { - if (e.key === 'Escape' && modalElem.classList.contains('active')) { + const addImageGrabbing = (image) => { + image?.addEventListener('mousedown', (e) => { + if (!image.classList.contains("natural-zoom")) { + e.stopPropagation() + e.stopImmediatePropagation() + e.preventDefault() + + imageContainer.classList.add("grabbing") + state.start.x = e.pageX - imageContainer.offsetLeft + state.scroll.x = imageContainer.scrollLeft + state.start.y = e.pageY - imageContainer.offsetTop + state.scroll.y = imageContainer.scrollTop + } + }) + + image?.addEventListener('mouseup', stopGrabbing) + image?.addEventListener('mouseleave', stopGrabbing) + image?.addEventListener('mousemove', (e) => { + if(imageContainer.classList.contains("grabbing")) { + e.stopPropagation() + e.stopImmediatePropagation() + e.preventDefault() + + // Might need to increase this multiplier based on the image size to window size ratio + // The default 1:1 is pretty slow + const multiplier = 1.0 + + const deltaX = e.pageX - imageContainer.offsetLeft - state.start.x + imageContainer.scrollLeft = state.scroll.x - (deltaX * multiplier) + const deltaY = e.pageY - imageContainer.offsetTop - state.start.y + imageContainer.scrollTop = state.scroll.y - (deltaY * multiplier) + } + }) + } + + const clear = () => { + imageContainer.innerHTML = "" + + Object.entries(initialState()).forEach(([key, value]) => state[key] = value) + + stopGrabbing() + } + + const close = () => { + clear() + modalElem.classList.remove("active") + document.body.style.overflow = "initial" + } + + /** + * @param {() => (string | ImageModalRequest) | string | ImageModalRequest} optionsFactory + */ + function init(optionsFactory) { + if (!optionsFactory) { close() + return + } + + clear() + + const options = typeof optionsFactory === "function" ? optionsFactory() : optionsFactory + const src = typeof options === "string" ? options : options.src + + const imgElem = createElement("img", { src }, "natural-zoom") + addImageGrabbing(imgElem) + imageContainer.appendChild(imgElem) + modalElem.classList.add("active") + document.body.style.overflow = "hidden" + setZoomLevel(false) + + if (typeof options === "object" && options.previous) { + state.previous = options.previous + backElem.style.display = "unset" + } else { + backElem.style.display = "none" + } + + if (typeof options === "object" && options.next) { + state.next = options.next + forwardElem.style.display = "unset" + } else { + forwardElem.style.display = "none" + } + } + + const back = () => { + if (state.previous) { + init(state.previous) + } else { + backElem.style.display = "none" + } + } + + const forward = () => { + if (state.next) { + init(state.next) + } else { + forwardElem.style.display = "none" + } + } + + window.addEventListener("keydown", (e) => { + if (modalElem.classList.contains("active")) { + switch (e.key) { + case "Escape": + close() + break + case "ArrowLeft": + back() + break + case "ArrowRight": + forward() + break + } } }) - window.addEventListener('click', (e) => { - if (modalElem.classList.contains('active')) { + window.addEventListener("click", (e) => { + if (modalElem.classList.contains("active")) { if (e.target === backdrop || e.target === closeElem) { close() } @@ -86,15 +217,12 @@ const imageModal = (function() { } }) - return (optionsFactory) => { - const options = typeof optionsFactory === 'function' ? optionsFactory() : optionsFactory - const src = typeof options === 'string' ? options : options.src + backElem.addEventListener("click", back) - // TODO center it if < window size - const imgElem = createElement('img', { src }, 'natural-zoom') - imageContainer.appendChild(imgElem) - modalElem.classList.add('active') - document.body.style.overflow = 'hidden' - setZoomLevel(false) - } + forwardElem.addEventListener("click", forward) + + /** + * @param {() => (string | ImageModalRequest) | string | ImageModalRequest} optionsFactory + */ + return (optionsFactory) => init(optionsFactory) })() diff --git a/ui/media/js/image-modifiers.js b/ui/media/js/image-modifiers.js index 194565c4..5f3a9014 100644 --- a/ui/media/js/image-modifiers.js +++ b/ui/media/js/image-modifiers.js @@ -1,216 +1,249 @@ let activeTags = [] let modifiers = [] let customModifiersGroupElement = undefined -let customModifiersInitialContent +let customModifiersInitialContent = "" +let modifierPanelFreezed = false -let editorModifierEntries = document.querySelector('#editor-modifiers-entries') -let editorModifierTagsList = document.querySelector('#editor-inputs-tags-list') -let editorTagsContainer = document.querySelector('#editor-inputs-tags-container') -let modifierCardSizeSlider = document.querySelector('#modifier-card-size-slider') -let previewImageField = document.querySelector('#preview-image') -let modifierSettingsBtn = document.querySelector('#modifier-settings-btn') -let modifierSettingsOverlay = document.querySelector('#modifier-settings-config') -let customModifiersTextBox = document.querySelector('#custom-modifiers-input') -let customModifierEntriesToolbar = document.querySelector('#editor-modifiers-entries-toolbar') +let modifiersMainContainer = document.querySelector("#editor-modifiers") +let modifierDropdown = document.querySelector("#image-modifier-dropdown") +let editorModifiersContainer = document.querySelector("#editor-modifiers") +let editorModifierEntries = document.querySelector("#editor-modifiers-entries") +let editorModifierTagsList = document.querySelector("#editor-inputs-tags-list") +let editorTagsContainer = document.querySelector("#editor-inputs-tags-container") +let modifierCardSizeSlider = document.querySelector("#modifier-card-size-slider") +let previewImageField = document.querySelector("#preview-image") +let modifierSettingsBtn = document.querySelector("#modifier-settings-btn") +let modifiersContainerSizeBtn = document.querySelector("#modifiers-container-size-btn") +let modifiersCloseBtn = document.querySelector("#modifiers-close-button") +let modifiersCollapsiblesBtn = document.querySelector("#modifiers-action-collapsibles-btn") +let modifierSettingsOverlay = document.querySelector("#modifier-settings-config") +let customModifiersTextBox = document.querySelector("#custom-modifiers-input") +let customModifierEntriesToolbar = document.querySelector("#editor-modifiers-entries-toolbar") -const modifierThumbnailPath = 'media/modifier-thumbnails' -const activeCardClass = 'modifier-card-active' +const modifierThumbnailPath = "media/modifier-thumbnails" +const activeCardClass = "modifier-card-active" const CUSTOM_MODIFIERS_KEY = "customModifiers" function createModifierCard(name, previews, removeBy) { - const modifierCard = document.createElement('div') - let style = previewImageField.value - let styleIndex = (style=='portrait') ? 0 : 1 + let cardPreviewImageType = previewImageField.value - modifierCard.className = 'modifier-card' + const modifierCard = document.createElement("div") + modifierCard.className = "modifier-card" modifierCard.innerHTML = `
+
-

+

No Image

Modifier Image
-

+
+ +

+
` - const image = modifierCard.querySelector('.modifier-card-image') - const errorText = modifierCard.querySelector('.modifier-card-error-label') - const label = modifierCard.querySelector('.modifier-card-label') + const image = modifierCard.querySelector(".modifier-card-image") + const longLabel = modifierCard.querySelector(".modifier-card-label span.long-label") + const regularLabel = modifierCard.querySelector(".modifier-card-label p.regular-label") - errorText.innerText = 'No Image' - - if (typeof previews == 'object') { - image.src = previews[styleIndex]; // portrait - image.setAttribute('preview-type', style) + if (typeof previews == "object") { + image.src = previews[cardPreviewImageType == "portrait" ? 0 : 1] // 0 index is portrait, 1 landscape + image.setAttribute("preview-type", cardPreviewImageType) } else { image.remove() } const maxLabelLength = 30 - const cardLabel = removeBy ? name.replace('by ', '') : name + const cardLabel = removeBy ? name.replace("by ", "") : name - if(cardLabel.length <= maxLabelLength) { - label.querySelector('p').innerText = cardLabel - } else { - const tooltipText = document.createElement('span') - tooltipText.className = 'tooltip-text' - tooltipText.innerText = name - - label.classList.add('tooltip') - label.appendChild(tooltipText) - - label.querySelector('p').innerText = cardLabel.substring(0, maxLabelLength) + '...' + function getFormattedLabel(length) { + if (cardLabel?.length <= length) { + return cardLabel + } else { + return cardLabel.substring(0, length) + "..." + } } - label.querySelector('p').dataset.fullName = name // preserve the full name + modifierCard.dataset.fullName = name // preserve the full name + regularLabel.dataset.fullName = name // preserve the full name, legacy support for older plugins + + longLabel.innerText = getFormattedLabel(maxLabelLength * 2) + regularLabel.innerText = getFormattedLabel(maxLabelLength) + + if (cardLabel.length > maxLabelLength) { + modifierCard.classList.add("support-long-label") + + if (cardLabel.length > maxLabelLength * 2) { + modifierCard.title = `"${name}"` + } + } + return modifierCard } -function createModifierGroup(modifierGroup, initiallyExpanded, removeBy) { +function createModifierGroup(modifierGroup, isInitiallyOpen, removeBy) { const title = modifierGroup.category const modifiers = modifierGroup.modifiers - const titleEl = document.createElement('h5') - titleEl.className = 'collapsible' + const titleEl = document.createElement("h5") + titleEl.className = "collapsible" titleEl.innerText = title - const modifiersEl = document.createElement('div') - modifiersEl.classList.add('collapsible-content', 'editor-modifiers-leaf') + const modifiersEl = document.createElement("div") + modifiersEl.classList.add("collapsible-content", "editor-modifiers-leaf") - if (initiallyExpanded === true) { - titleEl.className += ' active' + if (isInitiallyOpen === true) { + titleEl.classList.add("active") } - modifiers.forEach(modObj => { + modifiers.forEach((modObj) => { const modifierName = modObj.modifier - const modifierPreviews = modObj?.previews?.map(preview => `${IMAGE_REGEX.test(preview.image) ? preview.image : modifierThumbnailPath + '/' + preview.path}`) + const modifierPreviews = modObj?.previews?.map( + (preview) => + `${IMAGE_REGEX.test(preview.image) ? preview.image : modifierThumbnailPath + "/" + preview.path}` + ) const modifierCard = createModifierCard(modifierName, modifierPreviews, removeBy) - if(typeof modifierCard == 'object') { + if (typeof modifierCard == "object") { modifiersEl.appendChild(modifierCard) const trimmedName = trimModifiers(modifierName) - modifierCard.addEventListener('click', () => { - if (activeTags.map(x => trimModifiers(x.name)).includes(trimmedName)) { + modifierCard.addEventListener("click", () => { + if (activeTags.map((x) => trimModifiers(x.name)).includes(trimmedName)) { // remove modifier from active array - activeTags = activeTags.filter(x => trimModifiers(x.name) != trimmedName) + activeTags = activeTags.filter((x) => trimModifiers(x.name) != trimmedName) toggleCardState(trimmedName, false) } else { // add modifier to active array activeTags.push({ - 'name': modifierName, - 'element': modifierCard.cloneNode(true), - 'originElement': modifierCard, - 'previews': modifierPreviews + name: modifierName, + element: modifierCard.cloneNode(true), + originElement: modifierCard, + previews: modifierPreviews, }) toggleCardState(trimmedName, true) } refreshTagsList() - document.dispatchEvent(new Event('refreshImageModifiers')) + document.dispatchEvent(new Event("refreshImageModifiers")) }) } }) - let brk = document.createElement('br') - brk.style.clear = 'both' + let brk = document.createElement("br") + brk.style.clear = "both" modifiersEl.appendChild(brk) - let e = document.createElement('div') - e.className = 'modifier-category' + let e = document.createElement("div") + e.className = "modifier-category" e.appendChild(titleEl) e.appendChild(modifiersEl) - editorModifierEntries.insertBefore(e, customModifierEntriesToolbar.nextSibling) + editorModifierEntries.prepend(e) return e } function trimModifiers(tag) { // Remove trailing '-' and/or '+' - tag = tag.replace(/[-+]+$/, ''); + tag = tag.replace(/[-+]+$/, "") // Remove parentheses at beginning and end - return tag.replace(/^[(]+|[\s)]+$/g, ''); + return tag.replace(/^[(]+|[\s)]+$/g, "") } async function loadModifiers() { try { - let res = await fetch('/get/modifiers') + let res = await fetch("/get/modifiers") if (res.status === 200) { res = await res.json() - modifiers = res; // update global variable + modifiers = res // update global variable res.reverse() res.forEach((modifierGroup, idx) => { - createModifierGroup(modifierGroup, idx === res.length - 1, modifierGroup === 'Artist' ? true : false) // only remove "By " for artists + const isInitiallyOpen = false // idx === res.length - 1 + const removeBy = modifierGroup === "Artist" ? true : false // only remove "By " for artists + + createModifierGroup(modifierGroup, isInitiallyOpen, removeBy) }) createCollapsibles(editorModifierEntries) } } catch (e) { - console.error('error fetching modifiers', e) + console.error("error fetching modifiers", e) } loadCustomModifiers() resizeModifierCards(modifierCardSizeSlider.value) - document.dispatchEvent(new Event('loadImageModifiers')) + document.dispatchEvent(new Event("loadImageModifiers")) } function refreshModifiersState(newTags, inactiveTags) { // clear existing modifiers - document.querySelector('#editor-modifiers').querySelectorAll('.modifier-card').forEach(modifierCard => { - const modifierName = modifierCard.querySelector('.modifier-card-label p').dataset.fullName // pick the full modifier name - if (activeTags.map(x => x.name).includes(modifierName)) { - modifierCard.classList.remove(activeCardClass) - modifierCard.querySelector('.modifier-card-image-overlay').innerText = '+' - } - }) + document + .querySelector("#editor-modifiers") + .querySelectorAll(".modifier-card") + .forEach((modifierCard) => { + const modifierName = modifierCard.dataset.fullName // pick the full modifier name + if (activeTags.map((x) => x.name).includes(modifierName)) { + modifierCard.classList.remove(activeCardClass) + modifierCard.querySelector(".modifier-card-image-overlay").innerText = "+" + } + }) activeTags = [] // set new modifiers - newTags.forEach(tag => { + newTags.forEach((tag) => { let found = false - document.querySelector('#editor-modifiers').querySelectorAll('.modifier-card').forEach(modifierCard => { - const modifierName = modifierCard.querySelector('.modifier-card-label p').dataset.fullName - const shortModifierName = modifierCard.querySelector('.modifier-card-label p').innerText - if (trimModifiers(tag) == trimModifiers(modifierName)) { - // add modifier to active array - if (!activeTags.map(x => x.name).includes(tag)) { // only add each tag once even if several custom modifier cards share the same tag - const imageModifierCard = modifierCard.cloneNode(true) - imageModifierCard.querySelector('.modifier-card-label p').innerText = tag.replace(modifierName, shortModifierName) - activeTags.push({ - 'name': tag, - 'element': imageModifierCard, - 'originElement': modifierCard - }) + document + .querySelector("#editor-modifiers") + .querySelectorAll(".modifier-card") + .forEach((modifierCard) => { + const modifierName = modifierCard.dataset.fullName + const shortModifierName = modifierCard.querySelector(".modifier-card-label p").innerText + + if (trimModifiers(tag) == trimModifiers(modifierName)) { + // add modifier to active array + if (!activeTags.map((x) => x.name).includes(tag)) { + // only add each tag once even if several custom modifier cards share the same tag + const imageModifierCard = modifierCard.cloneNode(true) + imageModifierCard.querySelector(".modifier-card-label p").innerText = tag.replace( + modifierName, + shortModifierName + ) + activeTags.push({ + name: tag, + element: imageModifierCard, + originElement: modifierCard, + }) + } + modifierCard.classList.add(activeCardClass) + modifierCard.querySelector(".modifier-card-image-overlay").innerText = "-" + found = true } - modifierCard.classList.add(activeCardClass) - modifierCard.querySelector('.modifier-card-image-overlay').innerText = '-' - found = true - } - }) - if (found == false) { // custom tag went missing, create one here + }) + if (found == false) { + // custom tag went missing, create one here let modifierCard = createModifierCard(tag, undefined, false) // create a modifier card for the missing tag, no image - - modifierCard.addEventListener('click', () => { - if (activeTags.map(x => x.name).includes(tag)) { + + modifierCard.addEventListener("click", () => { + if (activeTags.map((x) => x.name).includes(tag)) { // remove modifier from active array - activeTags = activeTags.filter(x => x.name != tag) + activeTags = activeTags.filter((x) => x.name != tag) modifierCard.classList.remove(activeCardClass) - modifierCard.querySelector('.modifier-card-image-overlay').innerText = '+' + modifierCard.querySelector(".modifier-card-image-overlay").innerText = "+" } refreshTagsList() }) activeTags.push({ - 'name': tag, - 'element': modifierCard, - 'originElement': undefined // no origin element for missing tags + name: tag, + element: modifierCard, + originElement: undefined, // no origin element for missing tags }) } }) @@ -220,41 +253,50 @@ function refreshModifiersState(newTags, inactiveTags) { function refreshInactiveTags(inactiveTags) { // update inactive tags if (inactiveTags !== undefined && inactiveTags.length > 0) { - activeTags.forEach (tag => { - if (inactiveTags.find(element => element === tag.name) !== undefined) { + activeTags.forEach((tag) => { + if (inactiveTags.find((element) => element === tag.name) !== undefined) { tag.inactive = true } }) } - + // update cards - let overlays = document.querySelector('#editor-inputs-tags-list').querySelectorAll('.modifier-card-overlay') - overlays.forEach (i => { - let modifierName = i.parentElement.getElementsByClassName('modifier-card-label')[0].getElementsByTagName("p")[0].innerText - if (inactiveTags?.find(element => element === modifierName) !== undefined) { - i.parentElement.classList.add('modifier-toggle-inactive') + let overlays = editorModifierTagsList.querySelectorAll(".modifier-card-overlay") + overlays.forEach((i) => { + let modifierName = i.parentElement.dataset.fullName + + if (inactiveTags?.find((element) => trimModifiers(element) === modifierName) !== undefined) { + i.parentElement.classList.add("modifier-toggle-inactive") } }) } function refreshTagsList(inactiveTags) { - editorModifierTagsList.innerHTML = '' + editorModifierTagsList.innerHTML = "" if (activeTags.length == 0) { - editorTagsContainer.style.display = 'none' + editorTagsContainer.style.display = "none" return } else { - editorTagsContainer.style.display = 'block' + editorTagsContainer.style.display = "block" + } + + if(activeTags.length > 15) { + editorModifierTagsList.style["overflow-y"] = "auto" + } else { + editorModifierTagsList.style["overflow-y"] = "unset" } activeTags.forEach((tag, index) => { - tag.element.querySelector('.modifier-card-image-overlay').innerText = '-' - tag.element.classList.add('modifier-card-tiny') + tag.element.querySelector(".modifier-card-image-overlay").innerText = "-" + tag.element.classList.add("modifier-card-tiny") editorModifierTagsList.appendChild(tag.element) - tag.element.addEventListener('click', () => { - let idx = activeTags.findIndex(o => { return o.name === tag.name }) + tag.element.addEventListener("click", () => { + let idx = activeTags.findIndex((o) => { + return o.name === tag.name + }) if (idx !== -1) { toggleCardState(activeTags[idx].name, false) @@ -262,120 +304,90 @@ function refreshTagsList(inactiveTags) { activeTags.splice(idx, 1) refreshTagsList() } - document.dispatchEvent(new Event('refreshImageModifiers')) + document.dispatchEvent(new Event("refreshImageModifiers")) }) }) - let brk = document.createElement('br') - brk.style.clear = 'both' + let brk = document.createElement("br") + brk.style.clear = "both" + editorModifierTagsList.appendChild(brk) + refreshInactiveTags(inactiveTags) - document.dispatchEvent(new Event('refreshImageModifiers')) // notify plugins that the image tags have been refreshed + + document.dispatchEvent(new Event("refreshImageModifiers")) // notify plugins that the image tags have been refreshed } function toggleCardState(modifierName, makeActive) { - document.querySelector('#editor-modifiers').querySelectorAll('.modifier-card').forEach(card => { - const name = card.querySelector('.modifier-card-label').innerText - if ( trimModifiers(modifierName) == trimModifiers(name) - || trimModifiers(modifierName) == 'by ' + trimModifiers(name)) { - if(makeActive) { - card.classList.add(activeCardClass) - card.querySelector('.modifier-card-image-overlay').innerText = '-' - } - else{ - card.classList.remove(activeCardClass) - card.querySelector('.modifier-card-image-overlay').innerText = '+' - } + const cards = [...document.querySelectorAll("#editor-modifiers .modifier-card")] + .filter(cardElem => trimModifiers(cardElem.dataset.fullName) == trimModifiers(modifierName)) + + const cardExists = typeof cards == "object" && cards?.length > 0 + + if (cardExists) { + const card = cards[0] + + if (makeActive) { + card.classList.add(activeCardClass) + card.querySelector(".modifier-card-image-overlay").innerText = "-" + } else { + card.classList.remove(activeCardClass) + card.querySelector(".modifier-card-image-overlay").innerText = "+" } - }) + } } function changePreviewImages(val) { - const previewImages = document.querySelectorAll('.modifier-card-image-container img') + const previewImages = document.querySelectorAll(".modifier-card-image-container img") - let previewArr = [] - - modifiers.map(x => x.modifiers).forEach(x => previewArr.push(...x.map(m => m.previews))) - - previewArr = previewArr.map(x => { - let obj = {} - - x.forEach(preview => { + const previewArr = modifiers.flatMap((x) => x.modifiers.map((m) => m.previews)) + .map((x) => x.reduce((obj, preview) => { obj[preview.name] = preview.path - }) - - return obj - }) - previewImages.forEach(previewImage => { - const currentPreviewType = previewImage.getAttribute('preview-type') - const relativePreviewPath = previewImage.src.split(modifierThumbnailPath + '/').pop() + return obj + }, {})) - const previews = previewArr.find(preview => relativePreviewPath == preview[currentPreviewType]) + previewImages.forEach((previewImage) => { + const currentPreviewType = previewImage.getAttribute("preview-type") + const relativePreviewPath = previewImage.src.split(modifierThumbnailPath + "/").pop() - if(typeof previews == 'object') { + const previews = previewArr.find((preview) => relativePreviewPath == preview[currentPreviewType]) + + if (typeof previews == "object") { let preview = null - if (val == 'portrait') { + if (val == "portrait") { preview = previews.portrait - } - else if (val == 'landscape') { + } else if (val == "landscape") { preview = previews.landscape } - if(preview != null) { + if (preview != null) { previewImage.src = `${modifierThumbnailPath}/${preview}` - previewImage.setAttribute('preview-type', val) + previewImage.setAttribute("preview-type", val) } } }) } function resizeModifierCards(val) { - const cardSizePrefix = 'modifier-card-size_' - const modifierCardClass = 'modifier-card' + const cardSizePrefix = "modifier-card-size_" + const modifierCardClass = "modifier-card" const modifierCards = document.querySelectorAll(`.${modifierCardClass}`) - const cardSize = n => `${cardSizePrefix}${n}` + const cardSize = (n) => `${cardSizePrefix}${n}` - modifierCards.forEach(card => { + modifierCards.forEach((card) => { // remove existing size classes - const classes = card.className.split(' ').filter(c => !c.startsWith(cardSizePrefix)) - card.className = classes.join(' ').trim() + const classes = card.className.split(" ").filter((c) => !c.startsWith(cardSizePrefix)) + card.className = classes.join(" ").trim() - if(val != 0) { + if (val != 0) { card.classList.add(cardSize(val)) } }) } -modifierCardSizeSlider.onchange = () => resizeModifierCards(modifierCardSizeSlider.value) -previewImageField.onchange = () => changePreviewImages(previewImageField.value) - -modifierSettingsBtn.addEventListener('click', function(e) { - modifierSettingsOverlay.classList.add("active") - customModifiersTextBox.setSelectionRange(0, 0) - customModifiersTextBox.focus() - customModifiersInitialContent = customModifiersTextBox.value // preserve the initial content - e.stopPropagation() -}) - -modifierSettingsOverlay.addEventListener('keydown', function(e) { - switch (e.key) { - case "Escape": // Escape to cancel - customModifiersTextBox.value = customModifiersInitialContent // undo the changes - modifierSettingsOverlay.classList.remove("active") - e.stopPropagation() - break - case "Enter": - if (e.ctrlKey) { // Ctrl+Enter to confirm - modifierSettingsOverlay.classList.remove("active") - e.stopPropagation() - break - } - } -}) - function saveCustomModifiers() { localStorage.setItem(CUSTOM_MODIFIERS_KEY, customModifiersTextBox.value.trim()) @@ -383,7 +395,167 @@ function saveCustomModifiers() { } function loadCustomModifiers() { - PLUGINS['MODIFIERS_LOAD'].forEach(fn=>fn.loader.call()) + PLUGINS["MODIFIERS_LOAD"].forEach((fn) => fn.loader.call()) } -customModifiersTextBox.addEventListener('change', saveCustomModifiers) +function showModifierContainer() { + document.addEventListener("click", checkIfClickedOutsideDropdownElem) + + modifierDropdown.dataset.active = true + editorModifiersContainer.classList.add("active") +} + +function hideModifierContainer() { + document.removeEventListener("click", checkIfClickedOutsideDropdownElem) + + modifierDropdown.dataset.active = false + editorModifiersContainer.classList.remove("active") +} + +function checkIfClickedOutsideDropdownElem(e) { + const clickedElement = e.target + + const clickedInsideSpecificElems = [modifierDropdown, editorModifiersContainer, modifierSettingsOverlay].some((div) => + div && (div.contains(clickedElement) || div === clickedElement)) + + if (!clickedInsideSpecificElems && !modifierPanelFreezed) { + hideModifierContainer() + } +} + +function collapseAllModifierCategory() { + const collapsibleElems = editorModifierEntries.querySelectorAll(".modifier-category .collapsible"); // needs to have ";" + + [...collapsibleElems].forEach((elem) => { + const isActive = elem.classList.contains("active") + + if(isActive) { + elem?.click() + } + }) +} + +function expandAllModifierCategory() { + const collapsibleElems = editorModifierEntries.querySelectorAll(".modifier-category .collapsible"); // needs to have ";" + + [...collapsibleElems].forEach((elem) => { + const isActive = elem.classList.contains("active") + + if (!isActive) { + elem?.click() + } + }) +} + +customModifiersTextBox.addEventListener("change", saveCustomModifiers) + +modifierCardSizeSlider.onchange = () => resizeModifierCards(modifierCardSizeSlider.value) +previewImageField.onchange = () => changePreviewImages(previewImageField.value) + +modifierSettingsOverlay.addEventListener("keydown", function(e) { + switch (e.key) { + case "Escape": // Escape to cancel + customModifiersTextBox.value = customModifiersInitialContent // undo the changes + modifierSettingsOverlay.classList.remove("active") + e.stopPropagation() + break + case "Enter": + if (e.ctrlKey) { + // Ctrl+Enter to confirm + modifierSettingsOverlay.classList.remove("active") + e.stopPropagation() + break + } + } +}) + +modifierDropdown.addEventListener("click", e => { + const targetElem = e.target + const isDropdownActive = targetElem.dataset.active == "true" ? true : false + + if (!isDropdownActive) + showModifierContainer() + else + hideModifierContainer() +}) + +let collapsiblesBtnState = false + +modifiersCollapsiblesBtn.addEventListener("click", (e) => { + const btnElem = modifiersCollapsiblesBtn + + const collapseText = "Collapse Categories" + const expandText = "Expand Categories" + + const collapseIconClasses = ["fa-solid", "fa-square-minus"] + const expandIconClasses = ["fa-solid", "fa-square-plus"] + + const iconElem = btnElem.querySelector(".modifiers-action-icon") + const textElem = btnElem.querySelector(".modifiers-action-text") + + if (collapsiblesBtnState) { + collapseAllModifierCategory() + + collapsiblesBtnState = false + + collapseIconClasses.forEach((c) => iconElem.classList.remove(c)) + expandIconClasses.forEach((c) => iconElem.classList.add(c)) + + textElem.innerText = expandText + } else { + expandAllModifierCategory() + + collapsiblesBtnState = true + + expandIconClasses.forEach((c) => iconElem.classList.remove(c)) + collapseIconClasses.forEach((c) => iconElem.classList.add(c)) + + textElem.innerText = collapseText + } +}) + +let containerSizeBtnState = false + +modifiersContainerSizeBtn.addEventListener("click", (e) => { + const btnElem = modifiersContainerSizeBtn + + const maximizeIconClasses = ["fa-solid", "fa-expand"] + const revertIconClasses = ["fa-solid", "fa-compress"] + + modifiersMainContainer.classList.toggle("modifiers-maximized") + + if(containerSizeBtnState) { + revertIconClasses.forEach((c) => btnElem.classList.remove(c)) + maximizeIconClasses.forEach((c) => btnElem.classList.add(c)) + + containerSizeBtnState = false + } else { + maximizeIconClasses.forEach((c) => btnElem.classList.remove(c)) + revertIconClasses.forEach((c) => btnElem.classList.add(c)) + + containerSizeBtnState = true + } +}) + +modifierSettingsBtn.addEventListener("click", (e) => { + modifierSettingsOverlay.classList.add("active") + customModifiersTextBox.setSelectionRange(0, 0) + customModifiersTextBox.focus() + customModifiersInitialContent = customModifiersTextBox.value // preserve the initial content + e.stopPropagation() +}) + +modifiersCloseBtn.addEventListener("click", (e) => { + hideModifierContainer() +}) + +// prevents the modifier panel closing at the same time as the settings overlay +new MutationObserver(() => { + const isActive = modifierSettingsOverlay.classList.contains("active") + + if (!isActive) { + modifierPanelFreezed = true + + setTimeout(() => modifierPanelFreezed = false, 25) + } +}).observe(modifierSettingsOverlay, { attributes: true }) \ No newline at end of file diff --git a/ui/media/js/main.js b/ui/media/js/main.js index e254956b..fda0493c 100644 --- a/ui/media/js/main.js +++ b/ui/media/js/main.js @@ -2,57 +2,114 @@ const MAX_INIT_IMAGE_DIMENSION = 768 const MIN_GPUS_TO_SHOW_SELECTION = 2 -const IMAGE_REGEX = new RegExp('data:image/[A-Za-z]+;base64') +const IMAGE_REGEX = new RegExp("data:image/[A-Za-z]+;base64") const htmlTaskMap = new WeakMap() +const taskConfigSetup = { + taskConfig: { + seed: { value: ({ seed }) => seed, label: "Seed" }, + dimensions: { value: ({ reqBody }) => `${reqBody?.width}x${reqBody?.height}`, label: "Dimensions" }, + sampler_name: "Sampler", + num_inference_steps: "Inference Steps", + guidance_scale: "Guidance Scale", + use_stable_diffusion_model: "Model", + clip_skip: { + label: "Clip Skip", + visible: ({ reqBody }) => reqBody?.clip_skip, + value: ({ reqBody }) => "yes", + }, + tiling: { + label: "Tiling", + visible: ({ reqBody }) => reqBody?.tiling != "none", + value: ({ reqBody }) => reqBody?.tiling, + }, + use_vae_model: { + label: "VAE", + visible: ({ reqBody }) => reqBody?.use_vae_model !== undefined && reqBody?.use_vae_model.trim() !== "", + }, + negative_prompt: { + label: "Negative Prompt", + visible: ({ reqBody }) => reqBody?.negative_prompt !== undefined && reqBody?.negative_prompt.trim() !== "", + }, + prompt_strength: "Prompt Strength", + use_face_correction: "Fix Faces", + upscale: { + value: ({ reqBody }) => `${reqBody?.use_upscale} (${reqBody?.upscale_amount || 4}x)`, + label: "Upscale", + visible: ({ reqBody }) => !!reqBody?.use_upscale, + }, + use_hypernetwork_model: "Hypernetwork", + hypernetwork_strength: { + label: "Hypernetwork Strength", + visible: ({ reqBody }) => !!reqBody?.use_hypernetwork_model, + }, + use_lora_model: { label: "Lora Model", visible: ({ reqBody }) => !!reqBody?.use_lora_model }, + lora_alpha: { label: "Lora Strength", visible: ({ reqBody }) => !!reqBody?.use_lora_model }, + preserve_init_image_color_profile: "Preserve Color Profile", + }, + pluginTaskConfig: {}, + getCSSKey: (key) => + key + .split("_") + .map((s) => s.charAt(0).toUpperCase() + s.slice(1)) + .join(""), +} + let imageCounter = 0 let imageRequest = [] -let promptField = document.querySelector('#prompt') -let promptsFromFileSelector = document.querySelector('#prompt_from_file') -let promptsFromFileBtn = document.querySelector('#promptsFromFileBtn') -let negativePromptField = document.querySelector('#negative_prompt') -let numOutputsTotalField = document.querySelector('#num_outputs_total') -let numOutputsParallelField = document.querySelector('#num_outputs_parallel') -let numInferenceStepsField = document.querySelector('#num_inference_steps') -let guidanceScaleSlider = document.querySelector('#guidance_scale_slider') -let guidanceScaleField = document.querySelector('#guidance_scale') -let outputQualitySlider = document.querySelector('#output_quality_slider') -let outputQualityField = document.querySelector('#output_quality') -let outputQualityRow = document.querySelector('#output_quality_row') +let promptField = document.querySelector("#prompt") +let promptsFromFileSelector = document.querySelector("#prompt_from_file") +let promptsFromFileBtn = document.querySelector("#promptsFromFileBtn") +let negativePromptField = document.querySelector("#negative_prompt") +let numOutputsTotalField = document.querySelector("#num_outputs_total") +let numOutputsParallelField = document.querySelector("#num_outputs_parallel") +let numInferenceStepsField = document.querySelector("#num_inference_steps") +let guidanceScaleSlider = document.querySelector("#guidance_scale_slider") +let guidanceScaleField = document.querySelector("#guidance_scale") +let outputQualitySlider = document.querySelector("#output_quality_slider") +let outputQualityField = document.querySelector("#output_quality") +let outputQualityRow = document.querySelector("#output_quality_row") let randomSeedField = document.querySelector("#random_seed") -let seedField = document.querySelector('#seed') -let widthField = document.querySelector('#width') -let heightField = document.querySelector('#height') -let smallImageWarning = document.querySelector('#small_image_warning') +let seedField = document.querySelector("#seed") +let widthField = document.querySelector("#width") +let heightField = document.querySelector("#height") +let smallImageWarning = document.querySelector("#small_image_warning") let initImageSelector = document.querySelector("#init_image") let initImagePreview = document.querySelector("#init_image_preview") let initImageSizeBox = document.querySelector("#init_image_size_box") let maskImageSelector = document.querySelector("#mask") let maskImagePreview = document.querySelector("#mask_preview") -let applyColorCorrectionField = document.querySelector('#apply_color_correction') -let colorCorrectionSetting = document.querySelector('#apply_color_correction_setting') -let promptStrengthSlider = document.querySelector('#prompt_strength_slider') -let promptStrengthField = document.querySelector('#prompt_strength') -let samplerField = document.querySelector('#sampler_name') +let applyColorCorrectionField = document.querySelector("#apply_color_correction") +let colorCorrectionSetting = document.querySelector("#apply_color_correction_setting") +let promptStrengthSlider = document.querySelector("#prompt_strength_slider") +let promptStrengthField = document.querySelector("#prompt_strength") +let samplerField = document.querySelector("#sampler_name") let samplerSelectionContainer = document.querySelector("#samplerSelection") let useFaceCorrectionField = document.querySelector("#use_face_correction") -let gfpganModelField = new ModelDropdown(document.querySelector("#gfpgan_model"), 'gfpgan') +let gfpganModelField = new ModelDropdown(document.querySelector("#gfpgan_model"), ["gfpgan", "codeformer"], "", false) let useUpscalingField = document.querySelector("#use_upscale") let upscaleModelField = document.querySelector("#upscale_model") let upscaleAmountField = document.querySelector("#upscale_amount") -let stableDiffusionModelField = new ModelDropdown(document.querySelector('#stable_diffusion_model'), 'stable-diffusion') -let vaeModelField = new ModelDropdown(document.querySelector('#vae_model'), 'vae', 'None') -let hypernetworkModelField = new ModelDropdown(document.querySelector('#hypernetwork_model'), 'hypernetwork', 'None') -let hypernetworkStrengthSlider = document.querySelector('#hypernetwork_strength_slider') -let hypernetworkStrengthField = document.querySelector('#hypernetwork_strength') -let loraModelField = new ModelDropdown(document.querySelector('#lora_model'), 'lora', 'None') -let loraAlphaSlider = document.querySelector('#lora_alpha_slider') -let loraAlphaField = document.querySelector('#lora_alpha') -let outputFormatField = document.querySelector('#output_format') -let outputLosslessField = document.querySelector('#output_lossless') -let outputLosslessContainer = document.querySelector('#output_lossless_container') -let blockNSFWField = document.querySelector('#block_nsfw') +let latentUpscalerSettings = document.querySelector("#latent_upscaler_settings") +let latentUpscalerStepsSlider = document.querySelector("#latent_upscaler_steps_slider") +let latentUpscalerStepsField = document.querySelector("#latent_upscaler_steps") +let codeformerFidelitySlider = document.querySelector("#codeformer_fidelity_slider") +let codeformerFidelityField = document.querySelector("#codeformer_fidelity") +let stableDiffusionModelField = new ModelDropdown(document.querySelector("#stable_diffusion_model"), "stable-diffusion") +let clipSkipField = document.querySelector("#clip_skip") +let tilingField = document.querySelector("#tiling") +let vaeModelField = new ModelDropdown(document.querySelector("#vae_model"), "vae", "None") +let hypernetworkModelField = new ModelDropdown(document.querySelector("#hypernetwork_model"), "hypernetwork", "None") +let hypernetworkStrengthSlider = document.querySelector("#hypernetwork_strength_slider") +let hypernetworkStrengthField = document.querySelector("#hypernetwork_strength") +let loraModelField = new ModelDropdown(document.querySelector("#lora_model"), "lora", "None") +let loraAlphaSlider = document.querySelector("#lora_alpha_slider") +let loraAlphaField = document.querySelector("#lora_alpha") +let outputFormatField = document.querySelector("#output_format") +let outputLosslessField = document.querySelector("#output_lossless") +let outputLosslessContainer = document.querySelector("#output_lossless_container") +let blockNSFWField = document.querySelector("#block_nsfw") let showOnlyFilteredImageField = document.querySelector("#show_only_filtered_image") let updateBranchLabel = document.querySelector("#updateBranchLabel") let streamImageProgressField = document.querySelector("#stream_image_progress") @@ -60,18 +117,19 @@ let thumbnailSizeField = document.querySelector("#thumbnail_size-input") let autoscrollBtn = document.querySelector("#auto_scroll_btn") let autoScroll = document.querySelector("#auto_scroll") -let makeImageBtn = document.querySelector('#makeImage') -let stopImageBtn = document.querySelector('#stopImage') -let pauseBtn = document.querySelector('#pause') -let resumeBtn = document.querySelector('#resume') -let renderButtons = document.querySelector('#render-buttons') +let makeImageBtn = document.querySelector("#makeImage") +let stopImageBtn = document.querySelector("#stopImage") +let pauseBtn = document.querySelector("#pause") +let resumeBtn = document.querySelector("#resume") +let renderButtons = document.querySelector("#render-buttons") -let imagesContainer = document.querySelector('#current-images') -let initImagePreviewContainer = document.querySelector('#init_image_preview_container') -let initImageClearBtn = document.querySelector('.init_image_clear') -let promptStrengthContainer = document.querySelector('#prompt_strength_container') +let imagesContainer = document.querySelector("#current-images") +let initImagePreviewContainer = document.querySelector("#init_image_preview_container") +let initImageClearBtn = document.querySelector(".init_image_clear") +let promptStrengthContainer = document.querySelector("#prompt_strength_container") let initialText = document.querySelector("#initial-text") +let versionText = document.querySelector("#version") let previewTools = document.querySelector("#preview-tools") let clearAllPreviewsBtn = document.querySelector("#clear-all-previews") let showDownloadPopupBtn = document.querySelector("#show-download-popup") @@ -81,10 +139,11 @@ let saveAllZipToggle = document.querySelector("#zip_toggle") let saveAllTreeToggle = document.querySelector("#tree_toggle") let saveAllJSONToggle = document.querySelector("#json_toggle") let saveAllFoldersOption = document.querySelector("#download-add-folders") +let splashScreenPopup = document.querySelector("#splash-screen") -let maskSetting = document.querySelector('#enable_mask') +let maskSetting = document.querySelector("#enable_mask") -const processOrder = document.querySelector('#process_order_toggle') +const processOrder = document.querySelector("#process_order_toggle") let imagePreview = document.querySelector("#preview") let imagePreviewContent = document.querySelector("#preview-content") @@ -93,8 +152,8 @@ let undoButton = document.querySelector("#undo") let undoBuffer = [] const UNDO_LIMIT = 20 -imagePreview.addEventListener('drop', function(ev) { - const data = ev.dataTransfer?.getData("text/plain"); +imagePreview.addEventListener("drop", function(ev) { + const data = ev.dataTransfer?.getData("text/plain") if (!data) { return } @@ -104,7 +163,7 @@ imagePreview.addEventListener('drop', function(ev) { } ev.preventDefault() let moveTarget = ev.target - while (moveTarget && typeof moveTarget === 'object' && moveTarget.parentNode !== imagePreviewContent) { + while (moveTarget && typeof moveTarget === "object" && moveTarget.parentNode !== imagePreviewContent) { moveTarget = moveTarget.parentNode } if (moveTarget === initialText || moveTarget === previewTools) { @@ -134,16 +193,14 @@ imagePreview.addEventListener('drop', function(ev) { } }) - - -let showConfigToggle = document.querySelector('#configToggleBtn') +let showConfigToggle = document.querySelector("#configToggleBtn") // let configBox = document.querySelector('#config') // let outputMsg = document.querySelector('#outputMsg') -let soundToggle = document.querySelector('#sound_toggle') +let soundToggle = document.querySelector("#sound_toggle") -let serverStatusColor = document.querySelector('#server-status-color') -let serverStatusMsg = document.querySelector('#server-status-msg') +let serverStatusColor = document.querySelector("#server-status-color") +let serverStatusMsg = document.querySelector("#server-status-msg") function getLocalStorageBoolItem(key, fallback) { let item = localStorage.getItem(key) @@ -151,7 +208,7 @@ function getLocalStorageBoolItem(key, fallback) { return fallback } - return (item === 'true' ? true : false) + return item === "true" ? true : false } function handleBoolSettingChange(key) { @@ -174,29 +231,28 @@ function getSavedDiskPath() { return getSetting("diskPath") } -function setStatus(statusType, msg, msgType) { -} +function setStatus(statusType, msg, msgType) {} function setServerStatus(event) { - switch(event.type) { - case 'online': - serverStatusColor.style.color = 'var(--status-green)' - serverStatusMsg.style.color = 'var(--status-green)' - serverStatusMsg.innerText = 'Stable Diffusion is ' + event.message + switch (event.type) { + case "online": + serverStatusColor.style.color = "var(--status-green)" + serverStatusMsg.style.color = "var(--status-green)" + serverStatusMsg.innerText = "Stable Diffusion is " + event.message break - case 'busy': - serverStatusColor.style.color = 'var(--status-orange)' - serverStatusMsg.style.color = 'var(--status-orange)' - serverStatusMsg.innerText = 'Stable Diffusion is ' + event.message + case "busy": + serverStatusColor.style.color = "var(--status-orange)" + serverStatusMsg.style.color = "var(--status-orange)" + serverStatusMsg.innerText = "Stable Diffusion is " + event.message break - case 'error': - serverStatusColor.style.color = 'var(--status-red)' - serverStatusMsg.style.color = 'var(--status-red)' - serverStatusMsg.innerText = 'Stable Diffusion has stopped' + case "error": + serverStatusColor.style.color = "var(--status-red)" + serverStatusMsg.style.color = "var(--status-red)" + serverStatusMsg.innerText = "Stable Diffusion has stopped" break } if (SD.serverState.devices) { - setDeviceInfo(SD.serverState.devices) + document.dispatchEvent(new CustomEvent("system_info_update", { detail: SD.serverState.devices })) } } @@ -206,37 +262,33 @@ function setServerStatus(event) { // fn : function to be called if the user confirms the dialog or has the shift key pressed // // If the user had the shift key pressed while clicking, the function fn will be executed. -// If the setting "confirm_dangerous_actions" in the system settings is disabled, the function +// If the setting "confirm_dangerous_actions" in the system settings is disabled, the function // fn will be executed. // Otherwise, a confirmation dialog is shown. If the user confirms, the function fn will also // be executed. function shiftOrConfirm(e, prompt, fn) { e.stopPropagation() if (e.shiftKey || !confirmDangerousActionsField.checked) { - fn(e) + fn(e) } else { - $.confirm({ - theme: 'modern', - title: prompt, - useBootstrap: false, - animateFromElement: false, - content: 'Tip: To skip this dialog, use shift-click or disable the "Confirm dangerous actions" setting in the Settings tab.', - buttons: { - yes: () => { fn(e) }, - cancel: () => {} + confirm( + 'Tip: To skip this dialog, use shift-click or disable the "Confirm dangerous actions" setting in the Settings tab.', + prompt, + () => { + fn(e) } - }); + ) } } function logMsg(msg, level, outputMsg) { if (outputMsg.hasChildNodes()) { - outputMsg.appendChild(document.createElement('br')) + outputMsg.appendChild(document.createElement("br")) } - if (level === 'error') { - outputMsg.innerHTML += 'Error: ' + msg + '' - } else if (level === 'warn') { - outputMsg.innerHTML += 'Warning: ' + msg + '' + if (level === "error") { + outputMsg.innerHTML += 'Error: ' + msg + "" + } else if (level === "warn") { + outputMsg.innerHTML += 'Warning: ' + msg + "" } else { outputMsg.innerText += msg } @@ -244,35 +296,46 @@ function logMsg(msg, level, outputMsg) { } function logError(msg, res, outputMsg) { - logMsg(msg, 'error', outputMsg) + logMsg(msg, "error", outputMsg) - console.log('request error', res) - setStatus('request', 'error', 'error') + console.log("request error", res) + console.trace() + setStatus("request", "error", "error") } function playSound() { - const audio = new Audio('/media/ding.mp3') + const audio = new Audio("/media/ding.mp3") audio.volume = 0.2 var promise = audio.play() if (promise !== undefined) { - promise.then(_ => {}).catch(error => { - console.warn("browser blocked autoplay") - }) + promise + .then((_) => {}) + .catch((error) => { + console.warn("browser blocked autoplay") + }) } } -function undoableRemove(element, doubleUndo=false) { - let data = { 'element': element, 'parent': element.parentNode, 'prev': element.previousSibling, 'next': element.nextSibling, 'doubleUndo': doubleUndo } +function undoableRemove(element, doubleUndo = false) { + let data = { + element: element, + parent: element.parentNode, + prev: element.previousSibling, + next: element.nextSibling, + doubleUndo: doubleUndo, + } undoBuffer.push(data) if (undoBuffer.length > UNDO_LIMIT) { // Remove item from memory and also remove it from the data structures let item = undoBuffer.shift() htmlTaskMap.delete(item.element) - item.element.querySelectorAll('[data-imagecounter]').forEach( (img) => { delete imageRequest[img.dataset['imagecounter']] }) + item.element.querySelectorAll("[data-imagecounter]").forEach((img) => { + delete imageRequest[img.dataset["imagecounter"]] + }) } element.remove() if (undoBuffer.length != 0) { - undoButton.classList.remove('displayNone') + undoButton.classList.remove("displayNone") } } @@ -290,42 +353,44 @@ function undoRemove() { undoRemove() } if (undoBuffer.length == 0) { - undoButton.classList.add('displayNone') + undoButton.classList.add("displayNone") } updateInitialText() } -undoButton.addEventListener('click', () => { undoRemove() }) +undoButton.addEventListener("click", () => { + undoRemove() +}) -document.addEventListener('keydown', function(e) { - if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.target == document.body) { +document.addEventListener("keydown", function(e) { + if ((e.ctrlKey || e.metaKey) && e.key === "z" && e.target == document.body) { undoRemove() } }) function showImages(reqBody, res, outputContainer, livePreview) { - let imageItemElements = outputContainer.querySelectorAll('.imgItem') - if(typeof res != 'object') return + let imageItemElements = outputContainer.querySelectorAll(".imgItem") + if (typeof res != "object") return res.output.reverse() res.output.forEach((result, index) => { - const imageData = result?.data || result?.path + '?t=' + Date.now(), + const imageData = result?.data || result?.path + "?t=" + Date.now(), imageSeed = result?.seed, imagePrompt = reqBody.prompt, imageInferenceSteps = reqBody.num_inference_steps, imageGuidanceScale = reqBody.guidance_scale, imageWidth = reqBody.width, - imageHeight = reqBody.height; + imageHeight = reqBody.height - if (!imageData.includes('/')) { + if (!imageData.includes("/")) { // res contained no data for the image, stop execution - setStatus('request', 'invalid image', 'error') + setStatus("request", "invalid image", "error") return } - let imageItemElem = (index < imageItemElements.length ? imageItemElements[index] : null) - if(!imageItemElem) { - imageItemElem = document.createElement('div') - imageItemElem.className = 'imgItem' + let imageItemElem = index < imageItemElements.length ? imageItemElements[index] : null + if (!imageItemElem) { + imageItemElem = document.createElement("div") + imageItemElem.className = "imgItem" imageItemElem.innerHTML = `
@@ -339,104 +404,135 @@ function showImages(reqBody, res, outputContainer, livePreview) {
` outputContainer.appendChild(imageItemElem) - const imageRemoveBtn = imageItemElem.querySelector('.imgPreviewItemClearBtn') - let parentTaskContainer = imageRemoveBtn.closest('.imageTaskContainer') - imageRemoveBtn.addEventListener('click', (e) => { + const imageRemoveBtn = imageItemElem.querySelector(".imgPreviewItemClearBtn") + let parentTaskContainer = imageRemoveBtn.closest(".imageTaskContainer") + imageRemoveBtn.addEventListener("click", (e) => { undoableRemove(imageItemElem) - let allHidden = true; - let children = parentTaskContainer.querySelectorAll('.imgItem'); - for(let x = 0; x < children.length; x++) { - let child = children[x]; - if(child.style.display != "none") { - allHidden = false; + let allHidden = true + let children = parentTaskContainer.querySelectorAll(".imgItem") + for (let x = 0; x < children.length; x++) { + let child = children[x] + if (child.style.display != "none") { + allHidden = false } } - if(allHidden === true) { + if (allHidden === true) { const req = htmlTaskMap.get(parentTaskContainer) - if(!req.isProcessing || req.batchesDone == req.batchCount) { undoableRemove(parentTaskContainer, true) } + if (!req.isProcessing || req.batchesDone == req.batchCount) { + undoableRemove(parentTaskContainer, true) + } } }) } - const imageElem = imageItemElem.querySelector('img') + const imageElem = imageItemElem.querySelector("img") imageElem.src = imageData imageElem.width = parseInt(imageWidth) imageElem.height = parseInt(imageHeight) - imageElem.setAttribute('data-prompt', imagePrompt) - imageElem.setAttribute('data-steps', imageInferenceSteps) - imageElem.setAttribute('data-guidance', imageGuidanceScale) + imageElem.setAttribute("data-prompt", imagePrompt) + imageElem.setAttribute("data-steps", imageInferenceSteps) + imageElem.setAttribute("data-guidance", imageGuidanceScale) - imageElem.addEventListener('load', function() { - imageItemElem.querySelector('.img_bottom_label').innerText = `${this.naturalWidth} x ${this.naturalHeight}` + imageElem.addEventListener("load", function() { + imageItemElem.querySelector(".img_bottom_label").innerText = `${this.naturalWidth} x ${this.naturalHeight}` }) - const imageInfo = imageItemElem.querySelector('.imgItemInfo') - imageInfo.style.visibility = (livePreview ? 'hidden' : 'visible') + const imageInfo = imageItemElem.querySelector(".imgItemInfo") + imageInfo.style.visibility = livePreview ? "hidden" : "visible" - if ('seed' in result && !imageElem.hasAttribute('data-seed')) { - const imageExpandBtn = imageItemElem.querySelector('.imgExpandBtn') - imageExpandBtn.addEventListener('click', function() { - imageModal(imageElem.src) + if ("seed" in result && !imageElem.hasAttribute("data-seed")) { + const imageExpandBtn = imageItemElem.querySelector(".imgExpandBtn") + imageExpandBtn.addEventListener("click", function() { + function previousImage(img) { + const allImages = Array.from(outputContainer.parentNode.querySelectorAll(".imgItem img")) + const index = allImages.indexOf(img) + return allImages.slice(0, index).reverse()[0] + } + + function nextImage(img) { + const allImages = Array.from(outputContainer.parentNode.querySelectorAll(".imgItem img")) + const index = allImages.indexOf(img) + return allImages.slice(index + 1)[0] + } + + function imageModalParameter(img) { + const previousImg = previousImage(img) + const nextImg = nextImage(img) + + return { + src: img.src, + previous: previousImg ? () => imageModalParameter(previousImg) : undefined, + next: nextImg ? () => imageModalParameter(nextImg) : undefined, + } + } + + imageModal(imageModalParameter(imageElem)) }) const req = Object.assign({}, reqBody, { - seed: result?.seed || reqBody.seed + seed: result?.seed || reqBody.seed, }) - imageElem.setAttribute('data-seed', req.seed) - imageElem.setAttribute('data-imagecounter', ++imageCounter) + imageElem.setAttribute("data-seed", req.seed) + imageElem.setAttribute("data-imagecounter", ++imageCounter) imageRequest[imageCounter] = req - const imageSeedLabel = imageItemElem.querySelector('.imgSeedLabel') - imageSeedLabel.innerText = 'Seed: ' + req.seed + const imageSeedLabel = imageItemElem.querySelector(".imgSeedLabel") + imageSeedLabel.innerText = "Seed: " + req.seed let buttons = [ - { text: 'Use as Input', on_click: onUseAsInputClick }, + { text: "Use as Input", on_click: onUseAsInputClick }, [ - { html: ' Download Image', on_click: onDownloadImageClick, class: "download-img" }, - { html: ' JSON', on_click: onDownloadJSONClick, class: "download-json" } + { + html: ' Download Image', + on_click: onDownloadImageClick, + class: "download-img", + }, + { + html: ' JSON', + on_click: onDownloadJSONClick, + class: "download-json", + }, ], - { text: 'Make Similar Images', on_click: onMakeSimilarClick }, - { text: 'Draw another 25 steps', on_click: onContinueDrawingClick }, + { text: "Make Similar Images", on_click: onMakeSimilarClick }, + { text: "Draw another 25 steps", on_click: onContinueDrawingClick }, [ - { text: 'Upscale', on_click: onUpscaleClick, filter: (req, img) => !req.use_upscale }, - { text: 'Fix Faces', on_click: onFixFacesClick, filter: (req, img) => !req.use_face_correction } - ] + { text: "Upscale", on_click: onUpscaleClick, filter: (req, img) => !req.use_upscale }, + { text: "Fix Faces", on_click: onFixFacesClick, filter: (req, img) => !req.use_face_correction }, + ], ] // include the plugins - buttons = buttons.concat(PLUGINS['IMAGE_INFO_BUTTONS']) + buttons = buttons.concat(PLUGINS["IMAGE_INFO_BUTTONS"]) - const imgItemInfo = imageItemElem.querySelector('.imgItemInfo') - const img = imageItemElem.querySelector('img') + const imgItemInfo = imageItemElem.querySelector(".imgItemInfo") + const img = imageItemElem.querySelector("img") const createButton = function(btnInfo) { if (Array.isArray(btnInfo)) { - const wrapper = document.createElement('div'); - btnInfo - .map(createButton) - .forEach(buttonElement => wrapper.appendChild(buttonElement)) + const wrapper = document.createElement("div") + btnInfo.map(createButton).forEach((buttonElement) => wrapper.appendChild(buttonElement)) return wrapper } - const isLabel = btnInfo.type === 'label' + const isLabel = btnInfo.type === "label" - const newButton = document.createElement(isLabel ? 'span' : 'button') - newButton.classList.add('tasksBtns') + const newButton = document.createElement(isLabel ? "span" : "button") + newButton.classList.add("tasksBtns") if (btnInfo.html) { - const html = typeof btnInfo.html === 'function' ? btnInfo.html() : btnInfo.html + const html = typeof btnInfo.html === "function" ? btnInfo.html() : btnInfo.html if (html instanceof HTMLElement) { newButton.appendChild(html) } else { newButton.innerHTML = html } } else { - newButton.innerText = typeof btnInfo.text === 'function' ? btnInfo.text() : btnInfo.text + newButton.innerText = typeof btnInfo.text === "function" ? btnInfo.text() : btnInfo.text } if (btnInfo.on_click || !isLabel) { - newButton.addEventListener('click', function(event) { + newButton.addEventListener("click", function(event) { btnInfo.on_click(req, img, event) }) } - + if (btnInfo.class !== undefined) { if (Array.isArray(btnInfo.class)) { newButton.classList.add(...btnInfo.class) @@ -446,9 +542,9 @@ function showImages(reqBody, res, outputContainer, livePreview) { } return newButton } - buttons.forEach(btn => { + buttons.forEach((btn) => { if (Array.isArray(btn)) { - btn = btn.filter(btnInfo => !btnInfo.filter || btnInfo.filter(req, img) === true) + btn = btn.filter((btnInfo) => !btnInfo.filter || btnInfo.filter(req, img) === true) if (btn.length === 0) { return } @@ -459,7 +555,7 @@ function showImages(reqBody, res, outputContainer, livePreview) { try { imgItemInfo.appendChild(createButton(btn)) } catch (err) { - console.error('Error creating image info button from plugin: ', btn, err) + console.error("Error creating image info button from plugin: ", btn, err) } }) } @@ -476,22 +572,22 @@ function onUseAsInputClick(req, img) { } function getDownloadFilename(img, suffix) { - const imageSeed = img.getAttribute('data-seed') - const imagePrompt = img.getAttribute('data-prompt') - const imageInferenceSteps = img.getAttribute('data-steps') - const imageGuidanceScale = img.getAttribute('data-guidance') - + const imageSeed = img.getAttribute("data-seed") + const imagePrompt = img.getAttribute("data-prompt") + const imageInferenceSteps = img.getAttribute("data-steps") + const imageGuidanceScale = img.getAttribute("data-guidance") + return createFileName(imagePrompt, imageSeed, imageInferenceSteps, imageGuidanceScale, suffix) } function onDownloadJSONClick(req, img) { - const name = getDownloadFilename(img, 'json') - const blob = new Blob([JSON.stringify(req, null, 2)], { type: 'text/plain' }) + const name = getDownloadFilename(img, "json") + const blob = new Blob([JSON.stringify(req, null, 2)], { type: "text/plain" }) saveAs(blob, name) } function onDownloadImageClick(req, img) { - const name = getDownloadFilename(img, req['output_format']) + const name = getDownloadFilename(img, req["output_format"]) const blob = dataURItoBlob(img.src) saveAs(blob, name) } @@ -500,7 +596,7 @@ function modifyCurrentRequest(...reqDiff) { const newTaskRequest = getCurrentUserRequest() newTaskRequest.reqBody = Object.assign(newTaskRequest.reqBody, ...reqDiff, { - use_cpu: useCPUField.checked + use_cpu: useCPUField.checked, }) newTaskRequest.seed = newTaskRequest.reqBody.seed @@ -514,7 +610,7 @@ function onMakeSimilarClick(req, img) { guidance_scale: 7.5, prompt_strength: 0.7, init_image: img.src, - seed: Math.floor(Math.random() * 10000000) + seed: Math.floor(Math.random() * 10000000), }) newTaskRequest.numOutputsTotal = 5 @@ -526,19 +622,19 @@ function onMakeSimilarClick(req, img) { } function enqueueImageVariationTask(req, img, reqDiff) { - const imageSeed = img.getAttribute('data-seed') + const imageSeed = img.getAttribute("data-seed") const newRequestBody = { num_outputs: 1, // this can be user-configurable in the future - seed: imageSeed + seed: imageSeed, } // If the user is editing pictures, stop modifyCurrentRequest from importing // new values by setting the missing properties to undefined - if (!('init_image' in req) && !('init_image' in reqDiff)) { + if (!("init_image" in req) && !("init_image" in reqDiff)) { newRequestBody.init_image = undefined newRequestBody.mask = undefined - } else if (!('mask' in req) && !('mask' in reqDiff)) { + } else if (!("mask" in req) && !("mask" in reqDiff)) { newRequestBody.mask = undefined } @@ -551,29 +647,28 @@ function enqueueImageVariationTask(req, img, reqDiff) { function onUpscaleClick(req, img) { enqueueImageVariationTask(req, img, { - use_upscale: upscaleModelField.value + use_upscale: upscaleModelField.value, }) } function onFixFacesClick(req, img) { enqueueImageVariationTask(req, img, { - use_face_correction: gfpganModelField.value + use_face_correction: gfpganModelField.value, }) } function onContinueDrawingClick(req, img) { enqueueImageVariationTask(req, img, { - num_inference_steps: parseInt(req.num_inference_steps) + 25 + num_inference_steps: parseInt(req.num_inference_steps) + 25, }) } function getUncompletedTaskEntries() { - const taskEntries = Array.from( - document.querySelectorAll('#preview .imageTaskContainer .taskStatusLabel') - ).filter((taskLabel) => taskLabel.style.display !== 'none' - ).map(function(taskLabel) { + const taskEntries = Array.from(document.querySelectorAll("#preview .imageTaskContainer .taskStatusLabel")) + .filter((taskLabel) => taskLabel.style.display !== "none") + .map(function(taskLabel) { let imageTaskContainer = taskLabel.parentNode - while(!imageTaskContainer.classList.contains('imageTaskContainer') && imageTaskContainer.parentNode) { + while (!imageTaskContainer.classList.contains("imageTaskContainer") && imageTaskContainer.parentNode) { imageTaskContainer = imageTaskContainer.parentNode } return imageTaskContainer @@ -586,34 +681,39 @@ function getUncompletedTaskEntries() { function makeImage() { if (typeof performance == "object" && performance.mark) { - performance.mark('click-makeImage') + performance.mark("click-makeImage") } if (!SD.isServerAvailable()) { - alert('The server is not available.') + alert("The server is not available.") return } - if (!randomSeedField.checked && seedField.value == '') { + if (!randomSeedField.checked && seedField.value == "") { alert('The "Seed" field must not be empty.') return } - if (numInferenceStepsField.value == '') { + if (numInferenceStepsField.value == "") { alert('The "Inference Steps" field must not be empty.') return } - if (numOutputsTotalField.value == '' || numOutputsTotalField.value == 0) { + if (numOutputsTotalField.value == "" || numOutputsTotalField.value == 0) { numOutputsTotalField.value = 1 } - if (numOutputsParallelField.value == '' || numOutputsParallelField.value == 0) { + if (numOutputsParallelField.value == "" || numOutputsParallelField.value == 0) { numOutputsParallelField.value = 1 } - if (guidanceScaleField.value == '') { + if (guidanceScaleField.value == "") { guidanceScaleField.value = guidanceScaleSlider.value / 10 } + if (hypernetworkStrengthField.value == "") { + hypernetworkStrengthField.value = hypernetworkStrengthSlider.value / 100 + } const taskTemplate = getCurrentUserRequest() - const newTaskRequests = getPrompts().map((prompt) => Object.assign({}, taskTemplate, { - reqBody: Object.assign({ prompt: prompt }, taskTemplate.reqBody) - })) + const newTaskRequests = getPrompts().map((prompt) => + Object.assign({}, taskTemplate, { + reqBody: Object.assign({ prompt: prompt }, taskTemplate.reqBody), + }) + ) newTaskRequests.forEach(createTask) updateInitialText() @@ -621,7 +721,7 @@ function makeImage() { async function onIdle() { const serverCapacity = SD.serverCapacity - if (pauseClient===true) { + if (pauseClient === true) { await resumeClient() } @@ -631,8 +731,8 @@ async function onIdle() { } const task = htmlTaskMap.get(taskEntry) if (!task) { - const taskStatusLabel = taskEntry.querySelector('.taskStatusLabel') - taskStatusLabel.style.display = 'none' + const taskStatusLabel = taskEntry.querySelector(".taskStatusLabel") + taskStatusLabel.style.display = "none" continue } await onTaskStart(task) @@ -640,8 +740,8 @@ async function onIdle() { } function getTaskUpdater(task, reqBody, outputContainer) { - const outputMsg = task['outputMsg'] - const progressBar = task['progressBar'] + const outputMsg = task["outputMsg"] + const progressBar = task["progressBar"] const progressBarInner = progressBar.querySelector("div") const batchCount = task.batchCount @@ -649,60 +749,68 @@ function getTaskUpdater(task, reqBody, outputContainer) { return async function(event) { if (this.status !== lastStatus) { lastStatus = this.status - switch(this.status) { + switch (this.status) { case SD.TaskStatus.pending: - task['taskStatusLabel'].innerText = "Pending" - task['taskStatusLabel'].classList.add('waitingTaskLabel') + task["taskStatusLabel"].innerText = "Pending" + task["taskStatusLabel"].classList.add("waitingTaskLabel") break case SD.TaskStatus.waiting: - task['taskStatusLabel'].innerText = "Waiting" - task['taskStatusLabel'].classList.add('waitingTaskLabel') - task['taskStatusLabel'].classList.remove('activeTaskLabel') + task["taskStatusLabel"].innerText = "Waiting" + task["taskStatusLabel"].classList.add("waitingTaskLabel") + task["taskStatusLabel"].classList.remove("activeTaskLabel") break case SD.TaskStatus.processing: case SD.TaskStatus.completed: - task['taskStatusLabel'].innerText = "Processing" - task['taskStatusLabel'].classList.add('activeTaskLabel') - task['taskStatusLabel'].classList.remove('waitingTaskLabel') + task["taskStatusLabel"].innerText = "Processing" + task["taskStatusLabel"].classList.add("activeTaskLabel") + task["taskStatusLabel"].classList.remove("waitingTaskLabel") break case SD.TaskStatus.stopped: break case SD.TaskStatus.failed: if (!SD.isServerAvailable()) { - logError("Stable Diffusion is still starting up, please wait. If this goes on beyond a few minutes, Stable Diffusion has probably crashed. Please check the error message in the command-line window.", event, outputMsg) - } else if (typeof event?.response === 'object') { - let msg = 'Stable Diffusion had an error reading the response:
'
+                        logError(
+                            "Stable Diffusion is still starting up, please wait. If this goes on beyond a few minutes, Stable Diffusion has probably crashed. Please check the error message in the command-line window.",
+                            event,
+                            outputMsg
+                        )
+                    } else if (typeof event?.response === "object") {
+                        let msg = "Stable Diffusion had an error reading the response:
"
                         if (this.exception) {
                             msg += `Error: ${this.exception.message}
` } - try { // 'Response': body stream already read - msg += 'Read: ' + await event.response.text() - } catch(e) { - msg += 'Unexpected end of stream. ' + try { + // 'Response': body stream already read + msg += "Read: " + (await event.response.text()) + } catch (e) { + msg += "Unexpected end of stream. " } const bufferString = event.reader.bufferedString if (bufferString) { - msg += 'Buffered data: ' + bufferString + msg += "Buffered data: " + bufferString } - msg += '
' - logError(msg, event, outputMsg) - } else { - let msg = `Unexpected Read Error:
Error:${this.exception}
EventInfo: ${JSON.stringify(event, undefined, 4)}
` + msg += "
" logError(msg, event, outputMsg) } break } } - if ('update' in event) { + if ("update" in event) { const stepUpdate = event.update - if (!('step' in stepUpdate)) { + if (!("step" in stepUpdate)) { return } // task.instances can be a mix of different tasks with uneven number of steps (Render Vs Filter Tasks) - const overallStepCount = task.instances.reduce( - (sum, instance) => sum + (instance.isPending ? Math.max(0, instance.step || stepUpdate.step) / (instance.total_steps || stepUpdate.total_steps) : 1), - 0 // Initial value - ) * stepUpdate.total_steps // Scale to current number of steps. + const overallStepCount = + task.instances.reduce( + (sum, instance) => + sum + + (instance.isPending + ? Math.max(0, instance.step || stepUpdate.step) / + (instance.total_steps || stepUpdate.total_steps) + : 1), + 0 // Initial value + ) * stepUpdate.total_steps // Scale to current number of steps. const totalSteps = task.instances.reduce( (sum, instance) => sum + (instance.total_steps || stepUpdate.total_steps), stepUpdate.total_steps * (batchCount - task.batchesDone) // Initial value at (unstarted task count * Nbr of steps) @@ -711,9 +819,9 @@ function getTaskUpdater(task, reqBody, outputContainer) { const timeTaken = stepUpdate.step_time // sec const stepsRemaining = Math.max(0, totalSteps - overallStepCount) - const timeRemaining = (timeTaken < 0 ? '' : millisecondsToStr(stepsRemaining * timeTaken * 1000)) + const timeRemaining = timeTaken < 0 ? "" : millisecondsToStr(stepsRemaining * timeTaken * 1000) outputMsg.innerHTML = `Batch ${task.batchesDone} of ${batchCount}. Generating image(s): ${percent}%. Time remaining (approx): ${timeRemaining}` - outputMsg.style.display = 'block' + outputMsg.style.display = "block" progressBarInner.style.width = `${percent}%` if (stepUpdate.output) { @@ -729,8 +837,8 @@ function abortTask(task) { } task.isProcessing = false task.progressBar.classList.remove("active") - task['taskStatusLabel'].style.display = 'none' - task['stopTask'].innerHTML = ' Remove' + task["taskStatusLabel"].style.display = "none" + task["stopTask"].innerHTML = ' Remove' if (!task.instances?.some((r) => r.isPending)) { return } @@ -747,30 +855,49 @@ function onTaskErrorHandler(task, reqBody, instance, reason) { if (!task.isProcessing) { return } - console.log('Render request %o, Instance: %o, Error: %s', reqBody, instance, reason) + console.log("Render request %o, Instance: %o, Error: %s", reqBody, instance, reason) abortTask(task) - const outputMsg = task['outputMsg'] - logError('Stable Diffusion had an error. Please check the logs in the command-line window.

' + reason + '
' + reason.stack + '
', task, outputMsg) - setStatus('request', 'error', 'error') + const outputMsg = task["outputMsg"] + logError( + "Stable Diffusion had an error. Please check the logs in the command-line window.

" + + reason + + "
" +
+            reason.stack +
+            "
", + task, + outputMsg + ) + setStatus("request", "error", "error") } function onTaskCompleted(task, reqBody, instance, outputContainer, stepUpdate) { - if (typeof stepUpdate === 'object') { - if (stepUpdate.status === 'succeeded') { + if (typeof stepUpdate === "object") { + if (stepUpdate.status === "succeeded") { showImages(reqBody, stepUpdate, outputContainer, false) } else { task.isProcessing = false - const outputMsg = task['outputMsg'] - let msg = '' - if ('detail' in stepUpdate && typeof stepUpdate.detail === 'string' && stepUpdate.detail.length > 0) { + const outputMsg = task["outputMsg"] + let msg = "" + if ("detail" in stepUpdate && typeof stepUpdate.detail === "string" && stepUpdate.detail.length > 0) { msg = stepUpdate.detail - if (msg.toLowerCase().includes('out of memory')) { + if (msg.toLowerCase().includes("out of memory")) { msg += `

Suggestions:
1. If you have set an initial image, please try reducing its dimension to ${MAX_INIT_IMAGE_DIMENSION}x${MAX_INIT_IMAGE_DIMENSION} or smaller.
2. Try picking a lower level in the 'GPU Memory Usage' setting (in the 'Settings' tab).
3. Try generating a smaller image.
` + } else if (msg.includes("DefaultCPUAllocator: not enough memory")) { + msg += `

+ Reason: Your computer is running out of system RAM! +

+ Suggestions: +
+ 1. Try closing unnecessary programs and browser tabs.
+ 2. If that doesn't help, please increase your computer's virtual memory by following these steps for + Windows or + Linux.
+ 3. Try restarting your computer.
` } } else { msg = `Unexpected Read Error:
StepUpdate: ${JSON.stringify(stepUpdate, undefined, 4)}
` @@ -779,29 +906,29 @@ function onTaskCompleted(task, reqBody, instance, outputContainer, stepUpdate) { } } if (task.isProcessing && task.batchesDone < task.batchCount) { - task['taskStatusLabel'].innerText = "Pending" - task['taskStatusLabel'].classList.add('waitingTaskLabel') - task['taskStatusLabel'].classList.remove('activeTaskLabel') + task["taskStatusLabel"].innerText = "Pending" + task["taskStatusLabel"].classList.add("waitingTaskLabel") + task["taskStatusLabel"].classList.remove("activeTaskLabel") return } - if ('instances' in task && task.instances.some((ins) => ins != instance && ins.isPending)) { + if ("instances" in task && task.instances.some((ins) => ins != instance && ins.isPending)) { return } task.isProcessing = false - task['stopTask'].innerHTML = ' Remove' - task['taskStatusLabel'].style.display = 'none' + task["stopTask"].innerHTML = ' Remove' + task["taskStatusLabel"].style.display = "none" - let time = millisecondsToStr( Date.now() - task.startTime ) + let time = millisecondsToStr(Date.now() - task.startTime) if (task.batchesDone == task.batchCount) { - if (!task.outputMsg.innerText.toLowerCase().includes('error')) { + if (!task.outputMsg.innerText.toLowerCase().includes("error")) { task.outputMsg.innerText = `Processed ${task.numOutputsTotal} images in ${time}` } task.progressBar.style.height = "0px" task.progressBar.style.border = "0px solid var(--background-color3)" task.progressBar.classList.remove("active") - setStatus('request', 'done', 'success') + setStatus("request", "done", "success") } else { task.outputMsg.innerText += `. Task ended after ${time}` } @@ -818,10 +945,10 @@ function onTaskCompleted(task, reqBody, instance, outputContainer, stepUpdate) { return } - if (pauseClient) { - resumeBtn.click() + if (pauseClient) { + resumeBtn.click() } - renderButtons.style.display = 'none' + renderButtons.style.display = "none" renameMakeImageButton() if (isSoundEnabled()) { @@ -829,39 +956,40 @@ function onTaskCompleted(task, reqBody, instance, outputContainer, stepUpdate) { } } - async function onTaskStart(task) { if (!task.isProcessing || task.batchesDone >= task.batchCount) { return } - if (typeof task.startTime !== 'number') { + if (typeof task.startTime !== "number") { task.startTime = Date.now() } - if (!('instances' in task)) { - task['instances'] = [] + if (!("instances" in task)) { + task["instances"] = [] } - task['stopTask'].innerHTML = ' Stop' - task['taskStatusLabel'].innerText = "Starting" - task['taskStatusLabel'].classList.add('waitingTaskLabel') + task["stopTask"].innerHTML = ' Stop' + task["taskStatusLabel"].innerText = "Starting" + task["taskStatusLabel"].classList.add("waitingTaskLabel") let newTaskReqBody = task.reqBody if (task.batchCount > 1) { // Each output render batch needs it's own task reqBody instance to avoid altering the other runs after they are completed. newTaskReqBody = Object.assign({}, task.reqBody) - if (task.batchesDone == task.batchCount-1) { + if (task.batchesDone == task.batchCount - 1) { // Last batch of the task // If the number of parallel jobs is no factor of the total number of images, the last batch must create less than "parallel jobs count" images // E.g. with numOutputsTotal = 6 and num_outputs = 5, the last batch shall only generate 1 image. - newTaskReqBody.num_outputs = task.numOutputsTotal - task.reqBody.num_outputs * (task.batchCount-1) + newTaskReqBody.num_outputs = task.numOutputsTotal - task.reqBody.num_outputs * (task.batchCount - 1) } } const startSeed = task.seed || newTaskReqBody.seed - const genSeeds = Boolean(typeof newTaskReqBody.seed !== 'number' || (newTaskReqBody.seed === task.seed && task.numOutputsTotal > 1)) + const genSeeds = Boolean( + typeof newTaskReqBody.seed !== "number" || (newTaskReqBody.seed === task.seed && task.numOutputsTotal > 1) + ) if (genSeeds) { - newTaskReqBody.seed = parseInt(startSeed) + (task.batchesDone * task.reqBody.num_outputs) + newTaskReqBody.seed = parseInt(startSeed) + task.batchesDone * task.reqBody.num_outputs } // Update the seed *before* starting the processing so it's retained if user stops the task @@ -869,15 +997,15 @@ async function onTaskStart(task) { seedField.value = task.seed } - const outputContainer = document.createElement('div') - outputContainer.className = 'img-batch' + const outputContainer = document.createElement("div") + outputContainer.className = "img-batch" task.outputContainer.insertBefore(outputContainer, task.outputContainer.firstChild) - const eventInfo = {reqBody:newTaskReqBody} - const callbacksPromises = PLUGINS['TASK_CREATE'].map((hook) => { - if (typeof hook !== 'function') { - console.error('The provided TASK_CREATE hook is not a function. Hook: %o', hook) - return Promise.reject(new Error('hook is not a function.')) + const eventInfo = { reqBody: newTaskReqBody } + const callbacksPromises = PLUGINS["TASK_CREATE"].map((hook) => { + if (typeof hook !== "function") { + console.error("The provided TASK_CREATE hook is not a function. Hook: %o", hook) + return Promise.reject(new Error("hook is not a function.")) } try { return Promise.resolve(hook.call(task, eventInfo)) @@ -894,12 +1022,16 @@ async function onTaskStart(task) { instance = await Promise.resolve(factory(eventInfo.reqBody || newTaskReqBody)) } if (!instance) { - console.error(`${factory ? "Factory " + String(factory) : 'No factory defined'} for output format ${eventInfo.reqBody?.output_format || newTaskReqBody.output_format}. Instance is ${instance || 'undefined'}. Using default renderer.`) + console.error( + `${factory ? "Factory " + String(factory) : "No factory defined"} for output format ${eventInfo.reqBody + ?.output_format || newTaskReqBody.output_format}. Instance is ${instance || + "undefined"}. Using default renderer.` + ) instance = new SD.RenderTask(eventInfo.reqBody || newTaskReqBody) } } - task['instances'].push(instance) + task["instances"].push(instance) task.batchesDone++ instance.enqueue(getTaskUpdater(task, newTaskReqBody, outputContainer)).then( @@ -911,86 +1043,84 @@ async function onTaskStart(task) { } ) - setStatus('request', 'fetching..') - renderButtons.style.display = 'flex' + setStatus("request", "fetching..") + renderButtons.style.display = "flex" renameMakeImageButton() updateInitialText() } /* Hover effect for the init image in the task list */ function createInitImageHover(taskEntry) { - var $tooltip = $( taskEntry.querySelector('.task-fs-initimage') ) - var img = document.createElement('img') - img.src = taskEntry.querySelector('div.task-initimg > img').src + var $tooltip = $(taskEntry.querySelector(".task-fs-initimage")) + var img = document.createElement("img") + img.src = taskEntry.querySelector("div.task-initimg > img").src $tooltip.append(img) $tooltip.append(`
`) - $tooltip.find('button').on('click', (e) => { + $tooltip.find("button").on("click", (e) => { e.stopPropagation() - onUseAsInputClick(null,img) + onUseAsInputClick(null, img) }) } -let startX, startY; +let startX, startY function onTaskEntryDragOver(event) { - imagePreview.querySelectorAll(".imageTaskContainer").forEach(itc => { - if(itc != event.target.closest(".imageTaskContainer")){ - itc.classList.remove('dropTargetBefore','dropTargetAfter'); + imagePreview.querySelectorAll(".imageTaskContainer").forEach((itc) => { + if (itc != event.target.closest(".imageTaskContainer")) { + itc.classList.remove("dropTargetBefore", "dropTargetAfter") } - }); - if(event.target.closest(".imageTaskContainer")){ - if(startX && startY){ - if(event.target.closest(".imageTaskContainer").offsetTop > startY){ - event.target.closest(".imageTaskContainer").classList.add('dropTargetAfter'); - }else if(event.target.closest(".imageTaskContainer").offsetTop < startY){ - event.target.closest(".imageTaskContainer").classList.add('dropTargetBefore'); - }else if (event.target.closest(".imageTaskContainer").offsetLeft > startX){ - event.target.closest(".imageTaskContainer").classList.add('dropTargetAfter'); - }else if (event.target.closest(".imageTaskContainer").offsetLeft < startX){ - event.target.closest(".imageTaskContainer").classList.add('dropTargetBefore'); + }) + if (event.target.closest(".imageTaskContainer")) { + if (startX && startY) { + if (event.target.closest(".imageTaskContainer").offsetTop > startY) { + event.target.closest(".imageTaskContainer").classList.add("dropTargetAfter") + } else if (event.target.closest(".imageTaskContainer").offsetTop < startY) { + event.target.closest(".imageTaskContainer").classList.add("dropTargetBefore") + } else if (event.target.closest(".imageTaskContainer").offsetLeft > startX) { + event.target.closest(".imageTaskContainer").classList.add("dropTargetAfter") + } else if (event.target.closest(".imageTaskContainer").offsetLeft < startX) { + event.target.closest(".imageTaskContainer").classList.add("dropTargetBefore") } } } } +function generateConfig({ label, value, visible, cssKey }) { + if (!visible) return null + return `
${label}: ${value}` +} + +function getVisibleConfig(config, task) { + const mergedTaskConfig = { ...config.taskConfig, ...config.pluginTaskConfig } + return Object.keys(mergedTaskConfig) + .map((key) => { + const value = mergedTaskConfig?.[key]?.value?.(task) ?? task.reqBody[key] + const visible = mergedTaskConfig?.[key]?.visible?.(task) ?? value !== undefined ?? true + const label = mergedTaskConfig?.[key]?.label ?? mergedTaskConfig?.[key] + const cssKey = config.getCSSKey(key) + return { label, visible, value, cssKey } + }) + .map((obj) => generateConfig(obj)) + .filter((obj) => obj) +} + +function createTaskConfig(task) { + return getVisibleConfig(taskConfigSetup, task).join("
") +} + function createTask(task) { - let taskConfig = '' + let taskConfig = "" if (task.reqBody.init_image !== undefined) { let h = 80 - let w = task.reqBody.width * h / task.reqBody.height >>0 + let w = ((task.reqBody.width * h) / task.reqBody.height) >> 0 taskConfig += `
` } - taskConfig += `Seed: ${task.seed}, Sampler: ${task.reqBody.sampler_name}, Inference Steps: ${task.reqBody.num_inference_steps}, Guidance Scale: ${task.reqBody.guidance_scale}, Model: ${task.reqBody.use_stable_diffusion_model}` - if (task.reqBody.use_vae_model.trim() !== '') { - taskConfig += `, VAE: ${task.reqBody.use_vae_model}` - } - if (task.reqBody.negative_prompt.trim() !== '') { - taskConfig += `, Negative Prompt: ${task.reqBody.negative_prompt}` - } - if (task.reqBody.init_image !== undefined) { - taskConfig += `, Prompt Strength: ${task.reqBody.prompt_strength}` - } - if (task.reqBody.use_face_correction) { - taskConfig += `, Fix Faces: ${task.reqBody.use_face_correction}` - } - if (task.reqBody.use_upscale) { - taskConfig += `, Upscale: ${task.reqBody.use_upscale} (${task.reqBody.upscale_amount || 4}x)` - } - if (task.reqBody.use_hypernetwork_model) { - taskConfig += `, Hypernetwork: ${task.reqBody.use_hypernetwork_model}` - taskConfig += `, Hypernetwork Strength: ${task.reqBody.hypernetwork_strength}` - } - if (task.reqBody.use_lora_model) { - taskConfig += `, LoRA: ${task.reqBody.use_lora_model}` - } - if (task.reqBody.preserve_init_image_color_profile) { - taskConfig += `, Preserve Color Profile: true` - } + taskConfig += `
${createTaskConfig(task)}
` - let taskEntry = document.createElement('div') + let taskEntry = document.createElement("div") taskEntry.id = `imageTaskContainer-${Date.now()}` - taskEntry.className = 'imageTaskContainer' + taskEntry.className = "imageTaskContainer" taskEntry.innerHTML = `
Enqueued
@@ -1007,46 +1137,49 @@ function createTask(task) { createCollapsibles(taskEntry) - let draghandle = taskEntry.querySelector('.drag-handle') - draghandle.addEventListener('mousedown', (e) => { - taskEntry.setAttribute('draggable', true) + let draghandle = taskEntry.querySelector(".drag-handle") + draghandle.addEventListener("mousedown", (e) => { + taskEntry.setAttribute("draggable", true) }) // Add a debounce delay to allow mobile to bouble tap. - draghandle.addEventListener('mouseup', debounce((e) => { - taskEntry.setAttribute('draggable', false) - }, 2000)) - draghandle.addEventListener('click', (e) => { + draghandle.addEventListener( + "mouseup", + debounce((e) => { + taskEntry.setAttribute("draggable", false) + }, 2000) + ) + draghandle.addEventListener("click", (e) => { e.preventDefault() // Don't allow the results to be collapsed... }) - taskEntry.addEventListener('dragend', (e) => { - taskEntry.setAttribute('draggable', false); - imagePreview.querySelectorAll(".imageTaskContainer").forEach(itc => { - itc.classList.remove('dropTargetBefore','dropTargetAfter'); - }); - imagePreview.removeEventListener("dragover", onTaskEntryDragOver ); + taskEntry.addEventListener("dragend", (e) => { + taskEntry.setAttribute("draggable", false) + imagePreview.querySelectorAll(".imageTaskContainer").forEach((itc) => { + itc.classList.remove("dropTargetBefore", "dropTargetAfter") + }) + imagePreview.removeEventListener("dragover", onTaskEntryDragOver) }) - taskEntry.addEventListener('dragstart', function(e) { - imagePreview.addEventListener("dragover", onTaskEntryDragOver ); - e.dataTransfer.setData("text/plain", taskEntry.id); - startX = e.target.closest(".imageTaskContainer").offsetLeft; - startY = e.target.closest(".imageTaskContainer").offsetTop; + taskEntry.addEventListener("dragstart", function(e) { + imagePreview.addEventListener("dragover", onTaskEntryDragOver) + e.dataTransfer.setData("text/plain", taskEntry.id) + startX = e.target.closest(".imageTaskContainer").offsetLeft + startY = e.target.closest(".imageTaskContainer").offsetTop }) if (task.reqBody.init_image !== undefined) { createInitImageHover(taskEntry) } - task['taskStatusLabel'] = taskEntry.querySelector('.taskStatusLabel') - task['outputContainer'] = taskEntry.querySelector('.img-preview') - task['outputMsg'] = taskEntry.querySelector('.outputMsg') - task['previewPrompt'] = taskEntry.querySelector('.preview-prompt') - task['progressBar'] = taskEntry.querySelector('.progress-bar') - task['stopTask'] = taskEntry.querySelector('.stopTask') + task["taskStatusLabel"] = taskEntry.querySelector(".taskStatusLabel") + task["outputContainer"] = taskEntry.querySelector(".img-preview") + task["outputMsg"] = taskEntry.querySelector(".outputMsg") + task["previewPrompt"] = taskEntry.querySelector(".preview-prompt") + task["progressBar"] = taskEntry.querySelector(".progress-bar") + task["stopTask"] = taskEntry.querySelector(".stopTask") - task['stopTask'].addEventListener('click', (e) => { + task["stopTask"].addEventListener("click", (e) => { e.stopPropagation() - if (task['isProcessing']) { + if (task["isProcessing"]) { shiftOrConfirm(e, "Stop this task?", async function(e) { if (task.batchesDone <= 0 || !task.isProcessing) { removeTask(taskEntry) @@ -1058,8 +1191,8 @@ function createTask(task) { } }) - task['useSettings'] = taskEntry.querySelector('.useSettings') - task['useSettings'].addEventListener('click', function(e) { + task["useSettings"] = taskEntry.querySelector(".useSettings") + task["useSettings"].addEventListener("click", function(e) { e.stopPropagation() restoreTaskToUI(task, TASK_REQ_NO_EXPORT) }) @@ -1069,8 +1202,8 @@ function createTask(task) { htmlTaskMap.set(taskEntry, task) task.previewPrompt.innerText = task.reqBody.prompt - if (task.previewPrompt.innerText.trim() === '') { - task.previewPrompt.innerHTML = ' ' // allows the results to be collapsed + if (task.previewPrompt.innerText.trim() === "") { + task.previewPrompt.innerHTML = " " // allows the results to be collapsed } return taskEntry.id } @@ -1078,14 +1211,13 @@ function createTask(task) { function getCurrentUserRequest() { const numOutputsTotal = parseInt(numOutputsTotalField.value) const numOutputsParallel = parseInt(numOutputsParallelField.value) - const seed = (randomSeedField.checked ? Math.floor(Math.random() * 10000000) : parseInt(seedField.value)) + const seed = randomSeedField.checked ? Math.floor(Math.random() * (2 ** 32 - 1)) : parseInt(seedField.value) const newTask = { batchesDone: 0, numOutputsTotal: numOutputsTotal, batchCount: Math.ceil(numOutputsTotal / numOutputsParallel), seed, - reqBody: { seed, used_random_seed: randomSeedField.checked, @@ -1100,9 +1232,11 @@ function getCurrentUserRequest() { sampler_name: samplerField.value, //render_device: undefined, // Set device affinity. Prefer this device, but wont activate. use_stable_diffusion_model: stableDiffusionModelField.value, + clip_skip: clipSkipField.checked, + tiling: tilingField.value, use_vae_model: vaeModelField.value, stream_progress_updates: true, - stream_image_progress: (numOutputsTotal > 50 ? false : streamImageProgressField.checked), + stream_image_progress: numOutputsTotal > 50 ? false : streamImageProgressField.checked, show_only_filtered_image: showOnlyFilteredImageField.checked, block_nsfw: blockNSFWField.checked, output_format: outputFormatField.value, @@ -1110,14 +1244,13 @@ function getCurrentUserRequest() { output_lossless: outputLosslessField.checked, metadata_output_format: metadataOutputFormatField.value, original_prompt: promptField.value, - active_tags: (activeTags.map(x => x.name)), - inactive_tags: (activeTags.filter(tag => tag.inactive === true).map(x => x.name)) - } + active_tags: activeTags.map((x) => x.name), + inactive_tags: activeTags.filter((tag) => tag.inactive === true).map((x) => x.name), + }, } if (IMAGE_REGEX.test(initImagePreview.src)) { newTask.reqBody.init_image = initImagePreview.src newTask.reqBody.prompt_strength = parseFloat(promptStrengthField.value) - // if (IMAGE_REGEX.test(maskImagePreview.src)) { // newTask.reqBody.mask = maskImagePreview.src // } @@ -1126,54 +1259,62 @@ function getCurrentUserRequest() { } newTask.reqBody.preserve_init_image_color_profile = applyColorCorrectionField.checked if (!testDiffusers.checked) { - newTask.reqBody.sampler_name = 'ddim' + newTask.reqBody.sampler_name = "ddim" } } - if (saveToDiskField.checked && diskPathField.value.trim() !== '') { + if (saveToDiskField.checked && diskPathField.value.trim() !== "") { newTask.reqBody.save_to_disk_path = diskPathField.value.trim() } if (useFaceCorrectionField.checked) { newTask.reqBody.use_face_correction = gfpganModelField.value + + if (gfpganModelField.value.includes("codeformer")) { + newTask.reqBody.codeformer_upscale_faces = document.querySelector("#codeformer_upscale_faces").checked + newTask.reqBody.codeformer_fidelity = 1 - parseFloat(codeformerFidelityField.value) + } } if (useUpscalingField.checked) { newTask.reqBody.use_upscale = upscaleModelField.value newTask.reqBody.upscale_amount = upscaleAmountField.value + if (upscaleModelField.value === "latent_upscaler") { + newTask.reqBody.upscale_amount = "2" + newTask.reqBody.latent_upscaler_steps = latentUpscalerStepsField.value + } } if (hypernetworkModelField.value) { newTask.reqBody.use_hypernetwork_model = hypernetworkModelField.value newTask.reqBody.hypernetwork_strength = parseFloat(hypernetworkStrengthField.value) } - if (testDiffusers.checked) { + if (testDiffusers.checked && loraModelField.value) { newTask.reqBody.use_lora_model = loraModelField.value + newTask.reqBody.lora_alpha = parseFloat(loraAlphaField.value) } return newTask } function getPrompts(prompts) { - if (typeof prompts === 'undefined') { + if (typeof prompts === "undefined") { prompts = promptField.value } - if (prompts.trim() === '' && activeTags.length === 0) { - return [''] + if (prompts.trim() === "" && activeTags.length === 0) { + return [""] } let promptsToMake = [] - if (prompts.trim() !== '') { - prompts = prompts.split('\n') - prompts = prompts.map(prompt => prompt.trim()) - prompts = prompts.filter(prompt => prompt !== '') - + if (prompts.trim() !== "") { + prompts = prompts.split("\n") + prompts = prompts.map((prompt) => prompt.trim()) + prompts = prompts.filter((prompt) => prompt !== "") + promptsToMake = applyPermuteOperator(prompts) promptsToMake = applySetOperator(promptsToMake) } - const newTags = activeTags.filter(tag => tag.inactive === undefined || tag.inactive === false) + const newTags = activeTags.filter((tag) => tag.inactive === undefined || tag.inactive === false) if (newTags.length > 0) { - const promptTags = newTags.map(x => x.name).join(", ") + const promptTags = newTags.map((x) => x.name).join(", ") if (promptsToMake.length > 0) { promptsToMake = promptsToMake.map((prompt) => `${prompt}, ${promptTags}`) - } - else - { + } else { promptsToMake.push(promptTags) } } @@ -1181,15 +1322,64 @@ function getPrompts(prompts) { promptsToMake = applyPermuteOperator(promptsToMake) promptsToMake = applySetOperator(promptsToMake) - PLUGINS['GET_PROMPTS_HOOK'].forEach(fn => { promptsToMake = fn(promptsToMake) }) + PLUGINS["GET_PROMPTS_HOOK"].forEach((fn) => { + promptsToMake = fn(promptsToMake) + }) return promptsToMake } +function getPromptsNumber(prompts) { + if (typeof prompts === "undefined") { + prompts = promptField.value + } + if (prompts.trim() === "" && activeTags.length === 0) { + return [""] + } + + let promptsToMake = [] + let numberOfPrompts = 0 + if (prompts.trim() !== "") { // this needs to stay sort of the same, as the prompts have to be passed through to the other functions + prompts = prompts.split("\n") + prompts = prompts.map((prompt) => prompt.trim()) + prompts = prompts.filter((prompt) => prompt !== "") + + // estimate number of prompts + let estimatedNumberOfPrompts = 0 + prompts.forEach((prompt) => { + estimatedNumberOfPrompts += (prompt.match(/{[^}]*}/g) || []).map((e) => e.match(/,/g).length + 1).reduce( (p,a) => p*a, 1) * (2**(prompt.match(/\|/g) || []).length) + }) + + if (estimatedNumberOfPrompts >= 10000) { + return 10000 + } + + promptsToMake = applySetOperator(prompts) // switched those around as Set grows in a linear fashion and permute in 2^n, and one has to be computed for the other to be calculated + numberOfPrompts = applyPermuteOperatorNumber(promptsToMake) + } + const newTags = activeTags.filter((tag) => tag.inactive === undefined || tag.inactive === false) + if (newTags.length > 0) { + const promptTags = newTags.map((x) => x.name).join(", ") + if (numberOfPrompts > 0) { + // promptsToMake = promptsToMake.map((prompt) => `${prompt}, ${promptTags}`) + // nothing changes, as all prompts just get modified + } else { + // promptsToMake.push(promptTags) + numberOfPrompts = 1 + } + } + + // Why is this applied twice? It does not do anything here, as everything should have already been done earlier + // promptsToMake = applyPermuteOperator(promptsToMake) + // promptsToMake = applySetOperator(promptsToMake) + + return numberOfPrompts +} + function applySetOperator(prompts) { let promptsToMake = [] let braceExpander = new BraceExpander() - prompts.forEach(prompt => { + prompts.forEach((prompt) => { let expandedPrompts = braceExpander.expand(prompt) promptsToMake = promptsToMake.concat(expandedPrompts) }) @@ -1197,15 +1387,15 @@ function applySetOperator(prompts) { return promptsToMake } -function applyPermuteOperator(prompts) { +function applyPermuteOperator(prompts) { // prompts is array of input, trimmed, filtered and split by \n let promptsToMake = [] - prompts.forEach(prompt => { - let promptMatrix = prompt.split('|') + prompts.forEach((prompt) => { + let promptMatrix = prompt.split("|") prompt = promptMatrix.shift().trim() promptsToMake.push(prompt) - promptMatrix = promptMatrix.map(p => p.trim()) - promptMatrix = promptMatrix.filter(p => p !== '') + promptMatrix = promptMatrix.map((p) => p.trim()) + promptMatrix = promptMatrix.filter((p) => p !== "") if (promptMatrix.length > 0) { let promptPermutations = permutePrompts(prompt, promptMatrix) @@ -1216,19 +1406,39 @@ function applyPermuteOperator(prompts) { return promptsToMake } +// returns how many prompts would have to be made with the given prompts +function applyPermuteOperatorNumber(prompts) { // prompts is array of input, trimmed, filtered and split by \n + let numberOfPrompts = 0 + prompts.forEach((prompt) => { + let promptCounter = 1 + let promptMatrix = prompt.split("|") + promptMatrix.shift() + + promptMatrix = promptMatrix.map((p) => p.trim()) + promptMatrix = promptMatrix.filter((p) => p !== "") + + if (promptMatrix.length > 0) { + promptCounter *= permuteNumber(promptMatrix) + } + numberOfPrompts += promptCounter + }) + + return numberOfPrompts +} + function permutePrompts(promptBase, promptMatrix) { let prompts = [] let permutations = permute(promptMatrix) - permutations.forEach(perm => { + permutations.forEach((perm) => { let prompt = promptBase if (perm.length > 0) { - let promptAddition = perm.join(', ') - if (promptAddition.trim() === '') { + let promptAddition = perm.join(", ") + if (promptAddition.trim() === "") { return } - prompt += ', ' + promptAddition + prompt += ", " + promptAddition } prompts.push(prompt) @@ -1240,9 +1450,8 @@ function permutePrompts(promptBase, promptMatrix) { // create a file name with embedded prompt and metadata // for easier cateloging and comparison function createFileName(prompt, seed, steps, guidance, outputFormat) { - // Most important information is the prompt - let underscoreName = prompt.replace(/[^a-zA-Z0-9]/g, '_') + let underscoreName = prompt.replace(/[^a-zA-Z0-9]/g, "_") underscoreName = underscoreName.substring(0, 70) // name and the top level metadata @@ -1253,9 +1462,9 @@ function createFileName(prompt, seed, steps, guidance, outputFormat) { async function stopAllTasks() { getUncompletedTaskEntries().forEach((taskEntry) => { - const taskStatusLabel = taskEntry.querySelector('.taskStatusLabel') + const taskStatusLabel = taskEntry.querySelector(".taskStatusLabel") if (taskStatusLabel) { - taskStatusLabel.style.display = 'none' + taskStatusLabel.style.display = "none" } const task = htmlTaskMap.get(taskEntry) if (!task) { @@ -1266,14 +1475,16 @@ async function stopAllTasks() { } function updateInitialText() { - if (document.querySelector('.imageTaskContainer') === null) { - if (undoBuffer.length == 0) { - previewTools.classList.add('displayNone') + if (document.querySelector(".imageTaskContainer") === null) { + if (undoBuffer.length > 0) { + initialText.prepend(undoButton) } - initialText.classList.remove('displayNone') + previewTools.classList.add("displayNone") + initialText.classList.remove("displayNone") } else { - initialText.classList.add('displayNone') - previewTools.classList.remove('displayNone') + initialText.classList.add("displayNone") + previewTools.classList.remove("displayNone") + document.querySelector("div.display-settings").prepend(undoButton) } } @@ -1282,30 +1493,37 @@ function removeTask(taskToRemove) { updateInitialText() } -clearAllPreviewsBtn.addEventListener('click', (e) => { shiftOrConfirm(e, "Clear all the results and tasks in this window?", async function() { - await stopAllTasks() +clearAllPreviewsBtn.addEventListener("click", (e) => { + shiftOrConfirm(e, "Clear all the results and tasks in this window?", async function() { + await stopAllTasks() - let taskEntries = document.querySelectorAll('.imageTaskContainer') - taskEntries.forEach(removeTask) -})}) + let taskEntries = document.querySelectorAll(".imageTaskContainer") + taskEntries.forEach(removeTask) + }) +}) /* Download images popup */ -showDownloadPopupBtn.addEventListener("click", (e) => { saveAllImagesPopup.classList.add("active") }) +showDownloadPopupBtn.addEventListener("click", (e) => { + saveAllImagesPopup.classList.add("active") +}) -saveAllZipToggle.addEventListener('change', (e) => { +saveAllZipToggle.addEventListener("change", (e) => { if (saveAllZipToggle.checked) { - saveAllFoldersOption.classList.remove('displayNone') + saveAllFoldersOption.classList.remove("displayNone") } else { - saveAllFoldersOption.classList.add('displayNone') + saveAllFoldersOption.classList.add("displayNone") } }) // convert base64 to raw binary data held in a string function dataURItoBlob(dataURI) { - var byteString = atob(dataURI.split(',')[1]) + var byteString = atob(dataURI.split(",")[1]) // separate out the mime component - var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] + var mimeString = dataURI + .split(",")[0] + .split(":")[1] + .split(";")[0] // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length) @@ -1319,97 +1537,118 @@ function dataURItoBlob(dataURI) { } // write the ArrayBuffer to a blob, and you're done - return new Blob([ab], {type: mimeString}) + return new Blob([ab], { type: mimeString }) } function downloadAllImages() { let i = 0 - let optZIP = saveAllZipToggle.checked + let optZIP = saveAllZipToggle.checked let optTree = optZIP && saveAllTreeToggle.checked let optJSON = saveAllJSONToggle.checked - + let zip = new JSZip() let folder = zip - document.querySelectorAll(".imageTaskContainer").forEach(container => { + document.querySelectorAll(".imageTaskContainer").forEach((container) => { if (optTree) { - let name = ++i + '-' + container.querySelector('.preview-prompt').textContent.replace(/[^a-zA-Z0-9]/g, '_').substring(0,25) + let name = + ++i + + "-" + + container + .querySelector(".preview-prompt") + .textContent.replace(/[^a-zA-Z0-9]/g, "_") + .substring(0, 25) folder = zip.folder(name) } - container.querySelectorAll(".imgContainer img").forEach(img => { - let imgItem = img.closest('.imgItem') + container.querySelectorAll(".imgContainer img").forEach((img) => { + let imgItem = img.closest(".imgItem") - if (imgItem.style.display === 'none') { + if (imgItem.style.display === "none") { return } - let req = imageRequest[img.dataset['imagecounter']] + let req = imageRequest[img.dataset["imagecounter"]] if (optZIP) { - let suffix = img.dataset['imagecounter'] + '.' + req['output_format'] + let suffix = img.dataset["imagecounter"] + "." + req["output_format"] folder.file(getDownloadFilename(img, suffix), dataURItoBlob(img.src)) if (optJSON) { - suffix = img.dataset['imagecounter'] + '.json' + suffix = img.dataset["imagecounter"] + ".json" folder.file(getDownloadFilename(img, suffix), JSON.stringify(req, null, 2)) } } else { - setTimeout(() => {imgItem.querySelector('.download-img').click()}, i*200) - i = i+1 + setTimeout(() => { + imgItem.querySelector(".download-img").click() + }, i * 200) + i = i + 1 if (optJSON) { - setTimeout(() => {imgItem.querySelector('.download-json').click()}, i*200) - i = i+1 + setTimeout(() => { + imgItem.querySelector(".download-json").click() + }, i * 200) + i = i + 1 } } }) }) if (optZIP) { - let now = Date.now().toString(36).toUpperCase() - zip.generateAsync({type:"blob"}).then(function (blob) { - saveAs(blob, `EasyDiffusion-Images-${now}.zip`); + let now = Date.now() + .toString(36) + .toUpperCase() + zip.generateAsync({ type: "blob" }).then(function(blob) { + saveAs(blob, `EasyDiffusion-Images-${now}.zip`) }) } +} -} +saveAllImagesBtn.addEventListener("click", (e) => { + downloadAllImages() +}) -saveAllImagesBtn.addEventListener('click', (e) => { downloadAllImages() }) +stopImageBtn.addEventListener("click", (e) => { + shiftOrConfirm(e, "Stop all the tasks?", async function(e) { + await stopAllTasks() + }) +}) -stopImageBtn.addEventListener('click', (e) => { shiftOrConfirm(e, "Stop all the tasks?", async function(e) { - await stopAllTasks() -})}) - -widthField.addEventListener('change', onDimensionChange) -heightField.addEventListener('change', onDimensionChange) +widthField.addEventListener("change", onDimensionChange) +heightField.addEventListener("change", onDimensionChange) function renameMakeImageButton() { - let totalImages = Math.max(parseInt(numOutputsTotalField.value), parseInt(numOutputsParallelField.value)) * getPrompts().length - let imageLabel = 'Image' + let totalImages = + Math.max(parseInt(numOutputsTotalField.value), parseInt(numOutputsParallelField.value)) * getPromptsNumber() + let imageLabel = "Image" if (totalImages > 1) { - imageLabel = totalImages + ' Images' + imageLabel = totalImages + " Images" } if (SD.activeTasks.size == 0) { - makeImageBtn.innerText = 'Make ' + imageLabel + if (totalImages >= 10000) + makeImageBtn.innerText = "Make 10000+ images" + else + makeImageBtn.innerText = "Make " + imageLabel } else { - makeImageBtn.innerText = 'Enqueue Next ' + imageLabel + if (totalImages >= 10000) + makeImageBtn.innerText = "Enqueue 10000+ images" + else + makeImageBtn.innerText = "Enqueue Next " + imageLabel } } -numOutputsTotalField.addEventListener('change', renameMakeImageButton) -numOutputsTotalField.addEventListener('keyup', debounce(renameMakeImageButton, 300)) -numOutputsParallelField.addEventListener('change', renameMakeImageButton) -numOutputsParallelField.addEventListener('keyup', debounce(renameMakeImageButton, 300)) +numOutputsTotalField.addEventListener("change", renameMakeImageButton) +numOutputsTotalField.addEventListener("keyup", debounce(renameMakeImageButton, 300)) +numOutputsParallelField.addEventListener("change", renameMakeImageButton) +numOutputsParallelField.addEventListener("keyup", debounce(renameMakeImageButton, 300)) function onDimensionChange() { let widthValue = parseInt(widthField.value) let heightValue = parseInt(heightField.value) if (!initImagePreviewContainer.classList.contains("has-image")) { imageEditor.setImage(null, widthValue, heightValue) - } - else { + } else { imageInpainter.setImage(initImagePreview.src, widthValue, heightValue) } - if ( widthValue < 512 && heightValue < 512 ) { - smallImageWarning.classList.remove('displayNone') + if (widthValue < 512 && heightValue < 512) { + smallImageWarning.classList.remove("displayNone") } else { - smallImageWarning.classList.add('displayNone') + smallImageWarning.classList.add("displayNone") } } @@ -1417,26 +1656,101 @@ diskPathField.disabled = !saveToDiskField.checked metadataOutputFormatField.disabled = !saveToDiskField.checked gfpganModelField.disabled = !useFaceCorrectionField.checked -useFaceCorrectionField.addEventListener('change', function(e) { +useFaceCorrectionField.addEventListener("change", function(e) { gfpganModelField.disabled = !this.checked + + onFixFaceModelChange() }) +function onFixFaceModelChange() { + let codeformerSettings = document.querySelector("#codeformer_settings") + if (gfpganModelField.value === "codeformer" && !gfpganModelField.disabled) { + codeformerSettings.classList.remove("displayNone") + codeformerSettings.classList.add("expandedSettingRow") + } else { + codeformerSettings.classList.add("displayNone") + codeformerSettings.classList.remove("expandedSettingRow") + } +} +gfpganModelField.addEventListener("change", onFixFaceModelChange) +onFixFaceModelChange() + upscaleModelField.disabled = !useUpscalingField.checked upscaleAmountField.disabled = !useUpscalingField.checked -useUpscalingField.addEventListener('change', function(e) { +useUpscalingField.addEventListener("change", function(e) { upscaleModelField.disabled = !this.checked upscaleAmountField.disabled = !this.checked + + onUpscaleModelChange() }) -makeImageBtn.addEventListener('click', makeImage) +function onUpscaleModelChange() { + let upscale4x = document.querySelector("#upscale_amount_4x") + if (upscaleModelField.value === "latent_upscaler" && !upscaleModelField.disabled) { + upscale4x.disabled = true + upscaleAmountField.value = "2" + latentUpscalerSettings.classList.remove("displayNone") + latentUpscalerSettings.classList.add("expandedSettingRow") + } else { + upscale4x.disabled = false + latentUpscalerSettings.classList.add("displayNone") + latentUpscalerSettings.classList.remove("expandedSettingRow") + } +} +upscaleModelField.addEventListener("change", onUpscaleModelChange) +onUpscaleModelChange() + +makeImageBtn.addEventListener("click", makeImage) document.onkeydown = function(e) { - if (e.ctrlKey && e.code === 'Enter') { + if (e.ctrlKey && e.code === "Enter") { makeImage() e.preventDefault() } } +/********************* CodeFormer Fidelity **************************/ +function updateCodeformerFidelity() { + codeformerFidelityField.value = codeformerFidelitySlider.value / 10 + codeformerFidelityField.dispatchEvent(new Event("change")) +} + +function updateCodeformerFidelitySlider() { + if (codeformerFidelityField.value < 0) { + codeformerFidelityField.value = 0 + } else if (codeformerFidelityField.value > 1) { + codeformerFidelityField.value = 1 + } + + codeformerFidelitySlider.value = codeformerFidelityField.value * 10 + codeformerFidelitySlider.dispatchEvent(new Event("change")) +} + +codeformerFidelitySlider.addEventListener("input", updateCodeformerFidelity) +codeformerFidelityField.addEventListener("input", updateCodeformerFidelitySlider) +updateCodeformerFidelity() + +/********************* Latent Upscaler Steps **************************/ +function updateLatentUpscalerSteps() { + latentUpscalerStepsField.value = latentUpscalerStepsSlider.value + latentUpscalerStepsField.dispatchEvent(new Event("change")) +} + +function updateLatentUpscalerStepsSlider() { + if (latentUpscalerStepsField.value < 1) { + latentUpscalerStepsField.value = 1 + } else if (latentUpscalerStepsField.value > 50) { + latentUpscalerStepsField.value = 50 + } + + latentUpscalerStepsSlider.value = latentUpscalerStepsField.value + latentUpscalerStepsSlider.dispatchEvent(new Event("change")) +} + +latentUpscalerStepsSlider.addEventListener("input", updateLatentUpscalerSteps) +latentUpscalerStepsField.addEventListener("input", updateLatentUpscalerStepsSlider) +updateLatentUpscalerSteps() + /********************* Guidance **************************/ function updateGuidanceScale() { guidanceScaleField.value = guidanceScaleSlider.value / 10 @@ -1454,8 +1768,8 @@ function updateGuidanceScaleSlider() { guidanceScaleSlider.dispatchEvent(new Event("change")) } -guidanceScaleSlider.addEventListener('input', updateGuidanceScale) -guidanceScaleField.addEventListener('input', updateGuidanceScaleSlider) +guidanceScaleSlider.addEventListener("input", updateGuidanceScale) +guidanceScaleField.addEventListener("input", updateGuidanceScaleSlider) updateGuidanceScale() /********************* Prompt Strength *******************/ @@ -1475,8 +1789,8 @@ function updatePromptStrengthSlider() { promptStrengthSlider.dispatchEvent(new Event("change")) } -promptStrengthSlider.addEventListener('input', updatePromptStrength) -promptStrengthField.addEventListener('input', updatePromptStrengthSlider) +promptStrengthSlider.addEventListener("input", updatePromptStrength) +promptStrengthField.addEventListener("input", updatePromptStrengthSlider) updatePromptStrength() /********************* Hypernetwork Strength **********************/ @@ -1496,14 +1810,15 @@ function updateHypernetworkStrengthSlider() { hypernetworkStrengthSlider.dispatchEvent(new Event("change")) } -hypernetworkStrengthSlider.addEventListener('input', updateHypernetworkStrength) -hypernetworkStrengthField.addEventListener('input', updateHypernetworkStrengthSlider) +hypernetworkStrengthSlider.addEventListener("input", updateHypernetworkStrength) +hypernetworkStrengthField.addEventListener("input", updateHypernetworkStrengthSlider) updateHypernetworkStrength() function updateHypernetworkStrengthContainer() { - document.querySelector("#hypernetwork_strength_container").style.display = (hypernetworkModelField.value === "" ? 'none' : '') + document.querySelector("#hypernetwork_strength_container").style.display = + hypernetworkModelField.value === "" ? "none" : "" } -hypernetworkModelField.addEventListener('change', updateHypernetworkStrengthContainer) +hypernetworkModelField.addEventListener("change", updateHypernetworkStrengthContainer) updateHypernetworkStrengthContainer() /********************* LoRA alpha **********************/ @@ -1513,30 +1828,29 @@ function updateLoraAlpha() { } function updateLoraAlphaSlider() { - if (loraAlphaField.value < 0) { - loraAlphaField.value = 0 - } else if (loraAlphaField.value > 0.99) { - loraAlphaField.value = 0.99 + if (loraAlphaField.value < -2) { + loraAlphaField.value = -2 + } else if (loraAlphaField.value > 2) { + loraAlphaField.value = 2 } loraAlphaSlider.value = loraAlphaField.value * 100 loraAlphaSlider.dispatchEvent(new Event("change")) } -loraAlphaSlider.addEventListener('input', updateLoraAlpha) -loraAlphaField.addEventListener('input', updateLoraAlphaSlider) +loraAlphaSlider.addEventListener("input", updateLoraAlpha) +loraAlphaField.addEventListener("input", updateLoraAlphaSlider) updateLoraAlpha() -// function updateLoraAlphaContainer() { -// document.querySelector("#lora_alpha_container").style.display = (loraModelField.value === "" ? 'none' : '') -// } -// loraModelField.addEventListener('change', updateLoraAlphaContainer) -// updateLoraAlphaContainer() -document.querySelector("#lora_alpha_container").style.display = 'none' +function updateLoraAlphaContainer() { + document.querySelector("#lora_alpha_container").style.display = loraModelField.value === "" ? "none" : "" +} +loraModelField.addEventListener("change", updateLoraAlphaContainer) +updateLoraAlphaContainer() /********************* JPEG/WEBP Quality **********************/ function updateOutputQuality() { - outputQualityField.value = 0 | outputQualitySlider.value + outputQualityField.value = 0 | outputQualitySlider.value outputQualityField.dispatchEvent(new Event("change")) } @@ -1547,45 +1861,44 @@ function updateOutputQualitySlider() { outputQualityField.value = 95 } - outputQualitySlider.value = 0 | outputQualityField.value + outputQualitySlider.value = 0 | outputQualityField.value outputQualitySlider.dispatchEvent(new Event("change")) } -outputQualitySlider.addEventListener('input', updateOutputQuality) -outputQualityField.addEventListener('input', debounce(updateOutputQualitySlider, 1500)) +outputQualitySlider.addEventListener("input", updateOutputQuality) +outputQualityField.addEventListener("input", debounce(updateOutputQualitySlider, 1500)) updateOutputQuality() function updateOutputQualityVisibility() { - if (outputFormatField.value === 'webp') { - outputLosslessContainer.style.display = 'unset' + if (outputFormatField.value === "webp") { + outputLosslessContainer.classList.remove("displayNone") if (outputLosslessField.checked) { - outputQualityRow.style.display='none' + outputQualityRow.classList.add("displayNone") } else { - outputQualityRow.style.display='table-row' + outputQualityRow.classList.remove("displayNone") } - } - else if (outputFormatField.value === 'png') { - outputQualityRow.style.display='none' - outputLosslessContainer.style.display = 'none' + } else if (outputFormatField.value === "png") { + outputQualityRow.classList.add("displayNone") + outputLosslessContainer.classList.add("displayNone") } else { - outputQualityRow.style.display='table-row' - outputLosslessContainer.style.display = 'none' + outputQualityRow.classList.remove("displayNone") + outputLosslessContainer.classList.add("displayNone") } } -outputFormatField.addEventListener('change', updateOutputQualityVisibility) -outputLosslessField.addEventListener('change', updateOutputQualityVisibility) +outputFormatField.addEventListener("change", updateOutputQualityVisibility) +outputLosslessField.addEventListener("change", updateOutputQualityVisibility) /********************* Zoom Slider **********************/ -thumbnailSizeField.addEventListener('change', () => { - (function (s) { - for (var j =0; j < document.styleSheets.length; j++) { +thumbnailSizeField.addEventListener("change", () => { + ;(function(s) { + for (var j = 0; j < document.styleSheets.length; j++) { let cssSheet = document.styleSheets[j] for (var i = 0; i < cssSheet.cssRules.length; i++) { - var rule = cssSheet.cssRules[i]; + var rule = cssSheet.cssRules[i] if (rule.selectorText == "div.img-preview img") { - rule.style['max-height'] = s+'vh'; - rule.style['max-width'] = s+'vw'; - return; + rule.style["max-height"] = s + "vh" + rule.style["max-width"] = s + "vw" + return } } } @@ -1594,18 +1907,18 @@ thumbnailSizeField.addEventListener('change', () => { function onAutoScrollUpdate() { if (autoScroll.checked) { - autoscrollBtn.classList.add('pressed') + autoscrollBtn.classList.add("pressed") } else { - autoscrollBtn.classList.remove('pressed') + autoscrollBtn.classList.remove("pressed") } - autoscrollBtn.querySelector(".state").innerHTML = (autoScroll.checked ? "ON" : "OFF") + autoscrollBtn.querySelector(".state").innerHTML = autoScroll.checked ? "ON" : "OFF" } -autoscrollBtn.addEventListener('click', function() { +autoscrollBtn.addEventListener("click", function() { autoScroll.checked = !autoScroll.checked autoScroll.dispatchEvent(new Event("change")) onAutoScrollUpdate() }) -autoScroll.addEventListener('change', onAutoScrollUpdate) +autoScroll.addEventListener("change", onAutoScrollUpdate) function checkRandomSeed() { if (randomSeedField.checked) { @@ -1615,7 +1928,7 @@ function checkRandomSeed() { seedField.disabled = false } } -randomSeedField.addEventListener('input', checkRandomSeed) +randomSeedField.addEventListener("input", checkRandomSeed) checkRandomSeed() function loadImg2ImgFromFile() { @@ -1626,7 +1939,7 @@ function loadImg2ImgFromFile() { let reader = new FileReader() let file = initImageSelector.files[0] - reader.addEventListener('load', function(event) { + reader.addEventListener("load", function(event) { initImagePreview.src = reader.result }) @@ -1634,16 +1947,16 @@ function loadImg2ImgFromFile() { reader.readAsDataURL(file) } } -initImageSelector.addEventListener('change', loadImg2ImgFromFile) +initImageSelector.addEventListener("change", loadImg2ImgFromFile) loadImg2ImgFromFile() function img2imgLoad() { - promptStrengthContainer.style.display = 'table-row' + promptStrengthContainer.style.display = "table-row" if (!testDiffusers.checked) { samplerSelectionContainer.style.display = "none" } initImagePreviewContainer.classList.add("has-image") - colorCorrectionSetting.style.display = '' + colorCorrectionSetting.style.display = "" initImageSizeBox.textContent = initImagePreview.naturalWidth + " x " + initImagePreview.naturalHeight imageEditor.setImage(this.src, initImagePreview.naturalWidth, initImagePreview.naturalHeight) @@ -1652,7 +1965,7 @@ function img2imgLoad() { function img2imgUnload() { initImageSelector.value = null - initImagePreview.src = '' + initImagePreview.src = "" maskSetting.checked = false promptStrengthContainer.style.display = "none" @@ -1660,22 +1973,21 @@ function img2imgUnload() { samplerSelectionContainer.style.display = "" } initImagePreviewContainer.classList.remove("has-image") - colorCorrectionSetting.style.display = 'none' + colorCorrectionSetting.style.display = "none" imageEditor.setImage(null, parseInt(widthField.value), parseInt(heightField.value)) - } -initImagePreview.addEventListener('load', img2imgLoad) -initImageClearBtn.addEventListener('click', img2imgUnload) +initImagePreview.addEventListener("load", img2imgLoad) +initImageClearBtn.addEventListener("click", img2imgUnload) -maskSetting.addEventListener('click', function() { +maskSetting.addEventListener("click", function() { onDimensionChange() }) -promptsFromFileBtn.addEventListener('click', function() { +promptsFromFileBtn.addEventListener("click", function() { promptsFromFileSelector.click() }) -promptsFromFileSelector.addEventListener('change', async function() { +promptsFromFileSelector.addEventListener("change", async function() { if (promptsFromFileSelector.files.length === 0) { return } @@ -1683,7 +1995,7 @@ promptsFromFileSelector.addEventListener('change', async function() { let reader = new FileReader() let file = promptsFromFileSelector.files[0] - reader.addEventListener('load', async function() { + reader.addEventListener("load", async function() { await parseContent(reader.result) }) @@ -1693,15 +2005,15 @@ promptsFromFileSelector.addEventListener('change', async function() { }) /* setup popup handlers */ -document.querySelectorAll('.popup').forEach(popup => { - popup.addEventListener('click', event => { +document.querySelectorAll(".popup").forEach((popup) => { + popup.addEventListener("click", (event) => { if (event.target == popup) { popup.classList.remove("active") } }) var closeButton = popup.querySelector(".close-button") if (closeButton) { - closeButton.addEventListener('click', () => { + closeButton.addEventListener("click", () => { popup.classList.remove("active") }) } @@ -1709,9 +2021,9 @@ document.querySelectorAll('.popup').forEach(popup => { var tabElements = [] function selectTab(tab_id) { - let tabInfo = tabElements.find(t => t.tab.id == tab_id) + let tabInfo = tabElements.find((t) => t.tab.id == tab_id) if (!tabInfo.tab.classList.contains("active")) { - tabElements.forEach(info => { + tabElements.forEach((info) => { if (info.tab.classList.contains("active") && info.tab.parentNode === tabInfo.tab.parentNode) { info.tab.classList.toggle("active") info.content.classList.toggle("active") @@ -1720,7 +2032,7 @@ function selectTab(tab_id) { tabInfo.tab.classList.toggle("active") tabInfo.content.classList.toggle("active") } - document.dispatchEvent(new CustomEvent('tabClick', { detail: tabInfo })) + document.dispatchEvent(new CustomEvent("tabClick", { detail: tabInfo })) } function linkTabContents(tab) { var name = tab.id.replace("tab-", "") @@ -1728,10 +2040,10 @@ function linkTabContents(tab) { tabElements.push({ name: name, tab: tab, - content: content + content: content, }) - tab.addEventListener("click", event => selectTab(tab.id)) + tab.addEventListener("click", (event) => selectTab(tab.id)) } function isTabActive(tab) { return tab.classList.contains("active") @@ -1741,54 +2053,100 @@ let pauseClient = false function resumeClient() { if (pauseClient) { - document.body.classList.remove('wait-pause') - document.body.classList.add('pause') + document.body.classList.remove("wait-pause") + document.body.classList.add("pause") } - return new Promise(resolve => { - let playbuttonclick = function () { - resumeBtn.removeEventListener("click", playbuttonclick); - resolve("resolved"); + return new Promise((resolve) => { + let playbuttonclick = function() { + resumeBtn.removeEventListener("click", playbuttonclick) + resolve("resolved") } resumeBtn.addEventListener("click", playbuttonclick) }) } -promptField.addEventListener("input", debounce( renameMakeImageButton, 1000) ) + +function splashScreen(force = false) { + const splashVersion = splashScreenPopup.dataset['version'] + const lastSplash = localStorage.getItem("lastSplashScreenVersion") || 0 + if (testDiffusers.checked) { + if (force || lastSplash < splashVersion) { + splashScreenPopup.classList.add("active") + localStorage.setItem("lastSplashScreenVersion", splashVersion) + } + } +} -pauseBtn.addEventListener("click", function () { +document.getElementById("logo_img").addEventListener("click", (e) => { splashScreen(true) }) + +promptField.addEventListener("input", debounce(renameMakeImageButton, 1000)) + +pauseBtn.addEventListener("click", function() { pauseClient = true - pauseBtn.style.display="none" + pauseBtn.style.display = "none" resumeBtn.style.display = "inline" - document.body.classList.add('wait-pause') + document.body.classList.add("wait-pause") }) -resumeBtn.addEventListener("click", function () { +resumeBtn.addEventListener("click", function() { pauseClient = false resumeBtn.style.display = "none" pauseBtn.style.display = "inline" - document.body.classList.remove('pause') - document.body.classList.remove('wait-pause') + document.body.classList.remove("pause") + document.body.classList.remove("wait-pause") +}) + +function tunnelUpdate(event) { + if ("cloudflare" in event) { + document.getElementById("cloudflare-off").classList.add("displayNone") + document.getElementById("cloudflare-on").classList.remove("displayNone") + cloudflareAddressField.innerHTML = event.cloudflare + document.getElementById("toggle-cloudflare-tunnel").innerHTML = "Stop" + } else { + document.getElementById("cloudflare-on").classList.add("displayNone") + document.getElementById("cloudflare-off").classList.remove("displayNone") + document.getElementById("toggle-cloudflare-tunnel").innerHTML = "Start" + } +} + +document.getElementById("toggle-cloudflare-tunnel").addEventListener("click", async function() { + let command = "stop" + if (document.getElementById("toggle-cloudflare-tunnel").innerHTML == "Start") { + command = "start" + } + showToast(`Cloudflare tunnel ${command} initiated. Please wait.`) + + let res = await fetch("/tunnel/cloudflare/" + command, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({}), + }) + res = await res.json() + + console.log(`Cloudflare tunnel ${command} result:`, res) }) /* Pause function */ document.querySelectorAll(".tab").forEach(linkTabContents) window.addEventListener("beforeunload", function(e) { - const msg = "Unsaved pictures will be lost!"; + const msg = "Unsaved pictures will be lost!" - let elementList = document.getElementsByClassName("imageTaskContainer"); + let elementList = document.getElementsByClassName("imageTaskContainer") if (elementList.length != 0) { - e.preventDefault(); - (e || window.event).returnValue = msg; - return msg; + e.preventDefault() + ;(e || window.event).returnValue = msg + return msg } else { - return true; + return true } -}); +}) createCollapsibles() -prettifyInputs(document); +prettifyInputs(document) // set the textbox as focused on start promptField.focus() diff --git a/ui/media/js/parameters.js b/ui/media/js/parameters.js index cb0c7a4c..cd86be63 100644 --- a/ui/media/js/parameters.js +++ b/ui/media/js/parameters.js @@ -3,25 +3,33 @@ * @readonly * @enum {string} */ - var ParameterType = { +var ParameterType = { checkbox: "checkbox", select: "select", select_multiple: "select_multiple", slider: "slider", custom: "custom", -}; +} + +/** + * Element shortcuts + */ +let parametersTable = document.querySelector("#system-settings-table") +let networkParametersTable = document.querySelector("#system-settings-network-table") /** * JSDoc style * @typedef {object} Parameter * @property {string} id - * @property {ParameterType} type - * @property {string} label - * @property {?string} note + * @property {keyof ParameterType} type + * @property {string | (parameter: Parameter) => (HTMLElement | string)} label + * @property {string | (parameter: Parameter) => (HTMLElement | string) | undefined} note + * @property {(parameter: Parameter) => (HTMLElement | string) | undefined} render + * @property {string | undefined} icon * @property {number|boolean|string} default + * @property {boolean?} saveInAppConfig */ - /** @type {Array.} */ var PARAMETERS = [ { @@ -30,13 +38,14 @@ var PARAMETERS = [ label: "Theme", default: "theme-default", note: "customize the look and feel of the ui", - options: [ // Note: options expanded dynamically + options: [ + // Note: options expanded dynamically { value: "theme-default", - label: "Default" - } + label: "Default", + }, ], - icon: "fa-palette" + icon: "fa-palette", }, { id: "save_to_disk", @@ -52,7 +61,7 @@ var PARAMETERS = [ label: "Save Location", render: (parameter) => { return `` - } + }, }, { id: "metadata_output_format", @@ -63,20 +72,28 @@ var PARAMETERS = [ options: [ { value: "none", - label: "none" + label: "none", }, { value: "txt", - label: "txt" + label: "txt", }, { value: "json", - label: "json" + label: "json", }, { value: "embed", - label: "embed" - } + label: "embed", + }, + { + value: "embed,txt", + label: "embed & txt", + }, + { + value: "embed,json", + label: "embed & json", + }, ], }, { @@ -110,21 +127,23 @@ var PARAMETERS = [ note: "starts the default browser on startup", icon: "fa-window-restore", default: true, + saveInAppConfig: true, }, { id: "vram_usage_level", type: ParameterType.select, label: "GPU Memory Usage", - note: "Faster performance requires more GPU memory (VRAM)

" + - "Balanced: nearly as fast as High, much lower VRAM usage
" + - "High: fastest, maximum GPU memory usage
" + - "Low: slowest, recommended for GPUs with 3 to 4 GB memory", + note: + "Faster performance requires more GPU memory (VRAM)

" + + "Balanced: nearly as fast as High, much lower VRAM usage
" + + "High: fastest, maximum GPU memory usage
" + + "Low: slowest, recommended for GPUs with 3 to 4 GB memory", icon: "fa-forward", default: "balanced", options: [ - {value: "balanced", label: "Balanced"}, - {value: "high", label: "High"}, - {value: "low", label: "Low"} + { value: "balanced", label: "Balanced" }, + { value: "high", label: "High" }, + { value: "low", label: "Low" }, ], }, { @@ -160,7 +179,8 @@ var PARAMETERS = [ id: "confirm_dangerous_actions", type: ParameterType.checkbox, label: "Confirm dangerous actions", - note: "Actions that might lead to data loss must either be clicked with the shift key pressed, or confirmed in an 'Are you sure?' dialog", + note: + "Actions that might lead to data loss must either be clicked with the shift key pressed, or confirmed in an 'Are you sure?' dialog", icon: "fa-check-double", default: true, }, @@ -168,25 +188,31 @@ var PARAMETERS = [ id: "listen_to_network", type: ParameterType.checkbox, label: "Make Stable Diffusion available on your network", - note: "Other devices on your network can access this web page", + note: "Other devices on your network can access this web page. Please restart the program after changing this.", icon: "fa-network-wired", default: true, + saveInAppConfig: true, + table: networkParametersTable, }, { id: "listen_port", type: ParameterType.custom, label: "Network port", - note: "Port that this server listens to. The '9000' part in 'http://localhost:9000'", + note: + "Port that this server listens to. The '9000' part in 'http://localhost:9000'. Please restart the program after changing this.", icon: "fa-anchor", render: (parameter) => { return `` - } + }, + saveInAppConfig: true, + table: networkParametersTable, }, { id: "use_beta_channel", type: ParameterType.checkbox, label: "Beta channel", - note: "Get the latest features immediately (but could be less stable). Please restart the program after changing this.", + note: + "Get the latest features immediately (but could be less stable). Please restart the program after changing this.", icon: "fa-fire", default: false, }, @@ -194,14 +220,31 @@ var PARAMETERS = [ id: "test_diffusers", type: ParameterType.checkbox, label: "Test Diffusers", - note: "Experimental! Can have bugs! Use upcoming features (like LoRA) in our new engine. Please press Save, then restart the program after changing this.", + note: + "Experimental! Can have bugs! Use upcoming features (like LoRA) in our new engine. Please press Save, then restart the program after changing this.", icon: "fa-bolt", default: false, + saveInAppConfig: true, }, -]; + { + id: "cloudflare", + type: ParameterType.custom, + label: "Cloudflare tunnel", + note: `Create a VPN tunnel to share your Easy Diffusion instance with your friends. This will + generate a web server address on the public Internet for your Easy Diffusion instance. +
This Easy Diffusion server is available on the Internet using the + address:
+ Anyone knowing this address can access your server. The address of your server will change each time + you share a session.
+ Uses Cloudflare services.`, + icon: ["fa-brands", "fa-cloudflare"], + render: () => '', + table: networkParametersTable, + } +] function getParameterSettingsEntry(id) { - let parameter = PARAMETERS.filter(p => p.id === id) + let parameter = PARAMETERS.filter((p) => p.id === id) if (parameter.length === 0) { return } @@ -209,63 +252,125 @@ function getParameterSettingsEntry(id) { } function sliderUpdate(event) { - if (event.srcElement.id.endsWith('-input')) { - let slider = document.getElementById(event.srcElement.id.slice(0,-6)) + if (event.srcElement.id.endsWith("-input")) { + let slider = document.getElementById(event.srcElement.id.slice(0, -6)) slider.value = event.srcElement.value slider.dispatchEvent(new Event("change")) } else { - let field = document.getElementById(event.srcElement.id+'-input') + let field = document.getElementById(event.srcElement.id + "-input") field.value = event.srcElement.value field.dispatchEvent(new Event("change")) } } +/** + * @param {Parameter} parameter + * @returns {string | HTMLElement} + */ function getParameterElement(parameter) { switch (parameter.type) { case ParameterType.checkbox: - var is_checked = parameter.default ? " checked" : ""; + var is_checked = parameter.default ? " checked" : "" return `` case ParameterType.select: case ParameterType.select_multiple: - var options = (parameter.options || []).map(option => ``).join("") - var multiple = (parameter.type == ParameterType.select_multiple ? 'multiple' : '') + var options = (parameter.options || []) + .map((option) => ``) + .join("") + var multiple = parameter.type == ParameterType.select_multiple ? "multiple" : "" return `` case ParameterType.slider: return `  ${parameter.slider_unit}` case ParameterType.custom: return parameter.render(parameter) default: - console.error(`Invalid type for parameter ${parameter.id}`); + console.error(`Invalid type ${parameter.type} for parameter ${parameter.id}`) return "ERROR: Invalid Type" } } -let parametersTable = document.querySelector("#system-settings .parameters-table") -/* fill in the system settings popup table */ -function initParameters() { - PARAMETERS.forEach(parameter => { - var element = getParameterElement(parameter) - var note = parameter.note ? `${parameter.note}` : ""; - var icon = parameter.icon ? `` : ""; - var newrow = document.createElement('div') - newrow.innerHTML = ` -
${icon}
-
${note}
-
${element}
` - parametersTable.appendChild(newrow) +/** + * fill in the system settings popup table + * @param {Array | undefined} parameters + * */ +function initParameters(parameters) { + parameters.forEach((parameter) => { + const element = getParameterElement(parameter) + const elementWrapper = createElement("div") + if (element instanceof Node) { + elementWrapper.appendChild(element) + } else { + elementWrapper.innerHTML = element + } + + const note = typeof parameter.note === "function" ? parameter.note(parameter) : parameter.note + const noteElements = [] + if (note) { + const noteElement = createElement("small") + if (note instanceof Node) { + noteElement.appendChild(note) + } else { + noteElement.innerHTML = note || "" + } + noteElements.push(noteElement) + } + + if (typeof(parameter.icon) == "string") { + parameter.icon = [parameter.icon] + } + const icon = parameter.icon ? [createElement("i", undefined, ["fa", ...parameter.icon])] : [] + + const label = typeof parameter.label === "function" ? parameter.label(parameter) : parameter.label + const labelElement = createElement("label", { for: parameter.id }) + if (label instanceof Node) { + labelElement.appendChild(label) + } else { + labelElement.innerHTML = label + } + + const newrow = createElement( + "div", + { "data-setting-id": parameter.id, "data-save-in-app-config": parameter.saveInAppConfig }, + undefined, + [ + createElement("div", undefined, undefined, icon), + createElement("div", undefined, undefined, [labelElement, ...noteElements]), + elementWrapper, + ] + ) + + let p = parametersTable + if (parameter.table) { + p = parameter.table + } + p.appendChild(newrow) + parameter.settingsEntry = newrow }) } -initParameters() +initParameters(PARAMETERS) -let vramUsageLevelField = document.querySelector('#vram_usage_level') -let useCPUField = document.querySelector('#use_cpu') -let autoPickGPUsField = document.querySelector('#auto_pick_gpus') -let useGPUsField = document.querySelector('#use_gpus') -let saveToDiskField = document.querySelector('#save_to_disk') -let diskPathField = document.querySelector('#diskPath') -let metadataOutputFormatField = document.querySelector('#metadata_output_format') +// listen to parameters from plugins +PARAMETERS.addEventListener("push", (...items) => { + initParameters(items) + + if (items.find((item) => item.saveInAppConfig)) { + console.log( + "Reloading app config for new parameters", + items.map((p) => p.id) + ) + getAppConfig() + } +}) + +let vramUsageLevelField = document.querySelector("#vram_usage_level") +let useCPUField = document.querySelector("#use_cpu") +let autoPickGPUsField = document.querySelector("#auto_pick_gpus") +let useGPUsField = document.querySelector("#use_gpus") +let saveToDiskField = document.querySelector("#save_to_disk") +let diskPathField = document.querySelector("#diskPath") +let metadataOutputFormatField = document.querySelector("#metadata_output_format") let listenToNetworkField = document.querySelector("#listen_to_network") let listenPortField = document.querySelector("#listen_port") let useBetaChannelField = document.querySelector("#use_beta_channel") @@ -273,34 +378,38 @@ let uiOpenBrowserOnStartField = document.querySelector("#ui_open_browser_on_star let confirmDangerousActionsField = document.querySelector("#confirm_dangerous_actions") let testDiffusers = document.querySelector("#test_diffusers") -let saveSettingsBtn = document.querySelector('#save-system-settings-btn') - +let saveSettingsBtn = document.querySelector("#save-system-settings-btn") async function changeAppConfig(configDelta) { try { - let res = await fetch('/app_config', { - method: 'POST', + let res = await fetch("/app_config", { + method: "POST", headers: { - 'Content-Type': 'application/json' + "Content-Type": "application/json", }, - body: JSON.stringify(configDelta) + body: JSON.stringify(configDelta), }) res = await res.json() - console.log('set config status response', res) + console.log("set config status response", res) } catch (e) { - console.log('set config status error', e) + console.log("set config status error", e) } } async function getAppConfig() { try { - let res = await fetch('/get/app_config') + let res = await fetch("/get/app_config") const config = await res.json() - if (config.update_branch === 'beta') { + applySettingsFromConfig(config) + + // custom overrides + if (config.update_branch === "beta") { useBetaChannelField.checked = true document.querySelector("#updateBranchLabel").innerText = "(beta)" + } else { + getParameterSettingsEntry("test_diffusers").style.display = "none" } if (config.ui && config.ui.open_browser_on_start === false) { uiOpenBrowserOnStartField.checked = false @@ -311,86 +420,146 @@ async function getAppConfig() { if (config.net && config.net.listen_port !== undefined) { listenPortField.value = config.net.listen_port } - if (config.test_diffusers !== undefined) { - testDiffusers.checked = config.test_diffusers - document.querySelector("#lora_model_container").style.display = (testDiffusers.checked ? '' : 'none') + + const testDiffusersEnabled = config.test_diffusers && config.update_branch !== "main" + testDiffusers.checked = testDiffusersEnabled + + if (!testDiffusersEnabled) { + document.querySelector("#lora_model_container").style.display = "none" + document.querySelector("#lora_alpha_container").style.display = "none" + document.querySelector("#tiling_container").style.display = "none" + + document.querySelectorAll("#sampler_name option.diffusers-only").forEach((option) => { + option.style.display = "none" + }) + } else { + document.querySelector("#lora_model_container").style.display = "" + document.querySelector("#lora_alpha_container").style.display = loraModelField.value ? "" : "none" + document.querySelector("#tiling_container").style.display = "" + + document.querySelectorAll("#sampler_name option.k_diffusion-only").forEach((option) => { + option.disabled = true + }) + document.querySelector("#clip_skip_config").classList.remove("displayNone") } - console.log('get config status response', config) + console.log("get config status response", config) + + return config } catch (e) { - console.log('get config status error', e) + console.log("get config status error", e) + + return {} } } -saveToDiskField.addEventListener('change', function(e) { +function applySettingsFromConfig(config) { + Array.from(parametersTable.children).forEach((parameterRow) => { + if (parameterRow.dataset.settingId in config && parameterRow.dataset.saveInAppConfig === "true") { + const configValue = config[parameterRow.dataset.settingId] + const parameterElement = + document.getElementById(parameterRow.dataset.settingId) || + parameterRow.querySelector("input") || + parameterRow.querySelector("select") + + switch (parameterElement?.tagName) { + case "INPUT": + if (parameterElement.type === "checkbox") { + parameterElement.checked = configValue + } else { + parameterElement.value = configValue + } + parameterElement.dispatchEvent(new Event("change")) + break + case "SELECT": + if (Array.isArray(configValue)) { + Array.from(parameterElement.options).forEach((option) => { + if (configValue.includes(option.value || option.text)) { + option.selected = true + } + }) + } else { + parameterElement.value = configValue + } + parameterElement.dispatchEvent(new Event("change")) + break + } + } + }) +} + +saveToDiskField.addEventListener("change", function(e) { diskPathField.disabled = !this.checked metadataOutputFormatField.disabled = !this.checked }) function getCurrentRenderDeviceSelection() { - let selectedGPUs = $('#use_gpus').val() + let selectedGPUs = $("#use_gpus").val() if (useCPUField.checked && !autoPickGPUsField.checked) { - return 'cpu' + return "cpu" } if (autoPickGPUsField.checked || selectedGPUs.length == 0) { - return 'auto' + return "auto" } - return selectedGPUs.join(',') + return selectedGPUs.join(",") } -useCPUField.addEventListener('click', function() { - let gpuSettingEntry = getParameterSettingsEntry('use_gpus') - let autoPickGPUSettingEntry = getParameterSettingsEntry('auto_pick_gpus') +useCPUField.addEventListener("click", function() { + let gpuSettingEntry = getParameterSettingsEntry("use_gpus") + let autoPickGPUSettingEntry = getParameterSettingsEntry("auto_pick_gpus") if (this.checked) { - gpuSettingEntry.style.display = 'none' - autoPickGPUSettingEntry.style.display = 'none' - autoPickGPUsField.setAttribute('data-old-value', autoPickGPUsField.checked) + gpuSettingEntry.style.display = "none" + autoPickGPUSettingEntry.style.display = "none" + autoPickGPUsField.setAttribute("data-old-value", autoPickGPUsField.checked) autoPickGPUsField.checked = false } else if (useGPUsField.options.length >= MIN_GPUS_TO_SHOW_SELECTION) { - gpuSettingEntry.style.display = '' - autoPickGPUSettingEntry.style.display = '' - let oldVal = autoPickGPUsField.getAttribute('data-old-value') - if (oldVal === null || oldVal === undefined) { // the UI started with CPU selected by default + gpuSettingEntry.style.display = "" + autoPickGPUSettingEntry.style.display = "" + let oldVal = autoPickGPUsField.getAttribute("data-old-value") + if (oldVal === null || oldVal === undefined) { + // the UI started with CPU selected by default autoPickGPUsField.checked = true } else { - autoPickGPUsField.checked = (oldVal === 'true') + autoPickGPUsField.checked = oldVal === "true" } - gpuSettingEntry.style.display = (autoPickGPUsField.checked ? 'none' : '') + gpuSettingEntry.style.display = autoPickGPUsField.checked ? "none" : "" } }) -useGPUsField.addEventListener('click', function() { - let selectedGPUs = $('#use_gpus').val() - autoPickGPUsField.checked = (selectedGPUs.length === 0) +useGPUsField.addEventListener("click", function() { + let selectedGPUs = $("#use_gpus").val() + autoPickGPUsField.checked = selectedGPUs.length === 0 }) -autoPickGPUsField.addEventListener('click', function() { +autoPickGPUsField.addEventListener("click", function() { if (this.checked) { - $('#use_gpus').val([]) + $("#use_gpus").val([]) } - let gpuSettingEntry = getParameterSettingsEntry('use_gpus') - gpuSettingEntry.style.display = (this.checked ? 'none' : '') + let gpuSettingEntry = getParameterSettingsEntry("use_gpus") + gpuSettingEntry.style.display = this.checked ? "none" : "" }) -async function setDiskPath(defaultDiskPath, force=false) { +async function setDiskPath(defaultDiskPath, force = false) { var diskPath = getSetting("diskPath") - if (force || diskPath == '' || diskPath == undefined || diskPath == "undefined") { + if (force || diskPath == "" || diskPath == undefined || diskPath == "undefined") { setSetting("diskPath", defaultDiskPath) } } function setDeviceInfo(devices) { let cpu = devices.all.cpu.name - let allGPUs = Object.keys(devices.all).filter(d => d != 'cpu') + let allGPUs = Object.keys(devices.all).filter((d) => d != "cpu") let activeGPUs = Object.keys(devices.active) function ID_TO_TEXT(d) { let info = devices.all[d] if ("mem_free" in info && "mem_total" in info) { - return `${info.name} (${d}) (${info.mem_free.toFixed(1)}Gb free / ${info.mem_total.toFixed(1)} Gb total)` + return `${info.name} (${d}) (${info.mem_free.toFixed(1)}Gb free / ${info.mem_total.toFixed( + 1 + )} Gb total)` } else { return `${info.name} (${d}) (no memory info)` } @@ -399,95 +568,155 @@ function setDeviceInfo(devices) { allGPUs = allGPUs.map(ID_TO_TEXT) activeGPUs = activeGPUs.map(ID_TO_TEXT) - let systemInfoEl = document.querySelector('#system-info') - systemInfoEl.querySelector('#system-info-cpu').innerText = cpu - systemInfoEl.querySelector('#system-info-gpus-all').innerHTML = allGPUs.join('
') - systemInfoEl.querySelector('#system-info-rendering-devices').innerHTML = activeGPUs.join('
') + let systemInfoEl = document.querySelector("#system-info") + systemInfoEl.querySelector("#system-info-cpu").innerText = cpu + systemInfoEl.querySelector("#system-info-gpus-all").innerHTML = allGPUs.join("
") + systemInfoEl.querySelector("#system-info-rendering-devices").innerHTML = activeGPUs.join("
") } function setHostInfo(hosts) { let port = listenPortField.value - hosts = hosts.map(addr => `http://${addr}:${port}/`).map(url => ``) - document.querySelector('#system-info-server-hosts').innerHTML = hosts.join('') + hosts = hosts.map((addr) => `http://${addr}:${port}/`).map((url) => ``) + document.querySelector("#system-info-server-hosts").innerHTML = hosts.join("") } async function getSystemInfo() { try { const res = await SD.getSystemInfo() - let devices = res['devices'] + let devices = res["devices"] - let allDeviceIds = Object.keys(devices['all']).filter(d => d !== 'cpu') - let activeDeviceIds = Object.keys(devices['active']).filter(d => d !== 'cpu') + let allDeviceIds = Object.keys(devices["all"]).filter((d) => d !== "cpu") + let activeDeviceIds = Object.keys(devices["active"]).filter((d) => d !== "cpu") if (activeDeviceIds.length === 0) { useCPUField.checked = true } if (allDeviceIds.length < MIN_GPUS_TO_SHOW_SELECTION || useCPUField.checked) { - let gpuSettingEntry = getParameterSettingsEntry('use_gpus') - gpuSettingEntry.style.display = 'none' - let autoPickGPUSettingEntry = getParameterSettingsEntry('auto_pick_gpus') - autoPickGPUSettingEntry.style.display = 'none' + let gpuSettingEntry = getParameterSettingsEntry("use_gpus") + gpuSettingEntry.style.display = "none" + let autoPickGPUSettingEntry = getParameterSettingsEntry("auto_pick_gpus") + autoPickGPUSettingEntry.style.display = "none" } if (allDeviceIds.length === 0) { useCPUField.checked = true useCPUField.disabled = true // no compatible GPUs, so make the CPU mandatory + + getParameterSettingsEntry("use_cpu").addEventListener("click", function() { + alert( + "Sorry, we could not find a compatible graphics card! Easy Diffusion supports graphics cards with minimum 2 GB of RAM. " + + "Only NVIDIA cards are supported on Windows. NVIDIA and AMD cards are supported on Linux.

" + + "If you have a compatible graphics card, please try updating to the latest drivers.

" + + "Only the CPU can be used for generating images, without a compatible graphics card.", + "No compatible graphics card found!" + ) + }) } - autoPickGPUsField.checked = (devices['config'] === 'auto') + autoPickGPUsField.checked = devices["config"] === "auto" - useGPUsField.innerHTML = '' - allDeviceIds.forEach(device => { - let deviceName = devices['all'][device]['name'] + useGPUsField.innerHTML = "" + allDeviceIds.forEach((device) => { + let deviceName = devices["all"][device]["name"] let deviceOption = `` - useGPUsField.insertAdjacentHTML('beforeend', deviceOption) + useGPUsField.insertAdjacentHTML("beforeend", deviceOption) }) if (autoPickGPUsField.checked) { - let gpuSettingEntry = getParameterSettingsEntry('use_gpus') - gpuSettingEntry.style.display = 'none' + let gpuSettingEntry = getParameterSettingsEntry("use_gpus") + gpuSettingEntry.style.display = "none" } else { - $('#use_gpus').val(activeDeviceIds) + $("#use_gpus").val(activeDeviceIds) } - setDeviceInfo(devices) - setHostInfo(res['hosts']) + document.dispatchEvent(new CustomEvent("system_info_update", { detail: devices })) + setHostInfo(res["hosts"]) let force = false - if (res['enforce_output_dir'] !== undefined) { - force = res['enforce_output_dir'] + if (res["enforce_output_dir"] !== undefined) { + force = res["enforce_output_dir"] if (force == true) { - saveToDiskField.checked = true - metadataOutputFormatField.disabled = false + saveToDiskField.checked = true + metadataOutputFormatField.disabled = false } saveToDiskField.disabled = force diskPathField.disabled = force } - setDiskPath(res['default_output_dir'], force) + setDiskPath(res["default_output_dir"], force) } catch (e) { - console.log('error fetching devices', e) + console.log("error fetching devices", e) } } -saveSettingsBtn.addEventListener('click', function() { - if (listenPortField.value == '') { - alert('The network port field must not be empty.') +saveSettingsBtn.addEventListener("click", function() { + if (listenPortField.value == "") { + alert("The network port field must not be empty.") return } if (listenPortField.value < 1 || listenPortField.value > 65535) { - alert('The network port must be a number from 1 to 65535') + alert("The network port must be a number from 1 to 65535") return } - let updateBranch = (useBetaChannelField.checked ? 'beta' : 'main') - changeAppConfig({ - 'render_devices': getCurrentRenderDeviceSelection(), - 'update_branch': updateBranch, - 'ui_open_browser_on_start': uiOpenBrowserOnStartField.checked, - 'listen_to_network': listenToNetworkField.checked, - 'listen_port': listenPortField.value, - 'test_diffusers': testDiffusers.checked + const updateBranch = useBetaChannelField.checked ? "beta" : "main" + + const updateAppConfigRequest = { + render_devices: getCurrentRenderDeviceSelection(), + update_branch: updateBranch, + } + + document.querySelectorAll('#system-settings [data-setting-id]').forEach((parameterRow) => { + if (parameterRow.dataset.saveInAppConfig === "true") { + const parameterElement = + document.getElementById(parameterRow.dataset.settingId) || + parameterRow.querySelector("input") || + parameterRow.querySelector("select") + + switch (parameterElement?.tagName) { + case "INPUT": + if (parameterElement.type === "checkbox") { + updateAppConfigRequest[parameterRow.dataset.settingId] = parameterElement.checked + } else { + updateAppConfigRequest[parameterRow.dataset.settingId] = parameterElement.value + } + break + case "SELECT": + if (parameterElement.multiple) { + updateAppConfigRequest[parameterRow.dataset.settingId] = Array.from(parameterElement.options) + .filter((option) => option.selected) + .map((option) => option.value || option.text) + } else { + updateAppConfigRequest[parameterRow.dataset.settingId] = parameterElement.value + } + break + default: + console.error( + `Setting parameter ${parameterRow.dataset.settingId} couldn't be saved to app.config - element #${parameter.id} is a <${parameterElement?.tagName} /> instead of a or a `) +const pluginFilter = document.getElementById("plugin-filter") // search box + +// Add the debounced function to the keyup event listener +pluginFilter.addEventListener('keyup', debouncedFilterPlugins); + +// select the text on focus +pluginFilter.addEventListener('focus', function (event) { + pluginFilter.select() +}); + +// empty the searchbox on escape +pluginFilter.addEventListener('keydown', function (event) { + if (event.key === 'Escape') { + pluginFilter.value = ''; + filterPlugins(); + } +}); + +// focus on the search box upon tab selection +document.addEventListener("tabClick", (e) => { + if (e.detail.name == 'plugin') { + pluginFilter.focus() + } +}) + +// refresh link +pluginsTable.insertAdjacentHTML('afterend', `

Refresh plugins

+

(Plugin developers, add your plugins to plugins.json)

`) +const refreshPlugins = document.getElementById("refresh-plugins") +refreshPlugins.addEventListener("click", async function (event) { + event.preventDefault() + await initPlugins(true) +}) + +function showPluginToast(message, duration = 5000, error = false, addNotification = true) { + if (addNotification === true) { + addPluginNotification(pluginNotifications, message, error) + } + try { + showToast(message, duration, error) + } catch (error) { + console.error('Error while trying to show toast:', error); + } +} + +function matchPluginFileNames(fileName1, fileName2) { + const regex = /^(.+?)(?:-\d+(\.\d+)*)?\.plugin\.js$/; + const match1 = fileName1.match(regex); + const match2 = fileName2.match(regex); + + if (match1 && match2 && match1[1] === match2[1]) { + return true; // the two file names match + } else { + return false; // the two file names do not match + } +} + +function extractFilename(filepath) { + // Normalize the path separators to forward slashes and make the file names lowercase + const normalizedFilePath = filepath.replace(/\\/g, "/").toLowerCase(); + + // Strip off the path from the file name + const fileName = normalizedFilePath.substring(normalizedFilePath.lastIndexOf("/") + 1); + + return fileName +} + +function checkFileNameInArray(paths, filePath) { + // Strip off the path from the file name + const fileName = extractFilename(filePath); + + // Check if the file name exists in the array of paths + return paths.some(path => { + // Strip off the path from the file name + const baseName = extractFilename(path); + + // Check if the file names match and return the result as a boolean + return matchPluginFileNames(fileName, baseName); + }); +} + +function isGitHub(url) { + return url.startsWith("https://raw.githubusercontent.com/") === true +} + +/* fill in the plugins table */ +function getIncompatiblePlugins(pluginId) { + const enabledPlugins = plugins.filter(plugin => plugin.enabled && plugin.id !== pluginId); + const incompatiblePlugins = enabledPlugins.filter(plugin => plugin.compatIssueIds?.includes(pluginId)); + const pluginNames = incompatiblePlugins.map(plugin => plugin.name); + if (pluginNames.length === 0) { + return null; + } + const pluginNamesList = pluginNames.map(name => `
  • ${name}
  • `).join(''); + return `
      ${pluginNamesList}
    `; +} + +async function initPluginTable(plugins) { + pluginsTable.innerHTML = '' + plugins.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })) + plugins.forEach(plugin => { + const name = plugin.name + const author = plugin.author ? ', by ' + plugin.author : '' + const version = plugin.version ? ' (version: ' + plugin.version + ')' : '' + const warning = getIncompatiblePlugins(plugin.id) ? `This plugin might conflict with:${getIncompatiblePlugins(plugin.id)}` : '' + const note = plugin.description ? `${plugin.description.replaceAll('\n', '
    ')}
    ` : `No description`; + const icon = plugin.icon ? `` : ''; + const newRow = document.createElement('div') + const localPluginFound = checkFileNameInArray(localPlugins, plugin.url) + + newRow.innerHTML = ` +
    ${icon}
    +
    ${warning}${note}Source: ${extractFilename(plugin.url)}
    +
    + ${localPluginFound ? "Installed locally" : + (plugin.localInstallOnly ? 'Download and
    install manually
    ' : + (isGitHub(plugin.url) ? + '' : + '' + ) + ) + } +
    `; + newRow.classList.add('plugin-container') + //console.log(plugin.id, plugin.localInstallOnly) + pluginsTable.appendChild(newRow) + const pluginManualInstall = pluginsTable.querySelector('#plugin-' + plugin.id + '-install') + updateManualInstallButtonCaption() + + // checkbox event handler + const pluginToggle = pluginsTable.querySelector('#plugin-' + plugin.id) + if (pluginToggle !== null) { + pluginToggle.checked = plugin.enabled // set initial state of checkbox + pluginToggle.addEventListener('change', async () => { + const container = pluginToggle.closest(".plugin-container"); + const warningElement = container.querySelector(".plugin-warning"); + + // if the plugin got enabled, download the plugin's code + plugin.enabled = pluginToggle.checked + if (plugin.enabled) { + const pluginSource = await getDocument(plugin.url); + if (pluginSource !== null) { + // Store the current scroll position before navigating away + const currentPosition = window.pageYOffset; + initPluginTable(plugins) + // When returning to the page, set the scroll position to the stored value + window.scrollTo(0, currentPosition); + warningElement?.classList.remove("hide"); + plugin.code = pluginSource + loadPlugins([plugin]) + console.log(`Plugin ${plugin.name} installed`); + showPluginToast("Plugin " + plugin.name + " installed"); + } + else { + plugin.enabled = false + pluginToggle.checked = false + console.error(`Couldn't download plugin ${plugin.name}`); + showPluginToast("Failed to install " + plugin.name + " (Couldn't fetch " + extractFilename(plugin.url) + ")", 5000, true); + } + } else { + warningElement?.classList.add("hide"); + // Store the current scroll position before navigating away + const currentPosition = window.pageYOffset; + initPluginTable(plugins) + // When returning to the page, set the scroll position to the stored value + window.scrollTo(0, currentPosition); + console.log(`Plugin ${plugin.name} uninstalled`); + showPluginToast("Plugin " + plugin.name + " uninstalled"); + } + await setStorageData('plugins', JSON.stringify(plugins)) + }) + } + + // manual install event handler + if (pluginManualInstall !== null) { + pluginManualInstall.addEventListener('click', async () => { + pluginDialogOpenDialog(inputOK, inputCancel) + pluginDialogTextarea.value = plugin.code ? plugin.code : '' + pluginDialogTextarea.select() + pluginDialogTextarea.focus() + }) + } + // Dialog OK + async function inputOK() { + let pluginSource = pluginDialogTextarea.value + // remove empty lines and trim existing lines + plugin.code = pluginSource + if (pluginSource.trim() !== '') { + plugin.enabled = true + console.log(`Plugin ${plugin.name} installed`); + showPluginToast("Plugin " + plugin.name + " installed"); + } + else { + plugin.enabled = false + console.log(`No code provided for plugin ${plugin.name}, disabling the plugin`); + showPluginToast("No code provided for plugin " + plugin.name + ", disabling the plugin"); + } + updateManualInstallButtonCaption() + await setStorageData('plugins', JSON.stringify(plugins)) + } + // Dialog Cancel + async function inputCancel() { + plugin.enabled = false + console.log(`Installation of plugin ${plugin.name} cancelled`); + showPluginToast("Cancelled installation of " + plugin.name); + } + // update button caption + function updateManualInstallButtonCaption() { + if (pluginManualInstall !== null) { + pluginManualInstall.innerHTML = plugin.code === undefined || plugin.code.trim() === '' ? 'Install' : 'Edit' + } + } + }) + prettifyInputs(pluginsTable) + filterPlugins() +} + +/* version management. Thanks Madrang! */ +const parseVersion = function (versionString, options = {}) { + if (typeof versionString === "undefined") { + throw new Error("versionString is undefined."); + } + if (typeof versionString !== "string") { + throw new Error("versionString is not a string."); + } + const lexicographical = options && options.lexicographical; + const zeroExtend = options && options.zeroExtend; + let versionParts = versionString.split('.'); + function isValidPart(x) { + const re = (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/); + return re.test(x); + } + + if (!versionParts.every(isValidPart)) { + throw new Error("Version string is invalid."); + } + + if (zeroExtend) { + while (versionParts.length < 4) { + versionParts.push("0"); + } + } + if (!lexicographical) { + versionParts = versionParts.map(Number); + } + return versionParts; +}; + +const versionCompare = function (v1, v2, options = {}) { + if (typeof v1 == "undefined") { + throw new Error("vi is undefined."); + } + if (typeof v2 === "undefined") { + throw new Error("v2 is undefined."); + } + + let v1parts; + if (typeof v1 === "string") { + v1parts = parseVersion(v1, options); + } else if (Array.isArray(v1)) { + v1parts = [...v1]; + if (!v1parts.every(p => typeof p === "number" && p !== NaN)) { + throw new Error("v1 part array does not only contains numbers."); + } + } else { + throw new Error("v1 is of an unexpected type: " + typeof v1); + } + + let v2parts; + if (typeof v2 === "string") { + v2parts = parseVersion(v2, options); + } else if (Array.isArray(v2)) { + v2parts = [...v2]; + if (!v2parts.every(p => typeof p === "number" && p !== NaN)) { + throw new Error("v2 part array does not only contains numbers."); + } + } else { + throw new Error("v2 is of an unexpected type: " + typeof v2); + } + + while (v1parts.length < v2parts.length) { + v1parts.push("0"); + } + while (v2parts.length < v1parts.length) { + v2parts.push("0"); + } + + for (let i = 0; i < v1parts.length; ++i) { + if (v2parts.length == i) { + return 1; + } + if (v1parts[i] == v2parts[i]) { + continue; + } else if (v1parts[i] > v2parts[i]) { + return 1; + } else { + return -1; + } + } + return 0; +}; + +function filterPluginsByMinEDVersion(plugins, EDVersion) { + const filteredPlugins = plugins.filter(plugin => { + if (plugin.minEDVersion) { + return versionCompare(plugin.minEDVersion, EDVersion) <= 0; + } + return true; + }); + + return filteredPlugins; +} + +function extractVersionNumber(elem) { + const versionStr = elem.innerHTML; + const regex = /v(\d+\.\d+\.\d+)/; + const matches = regex.exec(versionStr); + if (matches && matches.length > 1) { + return matches[1]; + } else { + return null; + } +} +const EasyDiffusionVersion = extractVersionNumber(document.querySelector('#top-nav > #logo')) + +/* PLUGIN MANAGEMENT */ +let plugins +let localPlugins +let initPluginsInProgress = false + +async function initPlugins(refreshPlugins = false) { + let pluginsLoaded + if (initPluginsInProgress === true) { + return + } + initPluginsInProgress = true + + const res = await fetch('/get/ui_plugins') + if (!res.ok) { + console.error(`Error HTTP${res.status} while loading plugins list. - ${res.statusText}`) + } + else { + localPlugins = await res.json() + } + + if (refreshPlugins === false) { + // load the notifications + pluginNotifications = await getStorageData('notifications') + if (typeof pluginNotifications === "string") { + try { + pluginNotifications = JSON.parse(pluginNotifications) + } catch (e) { + console.error("Failed to parse pluginNotifications", e); + pluginNotifications = {}; + pluginNotifications.entries = []; + } + } + if (pluginNotifications !== undefined) { + if (pluginNotifications.entries && pluginNotifications.entries.length > 0 && pluginNotifications.entries[0].date && pluginNotifications.lastUpdated <= pluginNotifications.entries[0].date) { + notificationPill.style.display = "block"; + } + } else { + pluginNotifications = {}; + pluginNotifications.entries = []; + } + + // try and load plugins from local cache + plugins = await getStorageData('plugins') + if (plugins !== undefined) { + plugins = JSON.parse(plugins) + + // remove duplicate entries if any (should not happen) + plugins = deduplicatePluginsById(plugins) + + // remove plugins that don't meet the min ED version requirement + plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion) + + // remove from plugins the entries that don't have mandatory fields (id, name, url) + plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; }); + + // populate the table + initPluginTable(plugins) + await loadPlugins(plugins) + pluginsLoaded = true + } + else { + plugins = [] + pluginsLoaded = false + } + } + + // update plugins asynchronously (updated versions will be available next time the UI is loaded) + if (refreshAllowed()) { + let pluginCatalog = await getDocument(PLUGIN_CATALOG) + if (pluginCatalog !== null) { + let parseError = false; + try { + pluginCatalog = JSON.parse(pluginCatalog); + console.log('Plugin catalog successfully downloaded'); + } catch (error) { + console.error('Error parsing plugin catalog:', error); + parseError = true; + } + + if (!parseError) { + await downloadPlugins(pluginCatalog, plugins, refreshPlugins) + + // update compatIssueIds + updateCompatIssueIds() + + // remove plugins that don't meet the min ED version requirement + plugins = filterPluginsByMinEDVersion(plugins, EasyDiffusionVersion) + + // remove from plugins the entries that don't have mandatory fields (id, name, url) + plugins = plugins.filter((plugin) => { return plugin.id !== '' && plugin.name !== '' && plugin.url !== ''; }); + + // remove from plugins the entries that no longer exist in the catalog + plugins = plugins.filter((plugin) => { return pluginCatalog.some((p) => p.id === plugin.id) }); + + if (pluginCatalog.length > plugins.length) { + const newPlugins = pluginCatalog.filter((plugin) => { + return !plugins.some((p) => p.id === plugin.id); + }); + + newPlugins.forEach((plugin, index) => { + setTimeout(() => { + showPluginToast(`New plugin "${plugin.name}" is available.`); + }, (index + 1) * 1000); + }); + } + + let pluginsJson; + try { + pluginsJson = JSON.stringify(plugins); // attempt to parse plugins to JSON + } catch (error) { + console.error('Error converting plugins to JSON:', error); + } + + if (pluginsJson) { // only store the data if pluginsJson is not null or undefined + await setStorageData('plugins', pluginsJson) + } + + // refresh the display of the plugins table + initPluginTable(plugins) + if (pluginsLoaded && pluginsLoaded === false) { + loadPlugins(plugins) + } + } + } + } + else { + if (refreshPlugins) { + showPluginToast('Plugins have been refreshed recently, refresh will be available in ' + convertSeconds(getTimeUntilNextRefresh()), 5000, true, false) + } + } + initPluginsInProgress = false +} + +function updateMetaTagPlugins(plugin) { + // Update the meta tag with the list of loaded plugins + let metaTag = document.querySelector('meta[name="plugins"]'); + if (metaTag === null) { + metaTag = document.createElement('meta'); + metaTag.name = 'plugins'; + document.head.appendChild(metaTag); + } + const pluginArray = [...(metaTag.content ? metaTag.content.split(',') : []), plugin.id]; + metaTag.content = pluginArray.join(','); +} + +function updateCompatIssueIds() { + // Loop through each plugin + plugins.forEach(plugin => { + // Check if the plugin has `compatIssueIds` property + if (plugin.compatIssueIds !== undefined) { + // Loop through each of the `compatIssueIds` + plugin.compatIssueIds.forEach(issueId => { + // Find the plugin with the corresponding `issueId` + const issuePlugin = plugins.find(p => p.id === issueId); + // If the corresponding plugin is found, initialize its `compatIssueIds` property with an empty array if it's undefined + if (issuePlugin) { + if (issuePlugin.compatIssueIds === undefined) { + issuePlugin.compatIssueIds = []; + } + // If the current plugin's ID is not already in the `compatIssueIds` array, add it + if (!issuePlugin.compatIssueIds.includes(plugin.id)) { + issuePlugin.compatIssueIds.push(plugin.id); + } + } + }); + } else { + // If the plugin doesn't have `compatIssueIds` property, initialize it with an empty array + plugin.compatIssueIds = []; + } + }); +} + +function deduplicatePluginsById(plugins) { + const seenIds = new Set(); + const deduplicatedPlugins = []; + + for (const plugin of plugins) { + if (!seenIds.has(plugin.id)) { + seenIds.add(plugin.id); + deduplicatedPlugins.push(plugin); + } else { + // favor dupes that have enabled == true + const index = deduplicatedPlugins.findIndex(p => p.id === plugin.id); + if (index >= 0) { + if (plugin.enabled) { + deduplicatedPlugins[index] = plugin; + } + } + } + } + + return deduplicatedPlugins; +} + +async function loadPlugins(plugins) { + for (let i = 0; i < plugins.length; i++) { + const plugin = plugins[i]; + if (plugin.enabled === true && plugin.localInstallOnly !== true) { + const localPluginFound = checkFileNameInArray(localPlugins, plugin.url); + if (!localPluginFound) { + try { + // Indirect eval to work around sloppy plugin implementations + const indirectEval = { eval }; + console.log("Loading plugin " + plugin.name); + indirectEval.eval(plugin.code); + console.log("Plugin " + plugin.name + " loaded"); + await updateMetaTagPlugins(plugin); // add plugin to the meta tag + } catch (err) { + showPluginToast("Error loading plugin " + plugin.name + " (" + err.message + ")", null, true); + console.error("Error loading plugin " + plugin.name + ": " + err.message); + } + } else { + console.log("Skipping plugin " + plugin.name + " (installed locally)"); + } + } + } +} + +async function getFileHash(url) { + const regex = /^https:\/\/raw\.githubusercontent\.com\/(?[^/]+)\/(?[^/]+)\/(?[^/]+)\/(?.+)$/; + const match = url.match(regex); + if (!match) { + console.error('Invalid GitHub repository URL.'); + return Promise.resolve(null); + } + const owner = match.groups.owner; + const repo = match.groups.repo; + const branch = match.groups.branch; + const filePath = match.groups.filePath; + const apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${filePath}?ref=${branch}`; + + try { + const response = await fetch(apiUrl); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}, url: ${apiUrl}`); + } + const data = await response.json(); + return data.sha; + } catch (error) { + console.error('Error fetching data from url:', apiUrl, 'Error:', error); + return null; + } +} + +// only allow two refresh per hour +function getTimeUntilNextRefresh() { + const lastRuns = JSON.parse(localStorage.getItem('lastRuns') || '[]'); + const currentTime = new Date().getTime(); + const numRunsLast60Min = lastRuns.filter(run => currentTime - run <= 60 * 60 * 1000).length; + + if (numRunsLast60Min >= 2) { + return 3600 - Math.round((currentTime - lastRuns[lastRuns.length - 1]) / 1000); + } + + return 0; +} + +function refreshAllowed() { + const timeUntilNextRefresh = getTimeUntilNextRefresh(); + + if (timeUntilNextRefresh > 0) { + console.log(`Next refresh available in ${timeUntilNextRefresh} seconds`); + return false; + } + + const lastRuns = JSON.parse(localStorage.getItem('lastRuns') || '[]'); + const currentTime = new Date().getTime(); + lastRuns.push(currentTime); + localStorage.setItem('lastRuns', JSON.stringify(lastRuns)); + return true; +} + +async function downloadPlugins(pluginCatalog, plugins, refreshPlugins) { + // download the plugins as needed + for (const plugin of pluginCatalog) { + //console.log(plugin.id, plugin.url) + const existingPlugin = plugins.find(p => p.id === plugin.id); + // get the file hash in the GitHub repo + let sha + if (isGitHub(plugin.url) && existingPlugin?.enabled === true) { + sha = await getFileHash(plugin.url) + } + if (plugin.localInstallOnly !== true && isGitHub(plugin.url) && existingPlugin?.enabled === true && (refreshPlugins || (existingPlugin.sha !== undefined && existingPlugin.sha !== null && existingPlugin.sha !== sha) || existingPlugin?.code === undefined)) { + const pluginSource = await getDocument(plugin.url); + if (pluginSource !== null && pluginSource !== existingPlugin.code) { + console.log(`Plugin ${plugin.name} updated`); + showPluginToast("Plugin " + plugin.name + " updated", 5000); + // Update the corresponding plugin + const updatedPlugin = { + ...existingPlugin, + icon: plugin.icon ? plugin.icon : "fa-puzzle-piece", + id: plugin.id, + name: plugin.name, + description: plugin.description, + url: plugin.url, + localInstallOnly: Boolean(plugin.localInstallOnly), + version: plugin.version, + code: pluginSource, + author: plugin.author, + sha: sha, + compatIssueIds: plugin.compatIssueIds + }; + // Replace the old plugin in the plugins array + const pluginIndex = plugins.indexOf(existingPlugin); + if (pluginIndex >= 0) { + plugins.splice(pluginIndex, 1, updatedPlugin); + } else { + plugins.push(updatedPlugin); + } + } + } + else if (existingPlugin !== undefined) { + // Update the corresponding plugin's metadata + const updatedPlugin = { + ...existingPlugin, + icon: plugin.icon ? plugin.icon : "fa-puzzle-piece", + id: plugin.id, + name: plugin.name, + description: plugin.description, + url: plugin.url, + localInstallOnly: Boolean(plugin.localInstallOnly), + version: plugin.version, + author: plugin.author, + compatIssueIds: plugin.compatIssueIds + }; + // Replace the old plugin in the plugins array + const pluginIndex = plugins.indexOf(existingPlugin); + plugins.splice(pluginIndex, 1, updatedPlugin); + } + else { + plugins.push(plugin); + } + } +} + +async function getDocument(url) { + try { + let response = await fetch(url === PLUGIN_CATALOG ? PLUGIN_CATALOG : url, { cache: "no-cache" }); + if (!response.ok) { + throw new Error(`Response error: ${response.status} ${response.statusText}`); + } + let document = await response.text(); + return document; + } catch (error) { + showPluginToast("Couldn't fetch " + extractFilename(url) + " (" + error + ")", null, true); + console.error(error); + return null; + } +} + +/* MODAL DIALOG */ +const pluginDialogDialog = document.createElement("div"); +pluginDialogDialog.id = "pluginDialog-input-dialog"; +pluginDialogDialog.style.display = "none"; + +pluginDialogDialog.innerHTML = ` +
    +
    +
    +

    Paste the plugin's code here

    + +
    +
    + +
    +
    + + +
    +
    +`; + +document.body.appendChild(pluginDialogDialog); + +const pluginDialogOverlay = document.querySelector(".pluginDialog-dialog-overlay"); +const pluginDialogOkButton = document.getElementById("pluginDialog-input-ok"); +const pluginDialogCancelButton = document.getElementById("pluginDialog-input-cancel"); +const pluginDialogCloseButton = document.querySelector(".pluginDialog-dialog-close-button"); +const pluginDialogTextarea = document.getElementById("pluginDialog-input-textarea"); +let callbackOK +let callbackCancel + +function pluginDialogOpenDialog(inputOK, inputCancel) { + pluginDialogDialog.style.display = "block"; + callbackOK = inputOK + callbackCancel = inputCancel +} + +function pluginDialogCloseDialog() { + pluginDialogDialog.style.display = "none"; +} + +function pluginDialogHandleOkClick() { + const userInput = pluginDialogTextarea.value; + // Do something with the user input + callbackOK() + pluginDialogCloseDialog(); +} + +function pluginDialogHandleCancelClick() { + callbackCancel() + pluginDialogCloseDialog(); +} + +function pluginDialogHandleOverlayClick(event) { + if (event.target === pluginDialogOverlay) { + pluginDialogCloseDialog(); + } +} + +function pluginDialogHandleKeyDown(event) { + if ((event.key === "Enter" && event.ctrlKey) || event.key === "Escape") { + event.preventDefault(); + if (event.key === "Enter" && event.ctrlKey) { + pluginDialogHandleOkClick(); + } else { + pluginDialogCloseDialog(); + } + } +} + +pluginDialogTextarea.addEventListener("keydown", pluginDialogHandleKeyDown); +pluginDialogOkButton.addEventListener("click", pluginDialogHandleOkClick); +pluginDialogCancelButton.addEventListener("click", pluginDialogHandleCancelClick); +pluginDialogCloseButton.addEventListener("click", pluginDialogCloseDialog); +pluginDialogOverlay.addEventListener("click", pluginDialogHandleOverlayClick); diff --git a/ui/media/js/searchable-models.js b/ui/media/js/searchable-models.js index 4f311a76..7bdb176a 100644 --- a/ui/media/js/searchable-models.js +++ b/ui/media/js/searchable-models.js @@ -21,14 +21,13 @@ let hypernetworkModelField = new ModelDropdown(document.querySelector('#hypernet 3) Model dropdowns will be refreshed automatically when the reload models button is invoked. */ -class ModelDropdown -{ +class ModelDropdown { modelFilter //= document.querySelector("#model-filter") modelFilterArrow //= document.querySelector("#model-filter-arrow") modelList //= document.querySelector("#model-list") modelResult //= document.querySelector("#model-result") modelNoResult //= document.querySelector("#model-no-result") - + currentSelection //= { elem: undefined, value: '', path: ''} highlightedModelEntry //= undefined activeModel //= undefined @@ -39,6 +38,8 @@ class ModelDropdown noneEntry //= '' modelFilterInitialized //= undefined + sorted //= true + /* MIMIC A REGULAR INPUT FIELD */ get parentElement() { return this.modelFilter.parentElement @@ -59,11 +60,11 @@ class ModelDropdown set disabled(state) { this.modelFilter.disabled = state if (this.modelFilterArrow) { - this.modelFilterArrow.style.color = state ? 'dimgray' : '' + this.modelFilterArrow.style.color = state ? "dimgray" : "" } } get modelElements() { - return this.modelList.querySelectorAll('.model-file') + return this.modelList.querySelectorAll(".model-file") } addEventListener(type, listener, options) { return this.modelFilter.addEventListener(type, listener, options) @@ -82,21 +83,39 @@ class ModelDropdown } } - /* SEARCHABLE INPUT */ - constructor (input, modelKey, noneEntry = '') { + /* SEARCHABLE INPUT */ + + constructor(input, modelKey, noneEntry = "", sorted = true) { this.modelFilter = input this.noneEntry = noneEntry this.modelKey = modelKey + this.sorted = sorted - if (modelsOptions !== undefined) { // reuse models from cache (only useful for plugins, which are loaded after models) - this.inputModels = modelsOptions[this.modelKey] + if (modelsOptions !== undefined) { + // reuse models from cache (only useful for plugins, which are loaded after models) + this.inputModels = [] + let modelKeys = Array.isArray(this.modelKey) ? this.modelKey : [this.modelKey] + for (let i = 0; i < modelKeys.length; i++) { + let key = modelKeys[i] + let k = Array.isArray(modelsOptions[key]) ? modelsOptions[key] : [modelsOptions[key]] + this.inputModels.push(...k) + } this.populateModels() } - document.addEventListener("refreshModels", this.bind(function(e) { - // reload the models - this.inputModels = modelsOptions[this.modelKey] - this.populateModels() - }, this)) + document.addEventListener( + "refreshModels", + this.bind(function(e) { + // reload the models + this.inputModels = [] + let modelKeys = Array.isArray(this.modelKey) ? this.modelKey : [this.modelKey] + for (let i = 0; i < modelKeys.length; i++) { + let key = modelKeys[i] + let k = Array.isArray(modelsOptions[key]) ? modelsOptions[key] : [modelsOptions[key]] + this.inputModels.push(...k) + } + this.populateModels() + }, this) + ) } saveCurrentSelection(elem, value, path) { @@ -105,13 +124,13 @@ class ModelDropdown this.currentSelection.path = path this.modelFilter.dataset.path = path this.modelFilter.value = value - this.modelFilter.dispatchEvent(new Event('change')) + this.modelFilter.dispatchEvent(new Event("change")) } - + processClick(e) { e.preventDefault() - if (e.srcElement.classList.contains('model-file') || e.srcElement.classList.contains('fa-file')) { - const elem = e.srcElement.classList.contains('model-file') ? e.srcElement : e.srcElement.parentElement + if (e.srcElement.classList.contains("model-file") || e.srcElement.classList.contains("fa-file")) { + const elem = e.srcElement.classList.contains("model-file") ? e.srcElement : e.srcElement.parentElement this.saveCurrentSelection(elem, elem.innerText, elem.dataset.path) this.hideModelList() this.modelFilter.focus() @@ -126,66 +145,67 @@ class ModelDropdown return undefined } - return modelElements.slice(0, index).reverse().find(e => e.style.display === 'list-item') + return modelElements + .slice(0, index) + .reverse() + .find((e) => e.style.display === "list-item") } getLastVisibleChild(elem) { let lastElementChild = elem.lastElementChild - if (lastElementChild.style.display == 'list-item') return lastElementChild + if (lastElementChild.style.display == "list-item") return lastElementChild return this.getPreviousVisibleSibling(lastElementChild) } - + getNextVisibleSibling(elem) { const modelElements = Array.from(this.modelElements) const index = modelElements.indexOf(elem) - return modelElements.slice(index + 1).find(e => e.style.display === 'list-item') + return modelElements.slice(index + 1).find((e) => e.style.display === "list-item") } - + getFirstVisibleChild(elem) { let firstElementChild = elem.firstElementChild - if (firstElementChild.style.display == 'list-item') return firstElementChild + if (firstElementChild.style.display == "list-item") return firstElementChild return this.getNextVisibleSibling(firstElementChild) } - + selectModelEntry(elem) { if (elem) { if (this.highlightedModelEntry !== undefined) { - this.highlightedModelEntry.classList.remove('selected') + this.highlightedModelEntry.classList.remove("selected") } this.saveCurrentSelection(elem, elem.innerText, elem.dataset.path) - elem.classList.add('selected') - elem.scrollIntoView({block: 'nearest'}) + elem.classList.add("selected") + elem.scrollIntoView({ block: "nearest" }) this.highlightedModelEntry = elem } } - + selectPreviousFile() { const elem = this.getPreviousVisibleSibling(this.highlightedModelEntry) if (elem) { this.selectModelEntry(elem) - } - else - { + } else { //this.highlightedModelEntry.parentElement.parentElement.scrollIntoView({block: 'nearest'}) - this.highlightedModelEntry.closest('.model-list').scrollTop = 0 + this.highlightedModelEntry.closest(".model-list").scrollTop = 0 } this.modelFilter.select() } - + selectNextFile() { this.selectModelEntry(this.getNextVisibleSibling(this.highlightedModelEntry)) this.modelFilter.select() } - + selectFirstFile() { - this.selectModelEntry(this.modelList.querySelector('.model-file')) - this.highlightedModelEntry.scrollIntoView({block: 'nearest'}) + this.selectModelEntry(this.modelList.querySelector(".model-file")) + this.highlightedModelEntry.scrollIntoView({ block: "nearest" }) this.modelFilter.select() } - + selectLastFile() { - const elems = this.modelList.querySelectorAll('.model-file:last-child') - this.selectModelEntry(elems[elems.length -1]) + const elems = this.modelList.querySelectorAll(".model-file:last-child") + this.selectModelEntry(elems[elems.length - 1]) this.modelFilter.select() } @@ -198,57 +218,57 @@ class ModelDropdown } validEntrySelected() { - return (this.modelNoResult.style.display === 'none') + return this.modelNoResult.style.display === "none" } - + processKey(e) { switch (e.key) { - case 'Escape': + case "Escape": e.preventDefault() this.resetSelection() break - case 'Enter': + case "Enter": e.preventDefault() if (this.validEntrySelected()) { - if (this.modelList.style.display != 'block') { + if (this.modelList.style.display != "block") { this.showModelList() - } - else - { - this.saveCurrentSelection(this.highlightedModelEntry, this.highlightedModelEntry.innerText, this.highlightedModelEntry.dataset.path) + } else { + this.saveCurrentSelection( + this.highlightedModelEntry, + this.highlightedModelEntry.innerText, + this.highlightedModelEntry.dataset.path + ) this.hideModelList() this.showAllEntries() } this.modelFilter.focus() - } - else - { + } else { this.resetSelection() } break - case 'ArrowUp': + case "ArrowUp": e.preventDefault() if (this.validEntrySelected()) { this.selectPreviousFile() } break - case 'ArrowDown': + case "ArrowDown": e.preventDefault() if (this.validEntrySelected()) { this.selectNextFile() } break - case 'ArrowLeft': - if (this.modelList.style.display != 'block') { + case "ArrowLeft": + if (this.modelList.style.display != "block") { e.preventDefault() } break - case 'ArrowRight': - if (this.modelList.style.display != 'block') { + case "ArrowRight": + if (this.modelList.style.display != "block") { e.preventDefault() } break - case 'PageUp': + case "PageUp": e.preventDefault() if (this.validEntrySelected()) { this.selectPreviousFile() @@ -261,7 +281,7 @@ class ModelDropdown this.selectPreviousFile() } break - case 'PageDown': + case "PageDown": e.preventDefault() if (this.validEntrySelected()) { this.selectNextFile() @@ -274,201 +294,195 @@ class ModelDropdown this.selectNextFile() } break - case 'Home': + case "Home": //if (this.modelList.style.display != 'block') { - e.preventDefault() - if (this.validEntrySelected()) { - this.selectFirstFile() - } + e.preventDefault() + if (this.validEntrySelected()) { + this.selectFirstFile() + } //} break - case 'End': + case "End": //if (this.modelList.style.display != 'block') { - e.preventDefault() - if (this.validEntrySelected()) { - this.selectLastFile() - } + e.preventDefault() + if (this.validEntrySelected()) { + this.selectLastFile() + } //} break default: - //console.log(e.key) + //console.log(e.key) } } - + modelListFocus() { this.selectEntry() this.showAllEntries() } - + showModelList() { - this.modelList.style.display = 'block' + this.modelList.style.display = "block" this.selectEntry() this.showAllEntries() //this.modelFilter.value = '' this.modelFilter.select() // preselect the entire string so user can just start typing. this.modelFilter.focus() - this.modelFilter.style.cursor = 'auto' + this.modelFilter.style.cursor = "auto" } - + hideModelList() { - this.modelList.style.display = 'none' + this.modelList.style.display = "none" this.modelFilter.value = this.currentSelection.value - this.modelFilter.style.cursor = '' + this.modelFilter.style.cursor = "" } - + toggleModelList(e) { e.preventDefault() if (!this.modelFilter.disabled) { - if (this.modelList.style.display != 'block') { + if (this.modelList.style.display != "block") { this.showModelList() - } - else - { + } else { this.hideModelList() this.modelFilter.select() } } } - + selectEntry(path) { if (path !== undefined) { - const entries = this.modelElements; + const entries = this.modelElements for (const elem of entries) { if (elem.dataset.path == path) { this.saveCurrentSelection(elem, elem.innerText, elem.dataset.path) this.highlightedModelEntry = elem - elem.scrollIntoView({block: 'nearest'}) + elem.scrollIntoView({ block: "nearest" }) break } } } - + if (this.currentSelection.elem !== undefined) { // select the previous element if (this.highlightedModelEntry !== undefined && this.highlightedModelEntry != this.currentSelection.elem) { - this.highlightedModelEntry.classList.remove('selected') + this.highlightedModelEntry.classList.remove("selected") } - this.currentSelection.elem.classList.add('selected') + this.currentSelection.elem.classList.add("selected") this.highlightedModelEntry = this.currentSelection.elem - this.currentSelection.elem.scrollIntoView({block: 'nearest'}) - } - else - { + this.currentSelection.elem.scrollIntoView({ block: "nearest" }) + } else { this.selectFirstFile() } } - + highlightModelAtPosition(e) { let elem = document.elementFromPoint(e.clientX, e.clientY) - - if (elem.classList.contains('model-file')) { + + if (elem.classList.contains("model-file")) { this.highlightModel(elem) } } - + highlightModel(elem) { - if (elem.classList.contains('model-file')) { + if (elem.classList.contains("model-file")) { if (this.highlightedModelEntry !== undefined && this.highlightedModelEntry != elem) { - this.highlightedModelEntry.classList.remove('selected') + this.highlightedModelEntry.classList.remove("selected") } - elem.classList.add('selected') + elem.classList.add("selected") this.highlightedModelEntry = elem } } - + showAllEntries() { - this.modelList.querySelectorAll('li').forEach(function(li) { - if (li.id !== 'model-no-result') { - li.style.display = 'list-item' + this.modelList.querySelectorAll("li").forEach(function(li) { + if (li.id !== "model-no-result") { + li.style.display = "list-item" } }) - this.modelNoResult.style.display = 'none' + this.modelNoResult.style.display = "none" } - + filterList(e) { const filter = this.modelFilter.value.toLowerCase() let found = false let showAllChildren = false - - this.modelList.querySelectorAll('li').forEach(function(li) { - if (li.classList.contains('model-folder')) { + + this.modelList.querySelectorAll("li").forEach(function(li) { + if (li.classList.contains("model-folder")) { showAllChildren = false } - if (filter == '') { - li.style.display = 'list-item' + if (filter == "") { + li.style.display = "list-item" found = true } else if (showAllChildren || li.textContent.toLowerCase().match(filter)) { - li.style.display = 'list-item' - if (li.classList.contains('model-folder') && li.firstChild.textContent.toLowerCase().match(filter)) { + li.style.display = "list-item" + if (li.classList.contains("model-folder") && li.firstChild.textContent.toLowerCase().match(filter)) { showAllChildren = true } found = true } else { - li.style.display = 'none' + li.style.display = "none" } }) - + if (found) { - this.modelResult.style.display = 'list-item' - this.modelNoResult.style.display = 'none' - const elem = this.getNextVisibleSibling(this.modelList.querySelector('.model-file')) + this.modelResult.style.display = "list-item" + this.modelNoResult.style.display = "none" + const elem = this.getNextVisibleSibling(this.modelList.querySelector(".model-file")) this.highlightModel(elem) - elem.scrollIntoView({block: 'nearest'}) + elem.scrollIntoView({ block: "nearest" }) + } else { + this.modelResult.style.display = "none" + this.modelNoResult.style.display = "list-item" } - else - { - this.modelResult.style.display = 'none' - this.modelNoResult.style.display = 'list-item' - } - this.modelList.style.display = 'block' + this.modelList.style.display = "block" } /* MODEL LOADER */ getElementDimensions(element) { // Clone the element const clone = element.cloneNode(true) - + // Copy the styles of the original element to the cloned element const originalStyles = window.getComputedStyle(element) for (let i = 0; i < originalStyles.length; i++) { const property = originalStyles[i] clone.style[property] = originalStyles.getPropertyValue(property) } - + // Set its visibility to hidden and display to inline-block clone.style.visibility = "hidden" clone.style.display = "inline-block" - + // Put the cloned element next to the original element element.parentNode.insertBefore(clone, element.nextSibling) - + // Get its width and height const width = clone.offsetWidth const height = clone.offsetHeight - + // Remove it from the DOM clone.remove() - + // Return its width and height return { width, height } } - + /** - * @param {Array} models + * @param {Array} models */ sortStringArray(models) { - models.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })) + models.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" })) } populateModels() { this.activeModel = this.modelFilter.dataset.path - - this.currentSelection = { elem: undefined, value: '', path: ''} + + this.currentSelection = { elem: undefined, value: "", path: "" } this.highlightedModelEntry = undefined this.flatModelList = [] - if(this.modelList !== undefined) { + if (this.modelList !== undefined) { this.modelList.remove() this.modelFilterArrow.remove() } @@ -478,39 +492,39 @@ class ModelDropdown createDropdown() { // create dropdown entries let rootModelList = this.createRootModelList(this.inputModels) - this.modelFilter.insertAdjacentElement('afterend', rootModelList) + this.modelFilter.insertAdjacentElement("afterend", rootModelList) this.modelFilter.insertAdjacentElement( - 'afterend', - createElement( - 'i', - { id: `${this.modelFilter.id}-model-filter-arrow` }, - ['model-selector-arrow', 'fa-solid', 'fa-angle-down'], - ), + "afterend", + createElement("i", { id: `${this.modelFilter.id}-model-filter-arrow` }, [ + "model-selector-arrow", + "fa-solid", + "fa-angle-down", + ]) ) - this.modelFilter.classList.add('model-selector') + this.modelFilter.classList.add("model-selector") this.modelFilterArrow = document.querySelector(`#${this.modelFilter.id}-model-filter-arrow`) if (this.modelFilterArrow) { - this.modelFilterArrow.style.color = this.modelFilter.disabled ? 'dimgray' : '' + this.modelFilterArrow.style.color = this.modelFilter.disabled ? "dimgray" : "" } this.modelList = document.querySelector(`#${this.modelFilter.id}-model-list`) this.modelResult = document.querySelector(`#${this.modelFilter.id}-model-result`) this.modelNoResult = document.querySelector(`#${this.modelFilter.id}-model-no-result`) - + if (this.modelFilterInitialized !== true) { - this.modelFilter.addEventListener('input', this.bind(this.filterList, this)) - this.modelFilter.addEventListener('focus', this.bind(this.modelListFocus, this)) - this.modelFilter.addEventListener('blur', this.bind(this.hideModelList, this)) - this.modelFilter.addEventListener('click', this.bind(this.showModelList, this)) - this.modelFilter.addEventListener('keydown', this.bind(this.processKey, this)) + this.modelFilter.addEventListener("input", this.bind(this.filterList, this)) + this.modelFilter.addEventListener("focus", this.bind(this.modelListFocus, this)) + this.modelFilter.addEventListener("blur", this.bind(this.hideModelList, this)) + this.modelFilter.addEventListener("click", this.bind(this.showModelList, this)) + this.modelFilter.addEventListener("keydown", this.bind(this.processKey, this)) this.modelFilterInitialized = true } - this.modelFilterArrow.addEventListener('mousedown', this.bind(this.toggleModelList, this)) - this.modelList.addEventListener('mousemove', this.bind(this.highlightModelAtPosition, this)) - this.modelList.addEventListener('mousedown', this.bind(this.processClick, this)) + this.modelFilterArrow.addEventListener("mousedown", this.bind(this.toggleModelList, this)) + this.modelList.addEventListener("mousemove", this.bind(this.highlightModelAtPosition, this)) + this.modelList.addEventListener("mousedown", this.bind(this.processClick, this)) let mf = this.modelFilter - this.modelFilter.addEventListener('focus', function() { + this.modelFilter.addEventListener("focus", function() { let modelFilterStyle = window.getComputedStyle(mf) rootModelList.style.minWidth = modelFilterStyle.width }) @@ -520,74 +534,66 @@ class ModelDropdown /** * @param {Array { + modelTree.forEach((model) => { if (Array.isArray(model)) { const [childFolderName, childModels] = model foldersMap.set( childFolderName, - this.createModelNodeList( - `${folderName || ''}/${childFolderName}`, - childModels, - false, - ), + this.createModelNodeList(`${folderName || ""}/${childFolderName}`, childModels, false) ) } else { - const classes = ['model-file'] + const classes = ["model-file"] if (isRootFolder) { - classes.push('in-root-folder') + classes.push("in-root-folder") } // Remove the leading slash from the model path const fullPath = folderName ? `${folderName.substring(1)}/${model}` : model modelsMap.set( model, - createElement( - 'li', - { 'data-path': fullPath }, - classes, - [ - createElement('i', undefined, ['fa-regular', 'fa-file', 'icon']), - model, - ], - ), + createElement("li", { "data-path": fullPath }, classes, [ + createElement("i", undefined, ["fa-regular", "fa-file", "icon"]), + model, + ]) ) } }) const childFolderNames = Array.from(foldersMap.keys()) - this.sortStringArray(childFolderNames) - const folderElements = childFolderNames.map(name => foldersMap.get(name)) + if (this.sorted) { + this.sortStringArray(childFolderNames) + } + const folderElements = childFolderNames.map((name) => foldersMap.get(name)) const modelNames = Array.from(modelsMap.keys()) - this.sortStringArray(modelNames) - const modelElements = modelNames.map(name => modelsMap.get(name)) + if (this.sorted) { + this.sortStringArray(modelNames) + } + const modelElements = modelNames.map((name) => modelsMap.get(name)) if (modelElements.length && folderName) { listElement.appendChild( createElement( - 'li', + "li", undefined, - ['model-folder'], - [ - createElement('i', undefined, ['fa-regular', 'fa-folder-open', 'icon']), - folderName.substring(1), - ], + ["model-folder"], + [createElement("i", undefined, ["fa-regular", "fa-folder-open", "icon"]), folderName.substring(1)] ) ) } // const allModelElements = isRootFolder ? [...folderElements, ...modelElements] : [...modelElements, ...folderElements] const allModelElements = [...modelElements, ...folderElements] - allModelElements.forEach(e => listElement.appendChild(e)) + allModelElements.forEach((e) => listElement.appendChild(e)) return listElement } @@ -596,37 +602,21 @@ class ModelDropdown * @returns {HTMLElement} */ createRootModelList(modelTree) { - const rootList = createElement( - 'ul', - { id: `${this.modelFilter.id}-model-list` }, - ['model-list'], - ) + const rootList = createElement("ul", { id: `${this.modelFilter.id}-model-list` }, ["model-list"]) rootList.appendChild( - createElement( - 'li', - { id: `${this.modelFilter.id}-model-no-result` }, - ['model-no-result'], - 'No result' - ), + createElement("li", { id: `${this.modelFilter.id}-model-no-result` }, ["model-no-result"], "No result") ) if (this.noneEntry) { rootList.appendChild( - createElement( - 'li', - { 'data-path': '' }, - ['model-file', 'in-root-folder'], - this.noneEntry, - ), + createElement("li", { "data-path": "" }, ["model-file", "in-root-folder"], this.noneEntry) ) } if (modelTree.length > 0) { - const containerListItem = createElement( - 'li', - { id: `${this.modelFilter.id}-model-result` }, - ['model-result'], - ) + const containerListItem = createElement("li", { id: `${this.modelFilter.id}-model-result` }, [ + "model-result", + ]) //console.log(containerListItem) containerListItem.appendChild(this.createModelNodeList(undefined, modelTree, true)) rootList.appendChild(containerListItem) @@ -640,13 +630,16 @@ class ModelDropdown async function getModels() { try { modelsCache = await SD.getModels() - modelsOptions = modelsCache['options'] + modelsOptions = modelsCache["options"] if ("scan-error" in modelsCache) { // let previewPane = document.getElementById('tab-content-wrapper') - let previewPane = document.getElementById('preview') - previewPane.style.background="red" - previewPane.style.textAlign="center" - previewPane.innerHTML = '

    🔥Malware alert!🔥

    The file ' + modelsCache['scan-error'] + ' in your models/stable-diffusion folder is probably malware infected.

    Please delete this file from the folder before proceeding!

    After deleting the file, reload this page.

    ' + let previewPane = document.getElementById("preview") + previewPane.style.background = "red" + previewPane.style.textAlign = "center" + previewPane.innerHTML = + "

    🔥Malware alert!🔥

    The file " + + modelsCache["scan-error"] + + ' in your models/stable-diffusion folder is probably malware infected.

    Please delete this file from the folder before proceeding!

    After deleting the file, reload this page.

    ' makeImageBtn.disabled = true } @@ -667,11 +660,11 @@ async function getModels() { */ // notify ModelDropdown objects to refresh - document.dispatchEvent(new Event('refreshModels')) + document.dispatchEvent(new Event("refreshModels")) } catch (e) { - console.log('get models error', e) + console.log("get models error", e) } } // reload models button -document.querySelector('#reload-models').addEventListener('click', getModels) +document.querySelector("#reload-models").addEventListener("click", getModels) diff --git a/ui/media/js/themes.js b/ui/media/js/themes.js index d8577d68..a541eb44 100644 --- a/ui/media/js/themes.js +++ b/ui/media/js/themes.js @@ -1,82 +1,85 @@ -const themeField = document.getElementById("theme"); -var DEFAULT_THEME = {}; -var THEMES = []; // initialized in initTheme from data in css +const themeField = document.getElementById("theme") +var DEFAULT_THEME = {} +var THEMES = [] // initialized in initTheme from data in css function getThemeName(theme) { - theme = theme.replace("theme-", ""); - theme = theme.split("-").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); - return theme; + theme = theme.replace("theme-", "") + theme = theme + .split("-") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" ") + return theme } // init themefield function initTheme() { Array.from(document.styleSheets) - .filter(sheet => sheet.href?.startsWith(window.location.origin)) - .flatMap(sheet => Array.from(sheet.cssRules)) - .forEach(rule => { - var selector = rule.selectorText; + .filter((sheet) => sheet.href?.startsWith(window.location.origin)) + .flatMap((sheet) => Array.from(sheet.cssRules)) + .forEach((rule) => { + var selector = rule.selectorText if (selector && selector.startsWith(".theme-") && !selector.includes(" ")) { - if (DEFAULT_THEME) { // re-add props that dont change (css needs this so they update correctly) + if (DEFAULT_THEME) { + // re-add props that dont change (css needs this so they update correctly) Array.from(DEFAULT_THEME.rule.style) - .filter(cssVariable => !Array.from(rule.style).includes(cssVariable)) - .forEach(cssVariable => { - rule.style.setProperty(cssVariable, DEFAULT_THEME.rule.style.getPropertyValue(cssVariable)); - }); + .filter((cssVariable) => !Array.from(rule.style).includes(cssVariable)) + .forEach((cssVariable) => { + rule.style.setProperty(cssVariable, DEFAULT_THEME.rule.style.getPropertyValue(cssVariable)) + }) } - var theme_key = selector.substring(1); + var theme_key = selector.substring(1) THEMES.push({ key: theme_key, name: getThemeName(theme_key), - rule: rule + rule: rule, }) } if (selector && selector == ":root") { DEFAULT_THEME = { key: "theme-default", name: "Default", - rule: rule - }; + rule: rule, + } } - }); - - THEMES.forEach(theme => { - var new_option = document.createElement("option"); - new_option.setAttribute("value", theme.key); - new_option.innerText = theme.name; - themeField.appendChild(new_option); - }); + }) + + THEMES.forEach((theme) => { + var new_option = document.createElement("option") + new_option.setAttribute("value", theme.key) + new_option.innerText = theme.name + themeField.appendChild(new_option) + }) - // setup the style transitions a second after app initializes, so initial style is instant setTimeout(() => { - var body = document.querySelector("body"); - var style = document.createElement('style'); - style.innerHTML = "* { transition: background 0.5s, color 0.5s, background-color 0.5s; }"; - body.appendChild(style); - }, 1000); + var body = document.querySelector("body") + var style = document.createElement("style") + style.innerHTML = "* { transition: background 0.5s, color 0.5s, background-color 0.5s; }" + body.appendChild(style) + }, 1000) } -initTheme(); +initTheme() function themeFieldChanged() { - var theme_key = themeField.value; + var theme_key = themeField.value - var body = document.querySelector("body"); - body.classList.remove(...THEMES.map(theme => theme.key)); - body.classList.add(theme_key); - - // + var body = document.querySelector("body") + body.classList.remove(...THEMES.map((theme) => theme.key)) + body.classList.add(theme_key) - body.style = ""; - var theme = THEMES.find(t => t.key == theme_key); + // + + body.style = "" + var theme = THEMES.find((t) => t.key == theme_key) let borderColor = undefined if (theme) { - borderColor = theme.rule.style.getPropertyValue('--input-border-color').trim() - if (!borderColor.startsWith('#')) { - borderColor = theme.rule.style.getPropertyValue('--theme-color-fallback') + borderColor = theme.rule.style.getPropertyValue("--input-border-color").trim() + if (!borderColor.startsWith("#")) { + borderColor = theme.rule.style.getPropertyValue("--theme-color-fallback") } } else { - borderColor = DEFAULT_THEME.rule.style.getPropertyValue('--theme-color-fallback') + borderColor = DEFAULT_THEME.rule.style.getPropertyValue("--theme-color-fallback") } document.querySelector('meta[name="theme-color"]').setAttribute("content", borderColor) } -themeField.addEventListener('change', themeFieldChanged); +themeField.addEventListener("change", themeFieldChanged) diff --git a/ui/media/js/utils.js b/ui/media/js/utils.js index 6eb0d643..4c65bd00 100644 --- a/ui/media/js/utils.js +++ b/ui/media/js/utils.js @@ -1,4 +1,4 @@ -"use strict"; +"use strict" // https://gomakethings.com/finding-the-next-and-previous-sibling-elements-that-match-a-selector-with-vanilla-js/ function getNextSibling(elem, selector) { @@ -20,33 +20,34 @@ function getNextSibling(elem, selector) { } } - /* Panel Stuff */ // true = open -let COLLAPSIBLES_INITIALIZED = false; -const COLLAPSIBLES_KEY = "collapsibles"; -const COLLAPSIBLE_PANELS = []; // filled in by createCollapsibles with all the elements matching .collapsible +let COLLAPSIBLES_INITIALIZED = false +const COLLAPSIBLES_KEY = "collapsibles" +const COLLAPSIBLE_PANELS = [] // filled in by createCollapsibles with all the elements matching .collapsible // on-init call this for any panels that are marked open function toggleCollapsible(element) { - const collapsibleHeader = element.querySelector(".collapsible"); - const handle = element.querySelector(".collapsible-handle"); + const collapsibleHeader = element.querySelector(".collapsible") + const handle = element.querySelector(".collapsible-handle") collapsibleHeader.classList.toggle("active") - let content = getNextSibling(collapsibleHeader, '.collapsible-content') + let content = getNextSibling(collapsibleHeader, ".collapsible-content") if (!collapsibleHeader.classList.contains("active")) { content.style.display = "none" - if (handle != null) { // render results don't have a handle - handle.innerHTML = '➕' // plus + if (handle != null) { + // render results don't have a handle + handle.innerHTML = "➕" // plus } } else { content.style.display = "block" - if (handle != null) { // render results don't have a handle - handle.innerHTML = '➖' // minus + if (handle != null) { + // render results don't have a handle + handle.innerHTML = "➖" // minus } } - document.dispatchEvent(new CustomEvent('collapsibleClick', { detail: collapsibleHeader })) - + document.dispatchEvent(new CustomEvent("collapsibleClick", { detail: collapsibleHeader })) + if (COLLAPSIBLES_INITIALIZED && COLLAPSIBLE_PANELS.includes(element)) { saveCollapsibles() } @@ -54,7 +55,7 @@ function toggleCollapsible(element) { function saveCollapsibles() { let values = {} - COLLAPSIBLE_PANELS.forEach(element => { + COLLAPSIBLE_PANELS.forEach((element) => { let value = element.querySelector(".collapsible").className.indexOf("active") !== -1 values[element.id] = value }) @@ -72,31 +73,31 @@ function createCollapsibles(node) { if (save && c.parentElement.id) { COLLAPSIBLE_PANELS.push(c.parentElement) } - let handle = document.createElement('span') - handle.className = 'collapsible-handle' + let handle = document.createElement("span") + handle.className = "collapsible-handle" if (c.classList.contains("active")) { - handle.innerHTML = '➖' // minus + handle.innerHTML = "➖" // minus } else { - handle.innerHTML = '➕' // plus + handle.innerHTML = "➕" // plus } c.insertBefore(handle, c.firstChild) - c.addEventListener('click', function() { + c.addEventListener("click", function() { toggleCollapsible(c.parentElement) }) }) if (save) { let saved = localStorage.getItem(COLLAPSIBLES_KEY) - if (!saved) { - saved = tryLoadOldCollapsibles(); + if (!saved) { + saved = tryLoadOldCollapsibles() } if (!saved) { saveCollapsibles() saved = localStorage.getItem(COLLAPSIBLES_KEY) } let values = JSON.parse(saved) - COLLAPSIBLE_PANELS.forEach(element => { + COLLAPSIBLE_PANELS.forEach((element) => { let value = element.querySelector(".collapsible").className.indexOf("active") !== -1 if (values[element.id] != value) { toggleCollapsible(element) @@ -108,24 +109,24 @@ function createCollapsibles(node) { function tryLoadOldCollapsibles() { const old_map = { - "advancedPanelOpen": "editor-settings", - "modifiersPanelOpen": "editor-modifiers", - "negativePromptPanelOpen": "editor-inputs-prompt" - }; + advancedPanelOpen: "editor-settings", + modifiersPanelOpen: "editor-modifiers", + negativePromptPanelOpen: "editor-inputs-prompt", + } if (localStorage.getItem(Object.keys(old_map)[0])) { - let result = {}; - Object.keys(old_map).forEach(key => { - const value = localStorage.getItem(key); + let result = {} + Object.keys(old_map).forEach((key) => { + const value = localStorage.getItem(key) if (value !== null) { - result[old_map[key]] = (value == true || value == "true") + result[old_map[key]] = value == true || value == "true" localStorage.removeItem(key) } - }); + }) result = JSON.stringify(result) localStorage.setItem(COLLAPSIBLES_KEY, result) return result } - return null; + return null } function permute(arr) { @@ -134,10 +135,12 @@ function permute(arr) { let n_permutations = Math.pow(2, n) for (let i = 0; i < n_permutations; i++) { let perm = [] - let mask = Number(i).toString(2).padStart(n, '0') + let mask = Number(i) + .toString(2) + .padStart(n, "0") for (let idx = 0; idx < mask.length; idx++) { - if (mask[idx] === '1' && arr[idx].trim() !== '') { + if (mask[idx] === "1" && arr[idx].trim() !== "") { perm.push(arr[idx]) } } @@ -150,25 +153,29 @@ function permute(arr) { return permutations } +function permuteNumber(arr) { + return Math.pow(2, arr.length) +} + // https://stackoverflow.com/a/8212878 function millisecondsToStr(milliseconds) { - function numberEnding (number) { - return (number > 1) ? 's' : '' + function numberEnding(number) { + return number > 1 ? "s" : "" } let temp = Math.floor(milliseconds / 1000) let hours = Math.floor((temp %= 86400) / 3600) - let s = '' + let s = "" if (hours) { - s += hours + ' hour' + numberEnding(hours) + ' ' + s += hours + " hour" + numberEnding(hours) + " " } let minutes = Math.floor((temp %= 3600) / 60) if (minutes) { - s += minutes + ' minute' + numberEnding(minutes) + ' ' + s += minutes + " minute" + numberEnding(minutes) + " " } let seconds = temp % 60 if (!hours && minutes < 4 && seconds) { - s += seconds + ' second' + numberEnding(seconds) + s += seconds + " second" + numberEnding(seconds) } return s @@ -176,101 +183,82 @@ function millisecondsToStr(milliseconds) { // https://rosettacode.org/wiki/Brace_expansion#JavaScript function BraceExpander() { - 'use strict' + "use strict" // Index of any closing brace matching the opening // brace at iPosn, // with the indices of any immediately-enclosed commas. function bracePair(tkns, iPosn, iNest, lstCommas) { - if (iPosn >= tkns.length || iPosn < 0) return null; + if (iPosn >= tkns.length || iPosn < 0) return null let t = tkns[iPosn], - n = (t === '{') ? ( - iNest + 1 - ) : (t === '}' ? ( - iNest - 1 - ) : iNest), - lst = (t === ',' && iNest === 1) ? ( - lstCommas.concat(iPosn) - ) : lstCommas; + n = t === "{" ? iNest + 1 : t === "}" ? iNest - 1 : iNest, + lst = t === "," && iNest === 1 ? lstCommas.concat(iPosn) : lstCommas - return n ? bracePair(tkns, iPosn + 1, n, lst) : { - close: iPosn, - commas: lst - }; + return n + ? bracePair(tkns, iPosn + 1, n, lst) + : { + close: iPosn, + commas: lst, + } } // Parse of a SYNTAGM subtree function andTree(dctSofar, tkns) { - if (!tkns.length) return [dctSofar, []]; - - let dctParse = dctSofar ? dctSofar : { - fn: and, - args: [] - }, + if (!tkns.length) return [dctSofar, []] + let dctParse = dctSofar + ? dctSofar + : { + fn: and, + args: [], + }, head = tkns[0], tail = head ? tkns.slice(1) : [], + dctBrace = head === "{" ? bracePair(tkns, 0, 0, []) : null, + lstOR = dctBrace && dctBrace.close && dctBrace.commas.length ? splitAt(dctBrace.close + 1, tkns) : null - dctBrace = head === '{' ? bracePair( - tkns, 0, 0, [] - ) : null, - - lstOR = dctBrace && ( - dctBrace.close - ) && dctBrace.commas.length ? ( - splitAt(dctBrace.close + 1, tkns) - ) : null; - - return andTree({ - fn: and, - args: dctParse.args.concat( - lstOR ? ( - orTree(dctParse, lstOR[0], dctBrace.commas) - ) : head - ) - }, lstOR ? ( - lstOR[1] - ) : tail); + return andTree( + { + fn: and, + args: dctParse.args.concat(lstOR ? orTree(dctParse, lstOR[0], dctBrace.commas) : head), + }, + lstOR ? lstOR[1] : tail + ) } // Parse of a PARADIGM subtree function orTree(dctSofar, tkns, lstCommas) { - if (!tkns.length) return [dctSofar, []]; - let iLast = lstCommas.length; + if (!tkns.length) return [dctSofar, []] + let iLast = lstCommas.length return { fn: or, - args: splitsAt( - lstCommas, tkns - ).map(function (x, i) { - let ts = x.slice( - 1, i === iLast ? ( - -1 - ) : void 0 - ); + args: splitsAt(lstCommas, tkns) + .map(function(x, i) { + let ts = x.slice(1, i === iLast ? -1 : void 0) - return ts.length ? ts : ['']; - }).map(function (ts) { - return ts.length > 1 ? ( - andTree(null, ts)[0] - ) : ts[0]; - }) - }; + return ts.length ? ts : [""] + }) + .map(function(ts) { + return ts.length > 1 ? andTree(null, ts)[0] : ts[0] + }), + } } // List of unescaped braces and commas, and remaining strings function tokens(str) { // Filter function excludes empty splitting artefacts - let toS = function (x) { - return x.toString(); - }; + let toS = function(x) { + return x.toString() + } - return str.split(/(\\\\)/).filter(toS).reduce(function (a, s) { - return a.concat(s.charAt(0) === '\\' ? s : s.split( - /(\\*[{,}])/ - ).filter(toS)); - }, []); + return str + .split(/(\\\\)/) + .filter(toS) + .reduce(function(a, s) { + return a.concat(s.charAt(0) === "\\" ? s : s.split(/(\\*[{,}])/).filter(toS)) + }, []) } // PARSE TREE OPERATOR (1 of 2) @@ -278,76 +266,75 @@ function BraceExpander() { function and(args) { let lng = args.length, head = lng ? args[0] : null, - lstHead = "string" === typeof head ? ( - [head] - ) : head; + lstHead = "string" === typeof head ? [head] : head - return lng ? ( - 1 < lng ? lstHead.reduce(function (a, h) { - return a.concat( - and(args.slice(1)).map(function (t) { - return h + t; - }) - ); - }, []) : lstHead - ) : []; + return lng + ? 1 < lng + ? lstHead.reduce(function(a, h) { + return a.concat( + and(args.slice(1)).map(function(t) { + return h + t + }) + ) + }, []) + : lstHead + : [] } // PARSE TREE OPERATOR (2 of 2) // Each option flattened function or(args) { - return args.reduce(function (a, b) { - return a.concat(b); - }, []); + return args.reduce(function(a, b) { + return a.concat(b) + }, []) } // One list split into two (first sublist length n) function splitAt(n, lst) { - return n < lst.length + 1 ? [ - lst.slice(0, n), lst.slice(n) - ] : [lst, []]; + return n < lst.length + 1 ? [lst.slice(0, n), lst.slice(n)] : [lst, []] } // One list split into several (sublist lengths [n]) function splitsAt(lstN, lst) { - return lstN.reduceRight(function (a, x) { - return splitAt(x, a[0]).concat(a.slice(1)); - }, [lst]); + return lstN.reduceRight( + function(a, x) { + return splitAt(x, a[0]).concat(a.slice(1)) + }, + [lst] + ) } // Value of the parse tree function evaluated(e) { - return typeof e === 'string' ? e : - e.fn(e.args.map(evaluated)); + return typeof e === "string" ? e : e.fn(e.args.map(evaluated)) } // JSON prettyprint (for parse tree, token list etc) function pp(e) { - return JSON.stringify(e, function (k, v) { - return typeof v === 'function' ? ( - '[function ' + v.name + ']' - ) : v; - }, 2) + return JSON.stringify( + e, + function(k, v) { + return typeof v === "function" ? "[function " + v.name + "]" : v + }, + 2 + ) } - // ----------------------- MAIN ------------------------ // s -> [s] this.expand = function(s) { // BRACE EXPRESSION PARSED - let dctParse = andTree(null, tokens(s))[0]; + let dctParse = andTree(null, tokens(s))[0] // ABSTRACT SYNTAX TREE LOGGED // console.log(pp(dctParse)); // AST EVALUATED TO LIST OF STRINGS - return evaluated(dctParse); + return evaluated(dctParse) } - } - /** Pause the execution of an async function until timer elapse. * @Returns a promise that will resolve after the specified timeout. */ @@ -360,12 +347,12 @@ function asyncDelay(timeout) { function PromiseSource() { const srcPromise = new Promise((resolve, reject) => { Object.defineProperties(this, { - resolve: { value: resolve, writable: false } - , reject: { value: reject, writable: false } + resolve: { value: resolve, writable: false }, + reject: { value: reject, writable: false }, }) }) Object.defineProperties(this, { - promise: {value: makeQuerablePromise(srcPromise), writable: false} + promise: { value: makeQuerablePromise(srcPromise), writable: false }, }) } @@ -375,7 +362,7 @@ function PromiseSource() { * If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. * @Returns a promise that will resolve to func return value. */ -function debounce (func, wait, immediate) { +function debounce(func, wait, immediate) { if (typeof wait === "undefined") { wait = 40 } @@ -399,11 +386,11 @@ function debounce (func, wait, immediate) { } return function(...args) { const callNow = Boolean(immediate && !timeout) - const context = this; + const context = this if (timeout) { clearTimeout(timeout) } - timeout = setTimeout(function () { + timeout = setTimeout(function() { if (!immediate) { applyFn(context, args) } @@ -418,14 +405,14 @@ function debounce (func, wait, immediate) { } function preventNonNumericalInput(e) { - e = e || window.event; - let charCode = (typeof e.which == "undefined") ? e.keyCode : e.which; - let charStr = String.fromCharCode(charCode); - let re = e.target.getAttribute('pattern') || '^[0-9]+$' - re = new RegExp(re) + e = e || window.event + const charCode = typeof e.which == "undefined" ? e.keyCode : e.which + const charStr = String.fromCharCode(charCode) + const newInputValue = `${e.target.value}${charStr}` + const re = new RegExp(e.target.getAttribute("pattern") || "^[0-9]+$") - if (!charStr.match(re)) { - e.preventDefault(); + if (!re.test(charStr) && !re.test(newInputValue)) { + e.preventDefault() } } @@ -434,15 +421,15 @@ function preventNonNumericalInput(e) { * @Notes Allows unit testing and use of the engine outside of a browser. */ function getGlobal() { - if (typeof globalThis === 'object') { + if (typeof globalThis === "object") { return globalThis - } else if (typeof global === 'object') { + } else if (typeof global === "object") { return global - } else if (typeof self === 'object') { + } else if (typeof self === "object") { return self } try { - return Function('return this')() + return Function("return this")() } catch { // If the Function constructor fails, we're in a browser with eval disabled by CSP headers. return window @@ -453,18 +440,18 @@ function getGlobal() { * @Returns true if x is an Array or a TypedArray, false otherwise. */ function isArrayOrTypedArray(x) { - return Boolean(typeof x === 'object' && (Array.isArray(x) || (ArrayBuffer.isView(x) && !(x instanceof DataView)))) + return Boolean(typeof x === "object" && (Array.isArray(x) || (ArrayBuffer.isView(x) && !(x instanceof DataView)))) } function makeQuerablePromise(promise) { - if (typeof promise !== 'object') { - throw new Error('promise is not an object.') + if (typeof promise !== "object") { + throw new Error("promise is not an object.") } if (!(promise instanceof Promise)) { - throw new Error('Argument is not a promise.') + throw new Error("Argument is not a promise.") } // Don't modify a promise that's been already modified. - if ('isResolved' in promise || 'isRejected' in promise || 'isPending' in promise) { + if ("isResolved" in promise || "isRejected" in promise || "isPending" in promise) { return promise } let isPending = true @@ -473,13 +460,13 @@ function makeQuerablePromise(promise) { let isResolved = false let resolvedValue = undefined const qurPro = promise.then( - function(val){ + function(val) { isResolved = true isPending = false resolvedValue = val return val - } - , function(reason) { + }, + function(reason) { rejectReason = reason isRejected = true isPending = false @@ -487,46 +474,46 @@ function makeQuerablePromise(promise) { } ) Object.defineProperties(qurPro, { - 'isResolved': { - get: () => isResolved - } - , 'resolvedValue': { - get: () => resolvedValue - } - , 'isPending': { - get: () => isPending - } - , 'isRejected': { - get: () => isRejected - } - , 'rejectReason': { - get: () => rejectReason - } + isResolved: { + get: () => isResolved, + }, + resolvedValue: { + get: () => resolvedValue, + }, + isPending: { + get: () => isPending, + }, + isRejected: { + get: () => isRejected, + }, + rejectReason: { + get: () => rejectReason, + }, }) return qurPro } /* inserts custom html to allow prettifying of inputs */ function prettifyInputs(root_element) { - root_element.querySelectorAll(`input[type="checkbox"]`).forEach(element => { + root_element.querySelectorAll(`input[type="checkbox"]`).forEach((element) => { if (element.style.display === "none") { return } - var parent = element.parentNode; + var parent = element.parentNode if (!parent.classList.contains("input-toggle")) { - var wrapper = document.createElement("div"); - wrapper.classList.add("input-toggle"); - parent.replaceChild(wrapper, element); - wrapper.appendChild(element); - var label = document.createElement("label"); - label.htmlFor = element.id; - wrapper.appendChild(label); + var wrapper = document.createElement("div") + wrapper.classList.add("input-toggle") + parent.replaceChild(wrapper, element) + wrapper.appendChild(element) + var label = document.createElement("label") + label.htmlFor = element.id + wrapper.appendChild(label) } }) } class GenericEventSource { - #events = {}; + #events = {} #types = [] constructor(...eventsTypes) { if (Array.isArray(eventsTypes) && eventsTypes.length === 1 && Array.isArray(eventsTypes[0])) { @@ -541,7 +528,7 @@ class GenericEventSource { */ addEventListener(name, handler) { if (!this.#types.includes(name)) { - throw new Error('Invalid event name.') + throw new Error("Invalid event name.") } if (this.#events.hasOwnProperty(name)) { this.#events[name].push(handler) @@ -574,13 +561,15 @@ class GenericEventSource { if (evs.length <= 0) { return Promise.resolve() } - return Promise.allSettled(evs.map((callback) => { - try { - return Promise.resolve(callback.apply(SD, args)) - } catch (ex) { - return Promise.reject(ex) - } - })) + return Promise.allSettled( + evs.map((callback) => { + try { + return Promise.resolve(callback.apply(SD, args)) + } catch (ex) { + return Promise.reject(ex) + } + }) + ) } } @@ -590,7 +579,7 @@ class ServiceContainer { constructor(...servicesParams) { servicesParams.forEach(this.register.bind(this)) } - get services () { + get services() { return this.#services } get singletons() { @@ -598,54 +587,52 @@ class ServiceContainer { } register(params) { if (ServiceContainer.isConstructor(params)) { - if (typeof params.name !== 'string') { - throw new Error('params.name is not a string.') + if (typeof params.name !== "string") { + throw new Error("params.name is not a string.") } - params = {name:params.name, definition:params} + params = { name: params.name, definition: params } } - if (typeof params !== 'object') { - throw new Error('params is not an object.') + if (typeof params !== "object") { + throw new Error("params is not an object.") } - [ 'name', - 'definition', - ].forEach((key) => { + ;["name", "definition"].forEach((key) => { if (!(key in params)) { - console.error('Invalid service %o registration.', params) + console.error("Invalid service %o registration.", params) throw new Error(`params.${key} is not defined.`) } }) - const opts = {definition: params.definition} - if ('dependencies' in params) { + const opts = { definition: params.definition } + if ("dependencies" in params) { if (Array.isArray(params.dependencies)) { params.dependencies.forEach((dep) => { - if (typeof dep !== 'string') { - throw new Error('dependency name is not a string.') + if (typeof dep !== "string") { + throw new Error("dependency name is not a string.") } }) opts.dependencies = params.dependencies } else { - throw new Error('params.dependencies is not an array.') + throw new Error("params.dependencies is not an array.") } } if (params.singleton) { opts.singleton = true } this.#services.set(params.name, opts) - return Object.assign({name: params.name}, opts) + return Object.assign({ name: params.name }, opts) } get(name) { const ctorInfos = this.#services.get(name) if (!ctorInfos) { return } - if(!ServiceContainer.isConstructor(ctorInfos.definition)) { + if (!ServiceContainer.isConstructor(ctorInfos.definition)) { return ctorInfos.definition } - if(!ctorInfos.singleton) { + if (!ctorInfos.singleton) { return this._createInstance(ctorInfos) } const singletonInstance = this.#singletons.get(name) - if(singletonInstance) { + if (singletonInstance) { return singletonInstance } const newSingletonInstance = this._createInstance(ctorInfos) @@ -655,7 +642,7 @@ class ServiceContainer { _getResolvedDependencies(service) { let classDependencies = [] - if(service.dependencies) { + if (service.dependencies) { classDependencies = service.dependencies.map(this.get.bind(this)) } return classDependencies @@ -671,10 +658,14 @@ class ServiceContainer { } static isClass(definition) { - return typeof definition === 'function' && Boolean(definition.prototype) && definition.prototype.constructor === definition + return ( + typeof definition === "function" && + Boolean(definition.prototype) && + definition.prototype.constructor === definition + ) } static isConstructor(definition) { - return typeof definition === 'function' + return typeof definition === "function" } } @@ -683,23 +674,25 @@ class ServiceContainer { * @param {string} tag * @param {object} attributes * @param {string | Array} classes - * @param {string | HTMLElement | Array} + * @param {string | Node | Array} * @returns {HTMLElement} */ function createElement(tagName, attributes, classes, textOrElements) { const element = document.createElement(tagName) if (attributes) { Object.entries(attributes).forEach(([key, value]) => { - element.setAttribute(key, value) - }); + if (value !== undefined && value !== null) { + element.setAttribute(key, value) + } + }) } if (classes) { - (Array.isArray(classes) ? classes : [classes]).forEach(className => element.classList.add(className)) + ;(Array.isArray(classes) ? classes : [classes]).forEach((className) => element.classList.add(className)) } if (textOrElements) { const children = Array.isArray(textOrElements) ? textOrElements : [textOrElements] - children.forEach(textOrElem => { - if (textOrElem instanceof HTMLElement) { + children.forEach((textOrElem) => { + if (textOrElem instanceof Node) { element.appendChild(textOrElem) } else { element.appendChild(document.createTextNode(textOrElem)) @@ -708,3 +701,357 @@ function createElement(tagName, attributes, classes, textOrElements) { } return element } + +/** + * Add a listener for arrays + * @param {keyof Array} method + * @param {(args) => {}} callback + */ +Array.prototype.addEventListener = function(method, callback) { + const originalFunction = this[method] + if (originalFunction) { + this[method] = function() { + originalFunction.apply(this, arguments) + callback.apply(this, arguments) + } + } +} + +/** + * @typedef {object} TabOpenDetails + * @property {HTMLElement} contentElement + * @property {HTMLElement} labelElement + * @property {number} timesOpened + * @property {boolean} firstOpen + */ + +/** + * @typedef {object} CreateTabRequest + * @property {string} id + * @property {string | Node | (() => (string | Node))} label + * Label text or an HTML element + * @property {string} icon + * @property {string | Node | Promise | (() => (string | Node | Promise)) | undefined} content + * HTML string or HTML element + * @property {((TabOpenDetails, Event) => (undefined | string | Node | Promise)) | undefined} onOpen + * If an HTML string or HTML element is returned, then that will replace the tab content + * @property {string | undefined} css + */ + +/** + * @param {CreateTabRequest} request + */ +function createTab(request) { + if (!request?.id) { + console.error("createTab() error - id is required", Error().stack) + return + } + + if (!request.label) { + console.error("createTab() error - label is required", Error().stack) + return + } + + if (!request.icon) { + console.error("createTab() error - icon is required", Error().stack) + return + } + + if (!request.content && !request.onOpen) { + console.error("createTab() error - content or onOpen required", Error().stack) + return + } + + const tabsContainer = document.querySelector(".tab-container") + if (!tabsContainer) { + return + } + + const tabsContentWrapper = document.querySelector("#tab-content-wrapper") + if (!tabsContentWrapper) { + return + } + + // console.debug('creating tab: ', request) + + if (request.css) { + document + .querySelector("body") + .insertAdjacentElement( + "beforeend", + createElement("style", { id: `tab-${request.id}-css` }, undefined, request.css) + ) + } + + const label = typeof request.label === "function" ? request.label() : request.label + const labelElement = label instanceof Node ? label : createElement("span", undefined, undefined, label) + + const tab = createElement( + "span", + { id: `tab-${request.id}`, "data-times-opened": 0 }, + ["tab"], + createElement("span", undefined, undefined, [ + createElement("i", { style: "margin-right: 0.25em" }, [ + "fa-solid", + `${request.icon.startsWith("fa-") ? "" : "fa-"}${request.icon}`, + "icon", + ]), + labelElement, + ]) + ) + + tabsContainer.insertAdjacentElement("beforeend", tab) + + const wrapper = createElement("div", { id: request.id }, ["tab-content-inner"], "Loading..") + + const tabContent = createElement("div", { id: `tab-content-${request.id}` }, ["tab-content"], wrapper) + tabsContentWrapper.insertAdjacentElement("beforeend", tabContent) + + linkTabContents(tab) + + function replaceContent(resultFactory) { + if (resultFactory === undefined || resultFactory === null) { + return + } + const result = typeof resultFactory === "function" ? resultFactory() : resultFactory + if (result instanceof Promise) { + result.then(replaceContent) + } else if (result instanceof Node) { + wrapper.replaceChildren(result) + } else { + wrapper.innerHTML = result + } + } + + replaceContent(request.content) + + tab.addEventListener("click", (e) => { + const timesOpened = +(tab.dataset.timesOpened || 0) + 1 + tab.dataset.timesOpened = timesOpened + + if (request.onOpen) { + const result = request.onOpen( + { + contentElement: wrapper, + labelElement, + timesOpened, + firstOpen: timesOpened === 1, + }, + e + ) + + replaceContent(result) + } + }) +} + + +/* TOAST NOTIFICATIONS */ +function showToast(message, duration = 5000, error = false) { + const toast = document.createElement("div") + toast.classList.add("toast-notification") + if (error === true) { + toast.classList.add("toast-notification-error") + } + toast.innerHTML = message + document.body.appendChild(toast) + + // Set the position of the toast on the screen + const toastCount = document.querySelectorAll(".toast-notification").length + const toastHeight = toast.offsetHeight + const previousToastsHeight = Array.from(document.querySelectorAll(".toast-notification")) + .slice(0, -1) // exclude current toast + .reduce((totalHeight, toast) => totalHeight + toast.offsetHeight + 10, 0) // add 10 pixels for spacing + toast.style.bottom = `${10 + previousToastsHeight}px` + toast.style.right = "10px" + + // Delay the removal of the toast until animation has completed + const removeToast = () => { + toast.classList.add("hide") + const removeTimeoutId = setTimeout(() => { + toast.remove() + // Adjust the position of remaining toasts + const remainingToasts = document.querySelectorAll(".toast-notification") + const removedToastBottom = toast.getBoundingClientRect().bottom + + remainingToasts.forEach((toast) => { + if (toast.getBoundingClientRect().bottom < removedToastBottom) { + toast.classList.add("slide-down") + } + }) + + // Wait for the slide-down animation to complete + setTimeout(() => { + // Remove the slide-down class after the animation has completed + const slidingToasts = document.querySelectorAll(".slide-down") + slidingToasts.forEach((toast) => { + toast.classList.remove("slide-down") + }) + + // Adjust the position of remaining toasts again, in case there are multiple toasts being removed at once + const remainingToastsDown = document.querySelectorAll(".toast-notification") + let heightSoFar = 0 + remainingToastsDown.forEach((toast) => { + toast.style.bottom = `${10 + heightSoFar}px` + heightSoFar += toast.offsetHeight + 10 // add 10 pixels for spacing + }) + }, 0) // The duration of the slide-down animation (in milliseconds) + }, 500) + } + + // Remove the toast after specified duration + setTimeout(removeToast, duration) +} + +function alert(msg, title) { + title = title || "" + $.alert({ + theme: "modern", + title: title, + useBootstrap: false, + animateFromElement: false, + content: msg, + }) +} + +function confirm(msg, title, fn) { + title = title || "" + $.confirm({ + theme: "modern", + title: title, + useBootstrap: false, + animateFromElement: false, + content: msg, + buttons: { + yes: fn, + cancel: () => {}, + }, + }) +} + + +/* STORAGE MANAGEMENT */ +// Request persistent storage +async function requestPersistentStorage() { + if (navigator.storage && navigator.storage.persist) { + const isPersisted = await navigator.storage.persist(); + console.log(`Persisted storage granted: ${isPersisted}`); + } +} +requestPersistentStorage() + +// Open a database +async function openDB() { + return new Promise((resolve, reject) => { + let request = indexedDB.open("EasyDiffusionSettingsDatabase", 1); + request.addEventListener("upgradeneeded", function () { + let db = request.result; + db.createObjectStore("EasyDiffusionSettings", { keyPath: "id" }); + }); + request.addEventListener("success", function () { + resolve(request.result); + }); + request.addEventListener("error", function () { + reject(request.error); + }); + }); +} + +// Function to write data to the object store +async function setStorageData(key, value) { + return openDB().then(db => { + let tx = db.transaction("EasyDiffusionSettings", "readwrite"); + let store = tx.objectStore("EasyDiffusionSettings"); + let data = { id: key, value: value }; + return new Promise((resolve, reject) => { + let request = store.put(data); + request.addEventListener("success", function () { + resolve(request.result); + }); + request.addEventListener("error", function () { + reject(request.error); + }); + }); + }); +} + +// Function to retrieve data from the object store +async function getStorageData(key) { + return openDB().then(db => { + let tx = db.transaction("EasyDiffusionSettings", "readonly"); + let store = tx.objectStore("EasyDiffusionSettings"); + return new Promise((resolve, reject) => { + let request = store.get(key); + request.addEventListener("success", function () { + if (request.result) { + resolve(request.result.value); + } else { + // entry not found + resolve(); + } + }); + request.addEventListener("error", function () { + reject(request.error); + }); + }); + }); +} + +// indexedDB debug functions +async function getAllKeys() { + return openDB().then(db => { + let tx = db.transaction("EasyDiffusionSettings", "readonly"); + let store = tx.objectStore("EasyDiffusionSettings"); + let keys = []; + return new Promise((resolve, reject) => { + store.openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + keys.push(cursor.key); + cursor.continue(); + } else { + resolve(keys); + } + }; + }); + }); +} + +async function logAllStorageKeys() { + try { + let keys = await getAllKeys(); + console.log("All keys:", keys); + for (const k of keys) { + console.log(k, await getStorageData(k)) + } + } catch (error) { + console.error("Error retrieving keys:", error); + } +} + +// USE WITH CARE - THIS MAY DELETE ALL ENTRIES +async function deleteKeys(keyToDelete) { + let confirmationMessage = keyToDelete + ? `This will delete the template with key "${keyToDelete}". Continue?` + : "This will delete ALL templates. Continue?"; + if (confirm(confirmationMessage)) { + return openDB().then(db => { + let tx = db.transaction("EasyDiffusionSettings", "readwrite"); + let store = tx.objectStore("EasyDiffusionSettings"); + return new Promise((resolve, reject) => { + store.openCursor().onsuccess = function (event) { + let cursor = event.target.result; + if (cursor) { + if (!keyToDelete || cursor.key === keyToDelete) { + cursor.delete(); + } + cursor.continue(); + } else { + // refresh the dropdown and resolve + resolve(); + } + }; + }); + }); + } +} diff --git a/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/landscape-0.jpg b/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/landscape-0.jpg new file mode 100644 index 00000000..b37ec0ba Binary files /dev/null and b/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/landscape-0.jpg differ diff --git a/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/portrait-0.jpg b/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/portrait-0.jpg new file mode 100644 index 00000000..9569a884 Binary files /dev/null and b/ui/media/modifier-thumbnails/artist/by_zdzislaw_beksinski/portrait-0.jpg differ diff --git a/ui/modifiers.json b/ui/modifiers.json index 325e724e..6f93e29d 100644 --- a/ui/modifiers.json +++ b/ui/modifiers.json @@ -2428,6 +2428,19 @@ "path": "artist/by_yoshitaka_amano/landscape-0.jpg" } ] + }, + { + "modifier": "by Zdzislaw Beksinski", + "previews": [ + { + "name": "portrait", + "path": "artist/by_zdzislaw_beksinski/portrait-0.jpg" + }, + { + "name": "landscape", + "path": "artist/by_zdzislaw_beksinski/landscape-0.jpg" + } + ] } ] }, diff --git a/ui/plugins/ui/Autoscroll.plugin.js b/ui/plugins/ui/Autoscroll.plugin.js index 088b1457..336e8b50 100644 --- a/ui/plugins/ui/Autoscroll.plugin.js +++ b/ui/plugins/ui/Autoscroll.plugin.js @@ -1,28 +1,32 @@ -(function () { +;(function() { "use strict" let autoScroll = document.querySelector("#auto_scroll") // observe for changes in the preview pane - var observer = new MutationObserver(function (mutations) { - mutations.forEach(function (mutation) { - if (mutation.target.className == 'img-batch') { + var observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + if (mutation.target.className == "img-batch") { Autoscroll(mutation.target) } }) }) - - observer.observe(document.getElementById('preview'), { - childList: true, - subtree: true + + observer.observe(document.getElementById("preview"), { + childList: true, + subtree: true, }) function Autoscroll(target) { if (autoScroll.checked && target !== null) { - const img = target.querySelector('img') - img.addEventListener('load', function() { - img.closest('.imageTaskContainer').scrollIntoView() - }, { once: true }) + const img = target.querySelector("img") + img.addEventListener( + "load", + function() { + img?.closest(".imageTaskContainer").scrollIntoView() + }, + { once: true } + ) } } })() diff --git a/ui/plugins/ui/Modifiers-dnd.plugin.js b/ui/plugins/ui/Modifiers-dnd.plugin.js index b0aaaa95..d38307cf 100644 --- a/ui/plugins/ui/Modifiers-dnd.plugin.js +++ b/ui/plugins/ui/Modifiers-dnd.plugin.js @@ -1,93 +1,116 @@ -(function () { "use strict" - if (typeof editorModifierTagsList !== 'object') { - console.error('editorModifierTagsList missing...') +;(function() { + "use strict" + if (typeof editorModifierTagsList !== "object") { + console.error("editorModifierTagsList missing...") return } - const styleSheet = document.createElement("style"); + const styleSheet = document.createElement("style") styleSheet.textContent = ` .modifier-card-tiny.drag-sort-active { background: transparent; border: 2px dashed white; opacity:0.2; } - `; - document.head.appendChild(styleSheet); + ` + document.head.appendChild(styleSheet) // observe for changes in tag list - const observer = new MutationObserver(function (mutations) { - // mutations.forEach(function (mutation) { - if (editorModifierTagsList.childNodes.length > 0) { - ModifierDragAndDrop(editorModifierTagsList) - } - // }) + const observer = new MutationObserver(function(mutations) { + // mutations.forEach(function (mutation) { + if (editorModifierTagsList.childNodes.length > 0) { + ModifierDragAndDrop(editorModifierTagsList) + } + // }) }) - + observer.observe(editorModifierTagsList, { - childList: true + childList: true, }) let current function ModifierDragAndDrop(target) { - let overlays = document.querySelector('#editor-inputs-tags-list').querySelectorAll('.modifier-card-overlay') - overlays.forEach (i => { - i.parentElement.draggable = true; - + let overlays = document.querySelector("#editor-inputs-tags-list").querySelectorAll(".modifier-card-overlay") + overlays.forEach((i) => { + i.parentElement.draggable = true + i.parentElement.ondragstart = (e) => { current = i - i.parentElement.getElementsByClassName('modifier-card-image-overlay')[0].innerText = '' + i.parentElement.getElementsByClassName("modifier-card-image-overlay")[0].innerText = "" i.parentElement.draggable = true - i.parentElement.classList.add('drag-sort-active') - for(let item of document.querySelector('#editor-inputs-tags-list').getElementsByClassName('modifier-card-image-overlay')) { - if (item.parentElement.parentElement.getElementsByClassName('modifier-card-overlay')[0] != current) { - item.parentElement.parentElement.getElementsByClassName('modifier-card-image-overlay')[0].style.opacity = 0 - if(item.parentElement.getElementsByClassName('modifier-card-image').length > 0) { - item.parentElement.getElementsByClassName('modifier-card-image')[0].style.filter = 'none' + i.parentElement.classList.add("drag-sort-active") + for (let item of document + .querySelector("#editor-inputs-tags-list") + .getElementsByClassName("modifier-card-image-overlay")) { + if ( + item.parentElement.parentElement.getElementsByClassName("modifier-card-overlay")[0] != current + ) { + item.parentElement.parentElement.getElementsByClassName( + "modifier-card-image-overlay" + )[0].style.opacity = 0 + if (item.parentElement.getElementsByClassName("modifier-card-image").length > 0) { + item.parentElement.getElementsByClassName("modifier-card-image")[0].style.filter = "none" } - item.parentElement.parentElement.style.transform = 'none' - item.parentElement.parentElement.style.boxShadow = 'none' + item.parentElement.parentElement.style.transform = "none" + item.parentElement.parentElement.style.boxShadow = "none" } - item.innerText = '' + item.innerText = "" } } - + i.ondragenter = (e) => { e.preventDefault() if (i != current) { - let currentPos = 0, droppedPos = 0; + let currentPos = 0, + droppedPos = 0 for (let it = 0; it < overlays.length; it++) { - if (current == overlays[it]) { currentPos = it; } - if (i == overlays[it]) { droppedPos = it; } + if (current == overlays[it]) { + currentPos = it + } + if (i == overlays[it]) { + droppedPos = it + } } if (i.parentElement != current.parentElement) { - let currentPos = 0, droppedPos = 0 + let currentPos = 0, + droppedPos = 0 for (let it = 0; it < overlays.length; it++) { - if (current == overlays[it]) { currentPos = it } - if (i == overlays[it]) { droppedPos = it } + if (current == overlays[it]) { + currentPos = it + } + if (i == overlays[it]) { + droppedPos = it + } } if (currentPos < droppedPos) { - current = i.parentElement.parentNode.insertBefore(current.parentElement, i.parentElement.nextSibling).getElementsByClassName('modifier-card-overlay')[0] + current = i.parentElement.parentNode + .insertBefore(current.parentElement, i.parentElement.nextSibling) + .getElementsByClassName("modifier-card-overlay")[0] } else { - current = i.parentElement.parentNode.insertBefore(current.parentElement, i.parentElement).getElementsByClassName('modifier-card-overlay')[0] + current = i.parentElement.parentNode + .insertBefore(current.parentElement, i.parentElement) + .getElementsByClassName("modifier-card-overlay")[0] } // update activeTags const tag = activeTags.splice(currentPos, 1) activeTags.splice(droppedPos, 0, tag[0]) - document.dispatchEvent(new Event('refreshImageModifiers')) + document.dispatchEvent(new Event("refreshImageModifiers")) } } - }; + } i.ondragover = (e) => { e.preventDefault() } - + i.parentElement.ondragend = (e) => { - i.parentElement.classList.remove('drag-sort-active') - for(let item of document.querySelector('#editor-inputs-tags-list').getElementsByClassName('modifier-card-image-overlay')) { - item.style.opacity = '' - item.innerText = '-' + i.parentElement.classList.remove("drag-sort-active") + for (let item of document + .querySelector("#editor-inputs-tags-list") + .getElementsByClassName("modifier-card-image-overlay")) { + item.style.opacity = "" + item.innerText = "-" } } }) diff --git a/ui/plugins/ui/Modifiers-wheel.plugin.js b/ui/plugins/ui/Modifiers-wheel.plugin.js index 0967a725..df3a684f 100644 --- a/ui/plugins/ui/Modifiers-wheel.plugin.js +++ b/ui/plugins/ui/Modifiers-wheel.plugin.js @@ -1,35 +1,37 @@ -(function () { +;(function() { "use strict" const MAX_WEIGHT = 5 - - if (typeof editorModifierTagsList !== 'object') { - console.error('editorModifierTagsList missing...') + + if (typeof editorModifierTagsList !== "object") { + console.error("editorModifierTagsList missing...") return } // observe for changes in tag list - const observer = new MutationObserver(function (mutations) { - // mutations.forEach(function (mutation) { - if (editorModifierTagsList.childNodes.length > 0) { - ModifierMouseWheel(editorModifierTagsList) - } - // }) + const observer = new MutationObserver(function(mutations) { + // mutations.forEach(function (mutation) { + if (editorModifierTagsList.childNodes.length > 0) { + ModifierMouseWheel(editorModifierTagsList) + } + // }) }) - + observer.observe(editorModifierTagsList, { - childList: true + childList: true, }) function ModifierMouseWheel(target) { - let overlays = document.querySelector('#editor-inputs-tags-list').querySelectorAll('.modifier-card-overlay') - overlays.forEach (i => { + let overlays = document.querySelector("#editor-inputs-tags-list").querySelectorAll(".modifier-card-overlay") + overlays.forEach((i) => { i.onwheel = (e) => { if (e.ctrlKey == true) { e.preventDefault() - + const delta = Math.sign(event.deltaY) - let s = i.parentElement.getElementsByClassName('modifier-card-label')[0].getElementsByTagName("p")[0].innerText + let s = i.parentElement + .getElementsByClassName("modifier-card-label")[0] + .getElementsByTagName("p")[0].innerText let t // find the corresponding tag for (let it = 0; it < overlays.length; it++) { @@ -38,43 +40,40 @@ break } } - if (s.charAt(0) !== '(' && s.charAt(s.length - 1) !== ')' && s.trim().includes(' ')) { - s = '(' + s + ')' - t = '(' + t + ')' + if (s.charAt(0) !== "(" && s.charAt(s.length - 1) !== ")" && s.trim().includes(" ")) { + s = "(" + s + ")" + t = "(" + t + ")" } if (delta < 0) { // wheel scrolling up - if (s.substring(s.length - 1) == '-') { + if (s.substring(s.length - 1) == "-") { s = s.substring(0, s.length - 1) t = t.substring(0, t.length - 1) - } - else - { - if (s.substring(s.length - MAX_WEIGHT) !== '+'.repeat(MAX_WEIGHT)) { - s = s + '+' - t = t + '+' + } else { + if (s.substring(s.length - MAX_WEIGHT) !== "+".repeat(MAX_WEIGHT)) { + s = s + "+" + t = t + "+" } } - } - else{ + } else { // wheel scrolling down - if (s.substring(s.length - 1) == '+') { + if (s.substring(s.length - 1) == "+") { s = s.substring(0, s.length - 1) t = t.substring(0, t.length - 1) - } - else - { - if (s.substring(s.length - MAX_WEIGHT) !== '-'.repeat(MAX_WEIGHT)) { - s = s + '-' - t = t + '-' + } else { + if (s.substring(s.length - MAX_WEIGHT) !== "-".repeat(MAX_WEIGHT)) { + s = s + "-" + t = t + "-" } } } - if (s.charAt(0) === '(' && s.charAt(s.length - 1) === ')') { + if (s.charAt(0) === "(" && s.charAt(s.length - 1) === ")") { s = s.substring(1, s.length - 1) t = t.substring(1, t.length - 1) } - i.parentElement.getElementsByClassName('modifier-card-label')[0].getElementsByTagName("p")[0].innerText = s + i.parentElement + .getElementsByClassName("modifier-card-label")[0] + .getElementsByTagName("p")[0].innerText = s // update activeTags for (let it = 0; it < overlays.length; it++) { if (i == overlays[it]) { @@ -82,7 +81,7 @@ break } } - document.dispatchEvent(new Event('refreshImageModifiers')) + document.dispatchEvent(new Event("refreshImageModifiers")) } } }) diff --git a/ui/plugins/ui/custom-modifiers.plugin.js b/ui/plugins/ui/custom-modifiers.plugin.js index 68599c63..91d2acc4 100644 --- a/ui/plugins/ui/custom-modifiers.plugin.js +++ b/ui/plugins/ui/custom-modifiers.plugin.js @@ -1,31 +1,31 @@ -(function() { - PLUGINS['MODIFIERS_LOAD'].push({ +;(function() { + PLUGINS["MODIFIERS_LOAD"].push({ loader: function() { - let customModifiers = localStorage.getItem(CUSTOM_MODIFIERS_KEY, '') + let customModifiers = localStorage.getItem(CUSTOM_MODIFIERS_KEY, "") customModifiersTextBox.value = customModifiers if (customModifiersGroupElement !== undefined) { customModifiersGroupElement.remove() } - if (customModifiers && customModifiers.trim() !== '') { - customModifiers = customModifiers.split('\n') - customModifiers = customModifiers.filter(m => m.trim() !== '') + if (customModifiers && customModifiers.trim() !== "") { + customModifiers = customModifiers.split("\n") + customModifiers = customModifiers.filter((m) => m.trim() !== "") customModifiers = customModifiers.map(function(m) { return { - "modifier": m + modifier: m, } }) let customGroup = { - 'category': 'Custom Modifiers', - 'modifiers': customModifiers + category: "Custom Modifiers", + modifiers: customModifiers, } customModifiersGroupElement = createModifierGroup(customGroup, true) createCollapsibles(customModifiersGroupElement) } - } + }, }) })() diff --git a/ui/plugins/ui/jasmine/boot0.js b/ui/plugins/ui/jasmine/boot0.js index c773ba8e..df131d9e 100644 --- a/ui/plugins/ui/jasmine/boot0.js +++ b/ui/plugins/ui/jasmine/boot0.js @@ -26,39 +26,39 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. after `jasmine.js` and `jasmine_html.js`, but before `boot1.js` or any project source files or spec files are loaded. */ -(function() { - const jasmineRequire = window.jasmineRequire || require('./jasmine.js'); +;(function() { + const jasmineRequire = window.jasmineRequire || require("./jasmine.js") - /** - * ## Require & Instantiate - * - * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. - */ - const jasmine = jasmineRequire.core(jasmineRequire), - global = jasmine.getGlobal(); - global.jasmine = jasmine; + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + const jasmine = jasmineRequire.core(jasmineRequire), + global = jasmine.getGlobal() + global.jasmine = jasmine - /** - * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. - */ - jasmineRequire.html(jasmine); + /** + * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. + */ + jasmineRequire.html(jasmine) - /** - * Create the Jasmine environment. This is used to run all specs in a project. - */ - const env = jasmine.getEnv(); + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + const env = jasmine.getEnv() - /** - * ## The Global Interface - * - * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. - */ - const jasmineInterface = jasmineRequire.interface(jasmine, env); + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + const jasmineInterface = jasmineRequire.interface(jasmine, env) - /** - * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. - */ - for (const property in jasmineInterface) { - global[property] = jasmineInterface[property]; - } -})(); + /** + * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + for (const property in jasmineInterface) { + global[property] = jasmineInterface[property] + } +})() diff --git a/ui/plugins/ui/jasmine/boot1.js b/ui/plugins/ui/jasmine/boot1.js index 5fe49e41..39bfe0fa 100644 --- a/ui/plugins/ui/jasmine/boot1.js +++ b/ui/plugins/ui/jasmine/boot1.js @@ -33,100 +33,98 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. after `boot0.js` is loaded and before this file is loaded. */ -(function() { - const env = jasmine.getEnv(); +;(function() { + const env = jasmine.getEnv() - /** - * ## Runner Parameters - * - * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. - */ + /** + * ## Runner Parameters + * + * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. + */ - const queryString = new jasmine.QueryString({ - getWindowLocation: function() { - return window.location; + const queryString = new jasmine.QueryString({ + getWindowLocation: function() { + return window.location + }, + }) + + const filterSpecs = !!queryString.getParam("spec") + + const config = { + stopOnSpecFailure: queryString.getParam("stopOnSpecFailure"), + stopSpecOnExpectationFailure: queryString.getParam("stopSpecOnExpectationFailure"), + hideDisabled: queryString.getParam("hideDisabled"), } - }); - const filterSpecs = !!queryString.getParam('spec'); + const random = queryString.getParam("random") - const config = { - stopOnSpecFailure: queryString.getParam('stopOnSpecFailure'), - stopSpecOnExpectationFailure: queryString.getParam( - 'stopSpecOnExpectationFailure' - ), - hideDisabled: queryString.getParam('hideDisabled') - }; - - const random = queryString.getParam('random'); - - if (random !== undefined && random !== '') { - config.random = random; - } - - const seed = queryString.getParam('seed'); - if (seed) { - config.seed = seed; - } - - /** - * ## Reporters - * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). - */ - const htmlReporter = new jasmine.HtmlReporter({ - env: env, - navigateWithNewParam: function(key, value) { - return queryString.navigateWithNewParam(key, value); - }, - addToExistingQueryString: function(key, value) { - return queryString.fullStringWithNewParam(key, value); - }, - getContainer: function() { - return document.body; - }, - createElement: function() { - return document.createElement.apply(document, arguments); - }, - createTextNode: function() { - return document.createTextNode.apply(document, arguments); - }, - timer: new jasmine.Timer(), - filterSpecs: filterSpecs - }); - - /** - * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. - */ - env.addReporter(jsApiReporter); - env.addReporter(htmlReporter); - - /** - * Filter which specs will be run by matching the start of the full name against the `spec` query param. - */ - const specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { - return queryString.getParam('spec'); + if (random !== undefined && random !== "") { + config.random = random } - }); - config.specFilter = function(spec) { - return specFilter.matches(spec.getFullName()); - }; - - env.configure(config); - - /** - * ## Execution - * - * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. - */ - const currentWindowOnload = window.onload; - - window.onload = function() { - if (currentWindowOnload) { - currentWindowOnload(); + const seed = queryString.getParam("seed") + if (seed) { + config.seed = seed } - htmlReporter.initialize(); - env.execute(); - }; -})(); + + /** + * ## Reporters + * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). + */ + const htmlReporter = new jasmine.HtmlReporter({ + env: env, + navigateWithNewParam: function(key, value) { + return queryString.navigateWithNewParam(key, value) + }, + addToExistingQueryString: function(key, value) { + return queryString.fullStringWithNewParam(key, value) + }, + getContainer: function() { + return document.body + }, + createElement: function() { + return document.createElement.apply(document, arguments) + }, + createTextNode: function() { + return document.createTextNode.apply(document, arguments) + }, + timer: new jasmine.Timer(), + filterSpecs: filterSpecs, + }) + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jsApiReporter) + env.addReporter(htmlReporter) + + /** + * Filter which specs will be run by matching the start of the full name against the `spec` query param. + */ + const specFilter = new jasmine.HtmlSpecFilter({ + filterString: function() { + return queryString.getParam("spec") + }, + }) + + config.specFilter = function(spec) { + return specFilter.matches(spec.getFullName()) + } + + env.configure(config) + + /** + * ## Execution + * + * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. + */ + const currentWindowOnload = window.onload + + window.onload = function() { + if (currentWindowOnload) { + currentWindowOnload() + } + htmlReporter.initialize() + env.execute() + } +})() diff --git a/ui/plugins/ui/jasmine/jasmine-html.js b/ui/plugins/ui/jasmine/jasmine-html.js index 2ebc6d0e..2d09f498 100644 --- a/ui/plugins/ui/jasmine/jasmine-html.js +++ b/ui/plugins/ui/jasmine/jasmine-html.js @@ -21,944 +21,804 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // eslint-disable-next-line no-var -var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); +var jasmineRequire = window.jasmineRequire || require("./jasmine.js") jasmineRequire.html = function(j$) { - j$.ResultsNode = jasmineRequire.ResultsNode(); - j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); - j$.QueryString = jasmineRequire.QueryString(); - j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); -}; + j$.ResultsNode = jasmineRequire.ResultsNode() + j$.HtmlReporter = jasmineRequire.HtmlReporter(j$) + j$.QueryString = jasmineRequire.QueryString() + j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter() +} jasmineRequire.HtmlReporter = function(j$) { - function ResultsStateBuilder() { - this.topResults = new j$.ResultsNode({}, '', null); - this.currentParent = this.topResults; - this.specsExecuted = 0; - this.failureCount = 0; - this.pendingSpecCount = 0; - } - - ResultsStateBuilder.prototype.suiteStarted = function(result) { - this.currentParent.addChild(result, 'suite'); - this.currentParent = this.currentParent.last(); - }; - - ResultsStateBuilder.prototype.suiteDone = function(result) { - this.currentParent.updateResult(result); - if (this.currentParent !== this.topResults) { - this.currentParent = this.currentParent.parent; + function ResultsStateBuilder() { + this.topResults = new j$.ResultsNode({}, "", null) + this.currentParent = this.topResults + this.specsExecuted = 0 + this.failureCount = 0 + this.pendingSpecCount = 0 } - if (result.status === 'failed') { - this.failureCount++; - } - }; - - ResultsStateBuilder.prototype.specStarted = function(result) {}; - - ResultsStateBuilder.prototype.specDone = function(result) { - this.currentParent.addChild(result, 'spec'); - - if (result.status !== 'excluded') { - this.specsExecuted++; + ResultsStateBuilder.prototype.suiteStarted = function(result) { + this.currentParent.addChild(result, "suite") + this.currentParent = this.currentParent.last() } - if (result.status === 'failed') { - this.failureCount++; - } - - if (result.status == 'pending') { - this.pendingSpecCount++; - } - }; - - ResultsStateBuilder.prototype.jasmineDone = function(result) { - if (result.failedExpectations) { - this.failureCount += result.failedExpectations.length; - } - }; - - function HtmlReporter(options) { - function config() { - return (options.env && options.env.configuration()) || {}; - } - - const getContainer = options.getContainer; - const createElement = options.createElement; - const createTextNode = options.createTextNode; - const navigateWithNewParam = options.navigateWithNewParam || function() {}; - const addToExistingQueryString = - options.addToExistingQueryString || defaultQueryString; - const filterSpecs = options.filterSpecs; - let htmlReporterMain; - let symbols; - const deprecationWarnings = []; - const failures = []; - - this.initialize = function() { - clearPrior(); - htmlReporterMain = createDom( - 'div', - { className: 'jasmine_html-reporter' }, - createDom( - 'div', - { className: 'jasmine-banner' }, - createDom('a', { - className: 'jasmine-title', - href: 'http://jasmine.github.io/', - target: '_blank' - }), - createDom('span', { className: 'jasmine-version' }, j$.version) - ), - createDom('ul', { className: 'jasmine-symbol-summary' }), - createDom('div', { className: 'jasmine-alert' }), - createDom( - 'div', - { className: 'jasmine-results' }, - createDom('div', { className: 'jasmine-failures' }) - ) - ); - getContainer().appendChild(htmlReporterMain); - }; - - let totalSpecsDefined; - this.jasmineStarted = function(options) { - totalSpecsDefined = options.totalSpecsDefined || 0; - }; - - const summary = createDom('div', { className: 'jasmine-summary' }); - - const stateBuilder = new ResultsStateBuilder(); - - this.suiteStarted = function(result) { - stateBuilder.suiteStarted(result); - }; - - this.suiteDone = function(result) { - stateBuilder.suiteDone(result); - - if (result.status === 'failed') { - failures.push(failureDom(result)); - } - addDeprecationWarnings(result, 'suite'); - }; - - this.specStarted = function(result) { - stateBuilder.specStarted(result); - }; - - this.specDone = function(result) { - stateBuilder.specDone(result); - - if (noExpectations(result)) { - const noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; - if (result.status === 'failed') { - console.error(noSpecMsg); - } else { - console.warn(noSpecMsg); + ResultsStateBuilder.prototype.suiteDone = function(result) { + this.currentParent.updateResult(result) + if (this.currentParent !== this.topResults) { + this.currentParent = this.currentParent.parent } - } - if (!symbols) { - symbols = find('.jasmine-symbol-summary'); - } + if (result.status === "failed") { + this.failureCount++ + } + } - symbols.appendChild( - createDom('li', { - className: this.displaySpecInCorrectFormat(result), - id: 'spec_' + result.id, - title: result.fullName - }) - ); + ResultsStateBuilder.prototype.specStarted = function(result) {} - if (result.status === 'failed') { - failures.push(failureDom(result)); - } + ResultsStateBuilder.prototype.specDone = function(result) { + this.currentParent.addChild(result, "spec") - addDeprecationWarnings(result, 'spec'); - }; + if (result.status !== "excluded") { + this.specsExecuted++ + } - this.displaySpecInCorrectFormat = function(result) { - return noExpectations(result) && result.status === 'passed' - ? 'jasmine-empty' - : this.resultStatus(result.status); - }; + if (result.status === "failed") { + this.failureCount++ + } - this.resultStatus = function(status) { - if (status === 'excluded') { - return config().hideDisabled - ? 'jasmine-excluded-no-display' - : 'jasmine-excluded'; - } - return 'jasmine-' + status; - }; + if (result.status == "pending") { + this.pendingSpecCount++ + } + } - this.jasmineDone = function(doneResult) { - stateBuilder.jasmineDone(doneResult); - const banner = find('.jasmine-banner'); - const alert = find('.jasmine-alert'); - const order = doneResult && doneResult.order; + ResultsStateBuilder.prototype.jasmineDone = function(result) { + if (result.failedExpectations) { + this.failureCount += result.failedExpectations.length + } + } - alert.appendChild( - createDom( - 'span', - { className: 'jasmine-duration' }, - 'finished in ' + doneResult.totalTime / 1000 + 's' - ) - ); + function HtmlReporter(options) { + function config() { + return (options.env && options.env.configuration()) || {} + } - banner.appendChild(optionsMenu(config())); + const getContainer = options.getContainer + const createElement = options.createElement + const createTextNode = options.createTextNode + const navigateWithNewParam = options.navigateWithNewParam || function() {} + const addToExistingQueryString = options.addToExistingQueryString || defaultQueryString + const filterSpecs = options.filterSpecs + let htmlReporterMain + let symbols + const deprecationWarnings = [] + const failures = [] - if (stateBuilder.specsExecuted < totalSpecsDefined) { - const skippedMessage = - 'Ran ' + - stateBuilder.specsExecuted + - ' of ' + - totalSpecsDefined + - ' specs - run all'; - // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - const skippedLink = - (window.location.pathname || '') + - addToExistingQueryString('spec', ''); - alert.appendChild( - createDom( - 'span', - { className: 'jasmine-bar jasmine-skipped' }, - createDom( - 'a', - { href: skippedLink, title: 'Run all specs' }, - skippedMessage + this.initialize = function() { + clearPrior() + htmlReporterMain = createDom( + "div", + { className: "jasmine_html-reporter" }, + createDom( + "div", + { className: "jasmine-banner" }, + createDom("a", { + className: "jasmine-title", + href: "http://jasmine.github.io/", + target: "_blank", + }), + createDom("span", { className: "jasmine-version" }, j$.version) + ), + createDom("ul", { className: "jasmine-symbol-summary" }), + createDom("div", { className: "jasmine-alert" }), + createDom("div", { className: "jasmine-results" }, createDom("div", { className: "jasmine-failures" })) ) - ) - ); - } - let statusBarMessage = ''; - let statusBarClassName = 'jasmine-overall-result jasmine-bar '; - const globalFailures = - (doneResult && doneResult.failedExpectations) || []; - const failed = stateBuilder.failureCount + globalFailures.length > 0; - - if (totalSpecsDefined > 0 || failed) { - statusBarMessage += - pluralize('spec', stateBuilder.specsExecuted) + - ', ' + - pluralize('failure', stateBuilder.failureCount); - if (stateBuilder.pendingSpecCount) { - statusBarMessage += - ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); - } - } - - if (doneResult.overallStatus === 'passed') { - statusBarClassName += ' jasmine-passed '; - } else if (doneResult.overallStatus === 'incomplete') { - statusBarClassName += ' jasmine-incomplete '; - statusBarMessage = - 'Incomplete: ' + - doneResult.incompleteReason + - ', ' + - statusBarMessage; - } else { - statusBarClassName += ' jasmine-failed '; - } - - let seedBar; - if (order && order.random) { - seedBar = createDom( - 'span', - { className: 'jasmine-seed-bar' }, - ', randomized with seed ', - createDom( - 'a', - { - title: 'randomized with seed ' + order.seed, - href: seedHref(order.seed) - }, - order.seed - ) - ); - } - - alert.appendChild( - createDom( - 'span', - { className: statusBarClassName }, - statusBarMessage, - seedBar - ) - ); - - const errorBarClassName = 'jasmine-bar jasmine-errored'; - const afterAllMessagePrefix = 'AfterAll '; - - for (let i = 0; i < globalFailures.length; i++) { - alert.appendChild( - createDom( - 'span', - { className: errorBarClassName }, - globalFailureMessage(globalFailures[i]) - ) - ); - } - - function globalFailureMessage(failure) { - if (failure.globalErrorType === 'load') { - const prefix = 'Error during loading: ' + failure.message; - - if (failure.filename) { - return ( - prefix + ' in ' + failure.filename + ' line ' + failure.lineno - ); - } else { - return prefix; - } - } else if (failure.globalErrorType === 'afterAll') { - return afterAllMessagePrefix + failure.message; - } else { - return failure.message; - } - } - - addDeprecationWarnings(doneResult); - - for (let i = 0; i < deprecationWarnings.length; i++) { - const children = []; - let context; - - switch (deprecationWarnings[i].runnableType) { - case 'spec': - context = '(in spec: ' + deprecationWarnings[i].runnableName + ')'; - break; - case 'suite': - context = '(in suite: ' + deprecationWarnings[i].runnableName + ')'; - break; - default: - context = ''; + getContainer().appendChild(htmlReporterMain) } - deprecationWarnings[i].message.split('\n').forEach(function(line) { - children.push(line); - children.push(createDom('br')); - }); - - children[0] = 'DEPRECATION: ' + children[0]; - children.push(context); - - if (deprecationWarnings[i].stack) { - children.push(createExpander(deprecationWarnings[i].stack)); + let totalSpecsDefined + this.jasmineStarted = function(options) { + totalSpecsDefined = options.totalSpecsDefined || 0 } - alert.appendChild( - createDom( - 'span', - { className: 'jasmine-bar jasmine-warning' }, - children - ) - ); - } + const summary = createDom("div", { className: "jasmine-summary" }) - const results = find('.jasmine-results'); - results.appendChild(summary); + const stateBuilder = new ResultsStateBuilder() - summaryList(stateBuilder.topResults, summary); + this.suiteStarted = function(result) { + stateBuilder.suiteStarted(result) + } - if (failures.length) { - alert.appendChild( - createDom( - 'span', - { className: 'jasmine-menu jasmine-bar jasmine-spec-list' }, - createDom('span', {}, 'Spec List | '), - createDom( - 'a', - { className: 'jasmine-failures-menu', href: '#' }, - 'Failures' + this.suiteDone = function(result) { + stateBuilder.suiteDone(result) + + if (result.status === "failed") { + failures.push(failureDom(result)) + } + addDeprecationWarnings(result, "suite") + } + + this.specStarted = function(result) { + stateBuilder.specStarted(result) + } + + this.specDone = function(result) { + stateBuilder.specDone(result) + + if (noExpectations(result)) { + const noSpecMsg = "Spec '" + result.fullName + "' has no expectations." + if (result.status === "failed") { + console.error(noSpecMsg) + } else { + console.warn(noSpecMsg) + } + } + + if (!symbols) { + symbols = find(".jasmine-symbol-summary") + } + + symbols.appendChild( + createDom("li", { + className: this.displaySpecInCorrectFormat(result), + id: "spec_" + result.id, + title: result.fullName, + }) ) - ) - ); - alert.appendChild( - createDom( - 'span', - { className: 'jasmine-menu jasmine-bar jasmine-failure-list' }, - createDom( - 'a', - { className: 'jasmine-spec-list-menu', href: '#' }, - 'Spec List' - ), - createDom('span', {}, ' | Failures ') - ) - ); - find('.jasmine-failures-menu').onclick = function() { - setMenuModeTo('jasmine-failure-list'); - return false; - }; - find('.jasmine-spec-list-menu').onclick = function() { - setMenuModeTo('jasmine-spec-list'); - return false; - }; + if (result.status === "failed") { + failures.push(failureDom(result)) + } - setMenuModeTo('jasmine-failure-list'); - - const failureNode = find('.jasmine-failures'); - for (let i = 0; i < failures.length; i++) { - failureNode.appendChild(failures[i]); + addDeprecationWarnings(result, "spec") } - } - }; - return this; + this.displaySpecInCorrectFormat = function(result) { + return noExpectations(result) && result.status === "passed" + ? "jasmine-empty" + : this.resultStatus(result.status) + } - function failureDom(result) { - const failure = createDom( - 'div', - { className: 'jasmine-spec-detail jasmine-failed' }, - failureDescription(result, stateBuilder.currentParent), - createDom('div', { className: 'jasmine-messages' }) - ); - const messages = failure.childNodes[1]; + this.resultStatus = function(status) { + if (status === "excluded") { + return config().hideDisabled ? "jasmine-excluded-no-display" : "jasmine-excluded" + } + return "jasmine-" + status + } - for (let i = 0; i < result.failedExpectations.length; i++) { - const expectation = result.failedExpectations[i]; - messages.appendChild( - createDom( - 'div', - { className: 'jasmine-result-message' }, - expectation.message - ) - ); - messages.appendChild( - createDom( - 'div', - { className: 'jasmine-stack-trace' }, - expectation.stack - ) - ); - } + this.jasmineDone = function(doneResult) { + stateBuilder.jasmineDone(doneResult) + const banner = find(".jasmine-banner") + const alert = find(".jasmine-alert") + const order = doneResult && doneResult.order - if (result.failedExpectations.length === 0) { - messages.appendChild( - createDom( - 'div', - { className: 'jasmine-result-message' }, - 'Spec has no expectations' - ) - ); - } - - if (result.debugLogs) { - messages.appendChild(debugLogTable(result.debugLogs)); - } - - return failure; - } - - function debugLogTable(debugLogs) { - const tbody = createDom('tbody'); - - debugLogs.forEach(function(entry) { - tbody.appendChild( - createDom( - 'tr', - {}, - createDom('td', {}, entry.timestamp.toString()), - createDom('td', {}, entry.message) - ) - ); - }); - - return createDom( - 'div', - { className: 'jasmine-debug-log' }, - createDom( - 'div', - { className: 'jasmine-debug-log-header' }, - 'Debug logs' - ), - createDom( - 'table', - {}, - createDom( - 'thead', - {}, - createDom( - 'tr', - {}, - createDom('th', {}, 'Time (ms)'), - createDom('th', {}, 'Message') + alert.appendChild( + createDom("span", { className: "jasmine-duration" }, "finished in " + doneResult.totalTime / 1000 + "s") ) - ), - tbody - ) - ); - } - function summaryList(resultsTree, domParent) { - let specListNode; - for (let i = 0; i < resultsTree.children.length; i++) { - const resultNode = resultsTree.children[i]; - if (filterSpecs && !hasActiveSpec(resultNode)) { - continue; + banner.appendChild(optionsMenu(config())) + + if (stateBuilder.specsExecuted < totalSpecsDefined) { + const skippedMessage = + "Ran " + stateBuilder.specsExecuted + " of " + totalSpecsDefined + " specs - run all" + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + const skippedLink = (window.location.pathname || "") + addToExistingQueryString("spec", "") + alert.appendChild( + createDom( + "span", + { className: "jasmine-bar jasmine-skipped" }, + createDom("a", { href: skippedLink, title: "Run all specs" }, skippedMessage) + ) + ) + } + let statusBarMessage = "" + let statusBarClassName = "jasmine-overall-result jasmine-bar " + const globalFailures = (doneResult && doneResult.failedExpectations) || [] + const failed = stateBuilder.failureCount + globalFailures.length > 0 + + if (totalSpecsDefined > 0 || failed) { + statusBarMessage += + pluralize("spec", stateBuilder.specsExecuted) + + ", " + + pluralize("failure", stateBuilder.failureCount) + if (stateBuilder.pendingSpecCount) { + statusBarMessage += ", " + pluralize("pending spec", stateBuilder.pendingSpecCount) + } + } + + if (doneResult.overallStatus === "passed") { + statusBarClassName += " jasmine-passed " + } else if (doneResult.overallStatus === "incomplete") { + statusBarClassName += " jasmine-incomplete " + statusBarMessage = "Incomplete: " + doneResult.incompleteReason + ", " + statusBarMessage + } else { + statusBarClassName += " jasmine-failed " + } + + let seedBar + if (order && order.random) { + seedBar = createDom( + "span", + { className: "jasmine-seed-bar" }, + ", randomized with seed ", + createDom( + "a", + { + title: "randomized with seed " + order.seed, + href: seedHref(order.seed), + }, + order.seed + ) + ) + } + + alert.appendChild(createDom("span", { className: statusBarClassName }, statusBarMessage, seedBar)) + + const errorBarClassName = "jasmine-bar jasmine-errored" + const afterAllMessagePrefix = "AfterAll " + + for (let i = 0; i < globalFailures.length; i++) { + alert.appendChild( + createDom("span", { className: errorBarClassName }, globalFailureMessage(globalFailures[i])) + ) + } + + function globalFailureMessage(failure) { + if (failure.globalErrorType === "load") { + const prefix = "Error during loading: " + failure.message + + if (failure.filename) { + return prefix + " in " + failure.filename + " line " + failure.lineno + } else { + return prefix + } + } else if (failure.globalErrorType === "afterAll") { + return afterAllMessagePrefix + failure.message + } else { + return failure.message + } + } + + addDeprecationWarnings(doneResult) + + for (let i = 0; i < deprecationWarnings.length; i++) { + const children = [] + let context + + switch (deprecationWarnings[i].runnableType) { + case "spec": + context = "(in spec: " + deprecationWarnings[i].runnableName + ")" + break + case "suite": + context = "(in suite: " + deprecationWarnings[i].runnableName + ")" + break + default: + context = "" + } + + deprecationWarnings[i].message.split("\n").forEach(function(line) { + children.push(line) + children.push(createDom("br")) + }) + + children[0] = "DEPRECATION: " + children[0] + children.push(context) + + if (deprecationWarnings[i].stack) { + children.push(createExpander(deprecationWarnings[i].stack)) + } + + alert.appendChild(createDom("span", { className: "jasmine-bar jasmine-warning" }, children)) + } + + const results = find(".jasmine-results") + results.appendChild(summary) + + summaryList(stateBuilder.topResults, summary) + + if (failures.length) { + alert.appendChild( + createDom( + "span", + { className: "jasmine-menu jasmine-bar jasmine-spec-list" }, + createDom("span", {}, "Spec List | "), + createDom("a", { className: "jasmine-failures-menu", href: "#" }, "Failures") + ) + ) + alert.appendChild( + createDom( + "span", + { className: "jasmine-menu jasmine-bar jasmine-failure-list" }, + createDom("a", { className: "jasmine-spec-list-menu", href: "#" }, "Spec List"), + createDom("span", {}, " | Failures ") + ) + ) + + find(".jasmine-failures-menu").onclick = function() { + setMenuModeTo("jasmine-failure-list") + return false + } + find(".jasmine-spec-list-menu").onclick = function() { + setMenuModeTo("jasmine-spec-list") + return false + } + + setMenuModeTo("jasmine-failure-list") + + const failureNode = find(".jasmine-failures") + for (let i = 0; i < failures.length; i++) { + failureNode.appendChild(failures[i]) + } + } } - if (resultNode.type === 'suite') { - const suiteListNode = createDom( - 'ul', - { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, - createDom( - 'li', - { - className: - 'jasmine-suite-detail jasmine-' + resultNode.result.status - }, - createDom( - 'a', - { href: specHref(resultNode.result) }, - resultNode.result.description - ) + + return this + + function failureDom(result) { + const failure = createDom( + "div", + { className: "jasmine-spec-detail jasmine-failed" }, + failureDescription(result, stateBuilder.currentParent), + createDom("div", { className: "jasmine-messages" }) ) - ); + const messages = failure.childNodes[1] - summaryList(resultNode, suiteListNode); - domParent.appendChild(suiteListNode); + for (let i = 0; i < result.failedExpectations.length; i++) { + const expectation = result.failedExpectations[i] + messages.appendChild(createDom("div", { className: "jasmine-result-message" }, expectation.message)) + messages.appendChild(createDom("div", { className: "jasmine-stack-trace" }, expectation.stack)) + } + + if (result.failedExpectations.length === 0) { + messages.appendChild( + createDom("div", { className: "jasmine-result-message" }, "Spec has no expectations") + ) + } + + if (result.debugLogs) { + messages.appendChild(debugLogTable(result.debugLogs)) + } + + return failure } - if (resultNode.type === 'spec') { - if (domParent.getAttribute('class') !== 'jasmine-specs') { - specListNode = createDom('ul', { className: 'jasmine-specs' }); - domParent.appendChild(specListNode); - } - let specDescription = resultNode.result.description; - if (noExpectations(resultNode.result)) { - specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; - } - if ( - resultNode.result.status === 'pending' && - resultNode.result.pendingReason !== '' - ) { - specDescription = - specDescription + - ' PENDING WITH MESSAGE: ' + - resultNode.result.pendingReason; - } - specListNode.appendChild( - createDom( - 'li', - { - className: 'jasmine-' + resultNode.result.status, - id: 'spec-' + resultNode.result.id - }, - createDom( - 'a', - { href: specHref(resultNode.result) }, - specDescription - ) + + function debugLogTable(debugLogs) { + const tbody = createDom("tbody") + + debugLogs.forEach(function(entry) { + tbody.appendChild( + createDom( + "tr", + {}, + createDom("td", {}, entry.timestamp.toString()), + createDom("td", {}, entry.message) + ) + ) + }) + + return createDom( + "div", + { className: "jasmine-debug-log" }, + createDom("div", { className: "jasmine-debug-log-header" }, "Debug logs"), + createDom( + "table", + {}, + createDom( + "thead", + {}, + createDom("tr", {}, createDom("th", {}, "Time (ms)"), createDom("th", {}, "Message")) + ), + tbody + ) ) - ); } - } - } - function optionsMenu(config) { - const optionsMenuDom = createDom( - 'div', - { className: 'jasmine-run-options' }, - createDom('span', { className: 'jasmine-trigger' }, 'Options'), - createDom( - 'div', - { className: 'jasmine-payload' }, - createDom( - 'div', - { className: 'jasmine-stop-on-failure' }, - createDom('input', { - className: 'jasmine-fail-fast', - id: 'jasmine-fail-fast', - type: 'checkbox' - }), - createDom( - 'label', - { className: 'jasmine-label', for: 'jasmine-fail-fast' }, - 'stop execution on spec failure' + function summaryList(resultsTree, domParent) { + let specListNode + for (let i = 0; i < resultsTree.children.length; i++) { + const resultNode = resultsTree.children[i] + if (filterSpecs && !hasActiveSpec(resultNode)) { + continue + } + if (resultNode.type === "suite") { + const suiteListNode = createDom( + "ul", + { className: "jasmine-suite", id: "suite-" + resultNode.result.id }, + createDom( + "li", + { + className: "jasmine-suite-detail jasmine-" + resultNode.result.status, + }, + createDom("a", { href: specHref(resultNode.result) }, resultNode.result.description) + ) + ) + + summaryList(resultNode, suiteListNode) + domParent.appendChild(suiteListNode) + } + if (resultNode.type === "spec") { + if (domParent.getAttribute("class") !== "jasmine-specs") { + specListNode = createDom("ul", { className: "jasmine-specs" }) + domParent.appendChild(specListNode) + } + let specDescription = resultNode.result.description + if (noExpectations(resultNode.result)) { + specDescription = "SPEC HAS NO EXPECTATIONS " + specDescription + } + if (resultNode.result.status === "pending" && resultNode.result.pendingReason !== "") { + specDescription = specDescription + " PENDING WITH MESSAGE: " + resultNode.result.pendingReason + } + specListNode.appendChild( + createDom( + "li", + { + className: "jasmine-" + resultNode.result.status, + id: "spec-" + resultNode.result.id, + }, + createDom("a", { href: specHref(resultNode.result) }, specDescription) + ) + ) + } + } + } + + function optionsMenu(config) { + const optionsMenuDom = createDom( + "div", + { className: "jasmine-run-options" }, + createDom("span", { className: "jasmine-trigger" }, "Options"), + createDom( + "div", + { className: "jasmine-payload" }, + createDom( + "div", + { className: "jasmine-stop-on-failure" }, + createDom("input", { + className: "jasmine-fail-fast", + id: "jasmine-fail-fast", + type: "checkbox", + }), + createDom( + "label", + { className: "jasmine-label", for: "jasmine-fail-fast" }, + "stop execution on spec failure" + ) + ), + createDom( + "div", + { className: "jasmine-throw-failures" }, + createDom("input", { + className: "jasmine-throw", + id: "jasmine-throw-failures", + type: "checkbox", + }), + createDom( + "label", + { className: "jasmine-label", for: "jasmine-throw-failures" }, + "stop spec on expectation failure" + ) + ), + createDom( + "div", + { className: "jasmine-random-order" }, + createDom("input", { + className: "jasmine-random", + id: "jasmine-random-order", + type: "checkbox", + }), + createDom( + "label", + { className: "jasmine-label", for: "jasmine-random-order" }, + "run tests in random order" + ) + ), + createDom( + "div", + { className: "jasmine-hide-disabled" }, + createDom("input", { + className: "jasmine-disabled", + id: "jasmine-hide-disabled", + type: "checkbox", + }), + createDom( + "label", + { className: "jasmine-label", for: "jasmine-hide-disabled" }, + "hide disabled tests" + ) + ) + ) ) - ), - createDom( - 'div', - { className: 'jasmine-throw-failures' }, - createDom('input', { - className: 'jasmine-throw', - id: 'jasmine-throw-failures', - type: 'checkbox' - }), - createDom( - 'label', - { className: 'jasmine-label', for: 'jasmine-throw-failures' }, - 'stop spec on expectation failure' + + const failFastCheckbox = optionsMenuDom.querySelector("#jasmine-fail-fast") + failFastCheckbox.checked = config.stopOnSpecFailure + failFastCheckbox.onclick = function() { + navigateWithNewParam("stopOnSpecFailure", !config.stopOnSpecFailure) + } + + const throwCheckbox = optionsMenuDom.querySelector("#jasmine-throw-failures") + throwCheckbox.checked = config.stopSpecOnExpectationFailure + throwCheckbox.onclick = function() { + navigateWithNewParam("stopSpecOnExpectationFailure", !config.stopSpecOnExpectationFailure) + } + + const randomCheckbox = optionsMenuDom.querySelector("#jasmine-random-order") + randomCheckbox.checked = config.random + randomCheckbox.onclick = function() { + navigateWithNewParam("random", !config.random) + } + + const hideDisabled = optionsMenuDom.querySelector("#jasmine-hide-disabled") + hideDisabled.checked = config.hideDisabled + hideDisabled.onclick = function() { + navigateWithNewParam("hideDisabled", !config.hideDisabled) + } + + const optionsTrigger = optionsMenuDom.querySelector(".jasmine-trigger"), + optionsPayload = optionsMenuDom.querySelector(".jasmine-payload"), + isOpen = /\bjasmine-open\b/ + + optionsTrigger.onclick = function() { + if (isOpen.test(optionsPayload.className)) { + optionsPayload.className = optionsPayload.className.replace(isOpen, "") + } else { + optionsPayload.className += " jasmine-open" + } + } + + return optionsMenuDom + } + + function failureDescription(result, suite) { + const wrapper = createDom( + "div", + { className: "jasmine-description" }, + createDom("a", { title: result.description, href: specHref(result) }, result.description) ) - ), - createDom( - 'div', - { className: 'jasmine-random-order' }, - createDom('input', { - className: 'jasmine-random', - id: 'jasmine-random-order', - type: 'checkbox' - }), - createDom( - 'label', - { className: 'jasmine-label', for: 'jasmine-random-order' }, - 'run tests in random order' + let suiteLink + + while (suite && suite.parent) { + wrapper.insertBefore(createTextNode(" > "), wrapper.firstChild) + suiteLink = createDom("a", { href: suiteHref(suite) }, suite.result.description) + wrapper.insertBefore(suiteLink, wrapper.firstChild) + + suite = suite.parent + } + + return wrapper + } + + function suiteHref(suite) { + const els = [] + + while (suite && suite.parent) { + els.unshift(suite.result.description) + suite = suite.parent + } + + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return (window.location.pathname || "") + addToExistingQueryString("spec", els.join(" ")) + } + + function addDeprecationWarnings(result, runnableType) { + if (result && result.deprecationWarnings) { + for (let i = 0; i < result.deprecationWarnings.length; i++) { + const warning = result.deprecationWarnings[i].message + deprecationWarnings.push({ + message: warning, + stack: result.deprecationWarnings[i].stack, + runnableName: result.fullName, + runnableType: runnableType, + }) + } + } + } + + function createExpander(stackTrace) { + const expandLink = createDom("a", { href: "#" }, "Show stack trace") + const root = createDom( + "div", + { className: "jasmine-expander" }, + expandLink, + createDom("div", { className: "jasmine-expander-contents jasmine-stack-trace" }, stackTrace) ) - ), - createDom( - 'div', - { className: 'jasmine-hide-disabled' }, - createDom('input', { - className: 'jasmine-disabled', - id: 'jasmine-hide-disabled', - type: 'checkbox' - }), - createDom( - 'label', - { className: 'jasmine-label', for: 'jasmine-hide-disabled' }, - 'hide disabled tests' - ) - ) - ) - ); - const failFastCheckbox = optionsMenuDom.querySelector( - '#jasmine-fail-fast' - ); - failFastCheckbox.checked = config.stopOnSpecFailure; - failFastCheckbox.onclick = function() { - navigateWithNewParam('stopOnSpecFailure', !config.stopOnSpecFailure); - }; + expandLink.addEventListener("click", function(e) { + e.preventDefault() - const throwCheckbox = optionsMenuDom.querySelector( - '#jasmine-throw-failures' - ); - throwCheckbox.checked = config.stopSpecOnExpectationFailure; - throwCheckbox.onclick = function() { - navigateWithNewParam( - 'stopSpecOnExpectationFailure', - !config.stopSpecOnExpectationFailure - ); - }; + if (root.classList.contains("jasmine-expanded")) { + root.classList.remove("jasmine-expanded") + expandLink.textContent = "Show stack trace" + } else { + root.classList.add("jasmine-expanded") + expandLink.textContent = "Hide stack trace" + } + }) - const randomCheckbox = optionsMenuDom.querySelector( - '#jasmine-random-order' - ); - randomCheckbox.checked = config.random; - randomCheckbox.onclick = function() { - navigateWithNewParam('random', !config.random); - }; - - const hideDisabled = optionsMenuDom.querySelector( - '#jasmine-hide-disabled' - ); - hideDisabled.checked = config.hideDisabled; - hideDisabled.onclick = function() { - navigateWithNewParam('hideDisabled', !config.hideDisabled); - }; - - const optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), - optionsPayload = optionsMenuDom.querySelector('.jasmine-payload'), - isOpen = /\bjasmine-open\b/; - - optionsTrigger.onclick = function() { - if (isOpen.test(optionsPayload.className)) { - optionsPayload.className = optionsPayload.className.replace( - isOpen, - '' - ); - } else { - optionsPayload.className += ' jasmine-open'; + return root } - }; - return optionsMenuDom; - } - - function failureDescription(result, suite) { - const wrapper = createDom( - 'div', - { className: 'jasmine-description' }, - createDom( - 'a', - { title: result.description, href: specHref(result) }, - result.description - ) - ); - let suiteLink; - - while (suite && suite.parent) { - wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); - suiteLink = createDom( - 'a', - { href: suiteHref(suite) }, - suite.result.description - ); - wrapper.insertBefore(suiteLink, wrapper.firstChild); - - suite = suite.parent; - } - - return wrapper; - } - - function suiteHref(suite) { - const els = []; - - while (suite && suite.parent) { - els.unshift(suite.result.description); - suite = suite.parent; - } - - // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - return ( - (window.location.pathname || '') + - addToExistingQueryString('spec', els.join(' ')) - ); - } - - function addDeprecationWarnings(result, runnableType) { - if (result && result.deprecationWarnings) { - for (let i = 0; i < result.deprecationWarnings.length; i++) { - const warning = result.deprecationWarnings[i].message; - deprecationWarnings.push({ - message: warning, - stack: result.deprecationWarnings[i].stack, - runnableName: result.fullName, - runnableType: runnableType - }); + function find(selector) { + return getContainer().querySelector(".jasmine_html-reporter " + selector) } - } - } - function createExpander(stackTrace) { - const expandLink = createDom('a', { href: '#' }, 'Show stack trace'); - const root = createDom( - 'div', - { className: 'jasmine-expander' }, - expandLink, - createDom( - 'div', - { className: 'jasmine-expander-contents jasmine-stack-trace' }, - stackTrace - ) - ); + function clearPrior() { + const oldReporter = find("") - expandLink.addEventListener('click', function(e) { - e.preventDefault(); - - if (root.classList.contains('jasmine-expanded')) { - root.classList.remove('jasmine-expanded'); - expandLink.textContent = 'Show stack trace'; - } else { - root.classList.add('jasmine-expanded'); - expandLink.textContent = 'Hide stack trace'; + if (oldReporter) { + getContainer().removeChild(oldReporter) + } } - }); - return root; - } + function createDom(type, attrs, childrenArrayOrVarArgs) { + const el = createElement(type) + let children - function find(selector) { - return getContainer().querySelector('.jasmine_html-reporter ' + selector); - } + if (j$.isArray_(childrenArrayOrVarArgs)) { + children = childrenArrayOrVarArgs + } else { + children = [] - function clearPrior() { - const oldReporter = find(''); + for (let i = 2; i < arguments.length; i++) { + children.push(arguments[i]) + } + } - if (oldReporter) { - getContainer().removeChild(oldReporter); - } - } + for (let i = 0; i < children.length; i++) { + const child = children[i] - function createDom(type, attrs, childrenArrayOrVarArgs) { - const el = createElement(type); - let children; + if (typeof child === "string") { + el.appendChild(createTextNode(child)) + } else { + if (child) { + el.appendChild(child) + } + } + } - if (j$.isArray_(childrenArrayOrVarArgs)) { - children = childrenArrayOrVarArgs; - } else { - children = []; + for (const attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr] + } else { + el.setAttribute(attr, attrs[attr]) + } + } - for (let i = 2; i < arguments.length; i++) { - children.push(arguments[i]); + return el } - } - for (let i = 0; i < children.length; i++) { - const child = children[i]; + function pluralize(singular, count) { + const word = count == 1 ? singular : singular + "s" - if (typeof child === 'string') { - el.appendChild(createTextNode(child)); - } else { - if (child) { - el.appendChild(child); - } + return "" + count + " " + word } - } - for (const attr in attrs) { - if (attr == 'className') { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); + function specHref(result) { + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return (window.location.pathname || "") + addToExistingQueryString("spec", result.fullName) } - } - return el; - } - - function pluralize(singular, count) { - const word = count == 1 ? singular : singular + 's'; - - return '' + count + ' ' + word; - } - - function specHref(result) { - // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - return ( - (window.location.pathname || '') + - addToExistingQueryString('spec', result.fullName) - ); - } - - function seedHref(seed) { - // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 - return ( - (window.location.pathname || '') + - addToExistingQueryString('seed', seed) - ); - } - - function defaultQueryString(key, value) { - return '?' + key + '=' + value; - } - - function setMenuModeTo(mode) { - htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); - } - - function noExpectations(result) { - const allExpectations = - result.failedExpectations.length + result.passedExpectations.length; - - return ( - allExpectations === 0 && - (result.status === 'passed' || result.status === 'failed') - ); - } - - function hasActiveSpec(resultNode) { - if (resultNode.type == 'spec' && resultNode.result.status != 'excluded') { - return true; - } - - if (resultNode.type == 'suite') { - for (let i = 0, j = resultNode.children.length; i < j; i++) { - if (hasActiveSpec(resultNode.children[i])) { - return true; - } + function seedHref(seed) { + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return (window.location.pathname || "") + addToExistingQueryString("seed", seed) } - } - } - } - return HtmlReporter; -}; + function defaultQueryString(key, value) { + return "?" + key + "=" + value + } + + function setMenuModeTo(mode) { + htmlReporterMain.setAttribute("class", "jasmine_html-reporter " + mode) + } + + function noExpectations(result) { + const allExpectations = result.failedExpectations.length + result.passedExpectations.length + + return allExpectations === 0 && (result.status === "passed" || result.status === "failed") + } + + function hasActiveSpec(resultNode) { + if (resultNode.type == "spec" && resultNode.result.status != "excluded") { + return true + } + + if (resultNode.type == "suite") { + for (let i = 0, j = resultNode.children.length; i < j; i++) { + if (hasActiveSpec(resultNode.children[i])) { + return true + } + } + } + } + } + + return HtmlReporter +} jasmineRequire.HtmlSpecFilter = function() { - function HtmlSpecFilter(options) { - const filterString = - options && - options.filterString() && - options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); - const filterPattern = new RegExp(filterString); + function HtmlSpecFilter(options) { + const filterString = + options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + const filterPattern = new RegExp(filterString) - this.matches = function(specName) { - return filterPattern.test(specName); - }; - } + this.matches = function(specName) { + return filterPattern.test(specName) + } + } - return HtmlSpecFilter; -}; + return HtmlSpecFilter +} jasmineRequire.ResultsNode = function() { - function ResultsNode(result, type, parent) { - this.result = result; - this.type = type; - this.parent = parent; + function ResultsNode(result, type, parent) { + this.result = result + this.type = type + this.parent = parent - this.children = []; + this.children = [] - this.addChild = function(result, type) { - this.children.push(new ResultsNode(result, type, this)); - }; + this.addChild = function(result, type) { + this.children.push(new ResultsNode(result, type, this)) + } - this.last = function() { - return this.children[this.children.length - 1]; - }; + this.last = function() { + return this.children[this.children.length - 1] + } - this.updateResult = function(result) { - this.result = result; - }; - } + this.updateResult = function(result) { + this.result = result + } + } - return ResultsNode; -}; + return ResultsNode +} jasmineRequire.QueryString = function() { - function QueryString(options) { - this.navigateWithNewParam = function(key, value) { - options.getWindowLocation().search = this.fullStringWithNewParam( - key, - value - ); - }; - - this.fullStringWithNewParam = function(key, value) { - const paramMap = queryStringToParamMap(); - paramMap[key] = value; - return toQueryString(paramMap); - }; - - this.getParam = function(key) { - return queryStringToParamMap()[key]; - }; - - return this; - - function toQueryString(paramMap) { - const qStrPairs = []; - for (const prop in paramMap) { - qStrPairs.push( - encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) - ); - } - return '?' + qStrPairs.join('&'); - } - - function queryStringToParamMap() { - const paramStr = options.getWindowLocation().search.substring(1); - let params = []; - const paramMap = {}; - - if (paramStr.length > 0) { - params = paramStr.split('&'); - for (let i = 0; i < params.length; i++) { - const p = params[i].split('='); - let value = decodeURIComponent(p[1]); - if (value === 'true' || value === 'false') { - value = JSON.parse(value); - } - paramMap[decodeURIComponent(p[0])] = value; + function QueryString(options) { + this.navigateWithNewParam = function(key, value) { + options.getWindowLocation().search = this.fullStringWithNewParam(key, value) } - } - return paramMap; + this.fullStringWithNewParam = function(key, value) { + const paramMap = queryStringToParamMap() + paramMap[key] = value + return toQueryString(paramMap) + } + + this.getParam = function(key) { + return queryStringToParamMap()[key] + } + + return this + + function toQueryString(paramMap) { + const qStrPairs = [] + for (const prop in paramMap) { + qStrPairs.push(encodeURIComponent(prop) + "=" + encodeURIComponent(paramMap[prop])) + } + return "?" + qStrPairs.join("&") + } + + function queryStringToParamMap() { + const paramStr = options.getWindowLocation().search.substring(1) + let params = [] + const paramMap = {} + + if (paramStr.length > 0) { + params = paramStr.split("&") + for (let i = 0; i < params.length; i++) { + const p = params[i].split("=") + let value = decodeURIComponent(p[1]) + if (value === "true" || value === "false") { + value = JSON.parse(value) + } + paramMap[decodeURIComponent(p[0])] = value + } + } + + return paramMap + } } - } - return QueryString; -}; + return QueryString +} diff --git a/ui/plugins/ui/jasmine/jasmine.js b/ui/plugins/ui/jasmine/jasmine.js index 9160c753..5bbcadfc 100644 --- a/ui/plugins/ui/jasmine/jasmine.js +++ b/ui/plugins/ui/jasmine/jasmine.js @@ -22,5221 +22,4897 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // eslint-disable-next-line no-unused-vars,no-var var getJasmineRequireObj = (function(jasmineGlobal) { - let jasmineRequire; + let jasmineRequire - if ( - typeof module !== 'undefined' && - module.exports && - typeof exports !== 'undefined' - ) { - if (typeof global !== 'undefined') { - jasmineGlobal = global; + if (typeof module !== "undefined" && module.exports && typeof exports !== "undefined") { + if (typeof global !== "undefined") { + jasmineGlobal = global + } else { + jasmineGlobal = {} + } + jasmineRequire = exports } else { - jasmineGlobal = {}; + if ( + typeof window !== "undefined" && + typeof window.toString === "function" && + window.toString() === "[object GjsGlobal]" + ) { + jasmineGlobal = window + } + jasmineRequire = jasmineGlobal.jasmineRequire = {} } - jasmineRequire = exports; - } else { - if ( - typeof window !== 'undefined' && - typeof window.toString === 'function' && - window.toString() === '[object GjsGlobal]' - ) { - jasmineGlobal = window; + + function getJasmineRequire() { + return jasmineRequire } - jasmineRequire = jasmineGlobal.jasmineRequire = {}; - } - function getJasmineRequire() { - return jasmineRequire; - } + getJasmineRequire().core = function(jRequire) { + const j$ = {} - getJasmineRequire().core = function(jRequire) { - const j$ = {}; + jRequire.base(j$, jasmineGlobal) + j$.util = jRequire.util(j$) + j$.errors = jRequire.errors() + j$.formatErrorMsg = jRequire.formatErrorMsg() + j$.Any = jRequire.Any(j$) + j$.Anything = jRequire.Anything(j$) + j$.CallTracker = jRequire.CallTracker(j$) + j$.MockDate = jRequire.MockDate(j$) + j$.getClearStack = jRequire.clearStack(j$) + j$.Clock = jRequire.Clock() + j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$) + j$.Deprecator = jRequire.Deprecator(j$) + j$.Env = jRequire.Env(j$) + j$.StackTrace = jRequire.StackTrace(j$) + j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$) + j$.ExpectationFilterChain = jRequire.ExpectationFilterChain() + j$.Expector = jRequire.Expector(j$) + j$.Expectation = jRequire.Expectation(j$) + j$.buildExpectationResult = jRequire.buildExpectationResult(j$) + j$.JsApiReporter = jRequire.JsApiReporter(j$) + j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$) + j$.basicPrettyPrinter_ = j$.makePrettyPrinter() + j$.MatchersUtil = jRequire.MatchersUtil(j$) + j$.ObjectContaining = jRequire.ObjectContaining(j$) + j$.ArrayContaining = jRequire.ArrayContaining(j$) + j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$) + j$.MapContaining = jRequire.MapContaining(j$) + j$.SetContaining = jRequire.SetContaining(j$) + j$.QueueRunner = jRequire.QueueRunner(j$) + j$.NeverSkipPolicy = jRequire.NeverSkipPolicy(j$) + j$.SkipAfterBeforeAllErrorPolicy = jRequire.SkipAfterBeforeAllErrorPolicy(j$) + j$.CompleteOnFirstErrorSkipPolicy = jRequire.CompleteOnFirstErrorSkipPolicy(j$) + j$.ReportDispatcher = jRequire.ReportDispatcher(j$) + j$.RunableResources = jRequire.RunableResources(j$) + j$.Runner = jRequire.Runner(j$) + j$.Spec = jRequire.Spec(j$) + j$.Spy = jRequire.Spy(j$) + j$.SpyFactory = jRequire.SpyFactory(j$) + j$.SpyRegistry = jRequire.SpyRegistry(j$) + j$.SpyStrategy = jRequire.SpyStrategy(j$) + j$.StringMatching = jRequire.StringMatching(j$) + j$.StringContaining = jRequire.StringContaining(j$) + j$.UserContext = jRequire.UserContext(j$) + j$.Suite = jRequire.Suite(j$) + j$.SuiteBuilder = jRequire.SuiteBuilder(j$) + j$.Timer = jRequire.Timer() + j$.TreeProcessor = jRequire.TreeProcessor() + j$.version = jRequire.version() + j$.Order = jRequire.Order() + j$.DiffBuilder = jRequire.DiffBuilder(j$) + j$.NullDiffBuilder = jRequire.NullDiffBuilder(j$) + j$.ObjectPath = jRequire.ObjectPath(j$) + j$.MismatchTree = jRequire.MismatchTree(j$) + j$.GlobalErrors = jRequire.GlobalErrors(j$) - jRequire.base(j$, jasmineGlobal); - j$.util = jRequire.util(j$); - j$.errors = jRequire.errors(); - j$.formatErrorMsg = jRequire.formatErrorMsg(); - j$.Any = jRequire.Any(j$); - j$.Anything = jRequire.Anything(j$); - j$.CallTracker = jRequire.CallTracker(j$); - j$.MockDate = jRequire.MockDate(j$); - j$.getClearStack = jRequire.clearStack(j$); - j$.Clock = jRequire.Clock(); - j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$); - j$.Deprecator = jRequire.Deprecator(j$); - j$.Env = jRequire.Env(j$); - j$.StackTrace = jRequire.StackTrace(j$); - j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); - j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); - j$.Expector = jRequire.Expector(j$); - j$.Expectation = jRequire.Expectation(j$); - j$.buildExpectationResult = jRequire.buildExpectationResult(j$); - j$.JsApiReporter = jRequire.JsApiReporter(j$); - j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$); - j$.basicPrettyPrinter_ = j$.makePrettyPrinter(); - j$.MatchersUtil = jRequire.MatchersUtil(j$); - j$.ObjectContaining = jRequire.ObjectContaining(j$); - j$.ArrayContaining = jRequire.ArrayContaining(j$); - j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); - j$.MapContaining = jRequire.MapContaining(j$); - j$.SetContaining = jRequire.SetContaining(j$); - j$.QueueRunner = jRequire.QueueRunner(j$); - j$.NeverSkipPolicy = jRequire.NeverSkipPolicy(j$); - j$.SkipAfterBeforeAllErrorPolicy = jRequire.SkipAfterBeforeAllErrorPolicy( - j$ - ); - j$.CompleteOnFirstErrorSkipPolicy = jRequire.CompleteOnFirstErrorSkipPolicy( - j$ - ); - j$.ReportDispatcher = jRequire.ReportDispatcher(j$); - j$.RunableResources = jRequire.RunableResources(j$); - j$.Runner = jRequire.Runner(j$); - j$.Spec = jRequire.Spec(j$); - j$.Spy = jRequire.Spy(j$); - j$.SpyFactory = jRequire.SpyFactory(j$); - j$.SpyRegistry = jRequire.SpyRegistry(j$); - j$.SpyStrategy = jRequire.SpyStrategy(j$); - j$.StringMatching = jRequire.StringMatching(j$); - j$.StringContaining = jRequire.StringContaining(j$); - j$.UserContext = jRequire.UserContext(j$); - j$.Suite = jRequire.Suite(j$); - j$.SuiteBuilder = jRequire.SuiteBuilder(j$); - j$.Timer = jRequire.Timer(); - j$.TreeProcessor = jRequire.TreeProcessor(); - j$.version = jRequire.version(); - j$.Order = jRequire.Order(); - j$.DiffBuilder = jRequire.DiffBuilder(j$); - j$.NullDiffBuilder = jRequire.NullDiffBuilder(j$); - j$.ObjectPath = jRequire.ObjectPath(j$); - j$.MismatchTree = jRequire.MismatchTree(j$); - j$.GlobalErrors = jRequire.GlobalErrors(j$); + j$.Truthy = jRequire.Truthy(j$) + j$.Falsy = jRequire.Falsy(j$) + j$.Empty = jRequire.Empty(j$) + j$.NotEmpty = jRequire.NotEmpty(j$) + j$.Is = jRequire.Is(j$) - j$.Truthy = jRequire.Truthy(j$); - j$.Falsy = jRequire.Falsy(j$); - j$.Empty = jRequire.Empty(j$); - j$.NotEmpty = jRequire.NotEmpty(j$); - j$.Is = jRequire.Is(j$); + j$.matchers = jRequire.requireMatchers(jRequire, j$) + j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$) - j$.matchers = jRequire.requireMatchers(jRequire, j$); - j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$); + return j$ + } - return j$; - }; - - return getJasmineRequire; -})(this); + return getJasmineRequire +})(this) getJasmineRequireObj().requireMatchers = function(jRequire, j$) { - const availableMatchers = [ - 'nothing', - 'toBe', - 'toBeCloseTo', - 'toBeDefined', - 'toBeInstanceOf', - 'toBeFalse', - 'toBeFalsy', - 'toBeGreaterThan', - 'toBeGreaterThanOrEqual', - 'toBeLessThan', - 'toBeLessThanOrEqual', - 'toBeNaN', - 'toBeNegativeInfinity', - 'toBeNull', - 'toBePositiveInfinity', - 'toBeTrue', - 'toBeTruthy', - 'toBeUndefined', - 'toContain', - 'toEqual', - 'toHaveSize', - 'toHaveBeenCalled', - 'toHaveBeenCalledBefore', - 'toHaveBeenCalledOnceWith', - 'toHaveBeenCalledTimes', - 'toHaveBeenCalledWith', - 'toHaveClass', - 'toHaveSpyInteractions', - 'toMatch', - 'toThrow', - 'toThrowError', - 'toThrowMatching' - ], - matchers = {}; + const availableMatchers = [ + "nothing", + "toBe", + "toBeCloseTo", + "toBeDefined", + "toBeInstanceOf", + "toBeFalse", + "toBeFalsy", + "toBeGreaterThan", + "toBeGreaterThanOrEqual", + "toBeLessThan", + "toBeLessThanOrEqual", + "toBeNaN", + "toBeNegativeInfinity", + "toBeNull", + "toBePositiveInfinity", + "toBeTrue", + "toBeTruthy", + "toBeUndefined", + "toContain", + "toEqual", + "toHaveSize", + "toHaveBeenCalled", + "toHaveBeenCalledBefore", + "toHaveBeenCalledOnceWith", + "toHaveBeenCalledTimes", + "toHaveBeenCalledWith", + "toHaveClass", + "toHaveSpyInteractions", + "toMatch", + "toThrow", + "toThrowError", + "toThrowMatching", + ], + matchers = {} - for (const name of availableMatchers) { - matchers[name] = jRequire[name](j$); - } + for (const name of availableMatchers) { + matchers[name] = jRequire[name](j$) + } - return matchers; -}; + return matchers +} getJasmineRequireObj().base = function(j$, jasmineGlobal) { - /** - * Maximum object depth the pretty printer will print to. - * Set this to a lower value to speed up pretty printing if you have large objects. - * @name jasmine.MAX_PRETTY_PRINT_DEPTH - * @default 8 - * @since 1.3.0 - */ - j$.MAX_PRETTY_PRINT_DEPTH = 8; - /** - * Maximum number of array elements to display when pretty printing objects. - * This will also limit the number of keys and values displayed for an object. - * Elements past this number will be ellipised. - * @name jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH - * @default 50 - * @since 2.7.0 - */ - j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 50; - /** - * Maximum number of characters to display when pretty printing objects. - * Characters past this number will be ellipised. - * @name jasmine.MAX_PRETTY_PRINT_CHARS - * @default 100 - * @since 2.9.0 - */ - j$.MAX_PRETTY_PRINT_CHARS = 1000; - /** - * Default number of milliseconds Jasmine will wait for an asynchronous spec, - * before, or after function to complete. This can be overridden on a case by - * case basis by passing a time limit as the third argument to {@link it}, - * {@link beforeEach}, {@link afterEach}, {@link beforeAll}, or - * {@link afterAll}. The value must be no greater than the largest number of - * milliseconds supported by setTimeout, which is usually 2147483647. - * - * While debugging tests, you may want to set this to a large number (or pass - * a large number to one of the functions mentioned above) so that Jasmine - * does not move on to after functions or the next spec while you're debugging. - * @name jasmine.DEFAULT_TIMEOUT_INTERVAL - * @default 5000 - * @since 1.3.0 - */ - let DEFAULT_TIMEOUT_INTERVAL = 5000; - Object.defineProperty(j$, 'DEFAULT_TIMEOUT_INTERVAL', { - get: function() { - return DEFAULT_TIMEOUT_INTERVAL; - }, - set: function(newValue) { - j$.util.validateTimeout(newValue, 'jasmine.DEFAULT_TIMEOUT_INTERVAL'); - DEFAULT_TIMEOUT_INTERVAL = newValue; - } - }); + /** + * Maximum object depth the pretty printer will print to. + * Set this to a lower value to speed up pretty printing if you have large objects. + * @name jasmine.MAX_PRETTY_PRINT_DEPTH + * @default 8 + * @since 1.3.0 + */ + j$.MAX_PRETTY_PRINT_DEPTH = 8 + /** + * Maximum number of array elements to display when pretty printing objects. + * This will also limit the number of keys and values displayed for an object. + * Elements past this number will be ellipised. + * @name jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH + * @default 50 + * @since 2.7.0 + */ + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 50 + /** + * Maximum number of characters to display when pretty printing objects. + * Characters past this number will be ellipised. + * @name jasmine.MAX_PRETTY_PRINT_CHARS + * @default 100 + * @since 2.9.0 + */ + j$.MAX_PRETTY_PRINT_CHARS = 1000 + /** + * Default number of milliseconds Jasmine will wait for an asynchronous spec, + * before, or after function to complete. This can be overridden on a case by + * case basis by passing a time limit as the third argument to {@link it}, + * {@link beforeEach}, {@link afterEach}, {@link beforeAll}, or + * {@link afterAll}. The value must be no greater than the largest number of + * milliseconds supported by setTimeout, which is usually 2147483647. + * + * While debugging tests, you may want to set this to a large number (or pass + * a large number to one of the functions mentioned above) so that Jasmine + * does not move on to after functions or the next spec while you're debugging. + * @name jasmine.DEFAULT_TIMEOUT_INTERVAL + * @default 5000 + * @since 1.3.0 + */ + let DEFAULT_TIMEOUT_INTERVAL = 5000 + Object.defineProperty(j$, "DEFAULT_TIMEOUT_INTERVAL", { + get: function() { + return DEFAULT_TIMEOUT_INTERVAL + }, + set: function(newValue) { + j$.util.validateTimeout(newValue, "jasmine.DEFAULT_TIMEOUT_INTERVAL") + DEFAULT_TIMEOUT_INTERVAL = newValue + }, + }) - j$.getGlobal = function() { - return jasmineGlobal; - }; - - /** - * Get the currently booted Jasmine Environment. - * - * @name jasmine.getEnv - * @since 1.3.0 - * @function - * @return {Env} - */ - j$.getEnv = function(options) { - const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); - //jasmine. singletons in here (setTimeout blah blah). - return env; - }; - - j$.isArray_ = function(value) { - return j$.isA_('Array', value); - }; - - j$.isObject_ = function(value) { - return ( - !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value) - ); - }; - - j$.isString_ = function(value) { - return j$.isA_('String', value); - }; - - j$.isNumber_ = function(value) { - return j$.isA_('Number', value); - }; - - j$.isFunction_ = function(value) { - return j$.isA_('Function', value); - }; - - j$.isAsyncFunction_ = function(value) { - return j$.isA_('AsyncFunction', value); - }; - - j$.isGeneratorFunction_ = function(value) { - return j$.isA_('GeneratorFunction', value); - }; - - j$.isTypedArray_ = function(value) { - return ( - j$.isA_('Float32Array', value) || - j$.isA_('Float64Array', value) || - j$.isA_('Int16Array', value) || - j$.isA_('Int32Array', value) || - j$.isA_('Int8Array', value) || - j$.isA_('Uint16Array', value) || - j$.isA_('Uint32Array', value) || - j$.isA_('Uint8Array', value) || - j$.isA_('Uint8ClampedArray', value) - ); - }; - - j$.isA_ = function(typeName, value) { - return j$.getType_(value) === '[object ' + typeName + ']'; - }; - - j$.isError_ = function(value) { - if (!value) { - return false; + j$.getGlobal = function() { + return jasmineGlobal } - if (value instanceof Error) { - return true; + /** + * Get the currently booted Jasmine Environment. + * + * @name jasmine.getEnv + * @since 1.3.0 + * @function + * @return {Env} + */ + j$.getEnv = function(options) { + const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)) + //jasmine. singletons in here (setTimeout blah blah). + return env } - return typeof value.stack === 'string' && typeof value.message === 'string'; - }; - - j$.isAsymmetricEqualityTester_ = function(obj) { - return obj ? j$.isA_('Function', obj.asymmetricMatch) : false; - }; - - j$.getType_ = function(value) { - return Object.prototype.toString.apply(value); - }; - - j$.isDomNode = function(obj) { - // Node is a function, because constructors - return typeof jasmineGlobal.Node !== 'undefined' - ? obj instanceof jasmineGlobal.Node - : obj !== null && - typeof obj === 'object' && - typeof obj.nodeType === 'number' && - typeof obj.nodeName === 'string'; - // return obj.nodeType > 0; - }; - - j$.isMap = function(obj) { - return ( - obj !== null && - typeof obj !== 'undefined' && - obj.constructor === jasmineGlobal.Map - ); - }; - - j$.isSet = function(obj) { - return ( - obj !== null && - typeof obj !== 'undefined' && - obj.constructor === jasmineGlobal.Set - ); - }; - - j$.isWeakMap = function(obj) { - return ( - obj !== null && - typeof obj !== 'undefined' && - obj.constructor === jasmineGlobal.WeakMap - ); - }; - - j$.isURL = function(obj) { - return ( - obj !== null && - typeof obj !== 'undefined' && - obj.constructor === jasmineGlobal.URL - ); - }; - - j$.isIterable_ = function(value) { - return value && !!value[Symbol.iterator]; - }; - - j$.isDataView = function(obj) { - return ( - obj !== null && - typeof obj !== 'undefined' && - obj.constructor === jasmineGlobal.DataView - ); - }; - - j$.isPromise = function(obj) { - return !!obj && obj.constructor === jasmineGlobal.Promise; - }; - - j$.isPromiseLike = function(obj) { - return !!obj && j$.isFunction_(obj.then); - }; - - j$.fnNameFor = function(func) { - if (func.name) { - return func.name; + j$.isArray_ = function(value) { + return j$.isA_("Array", value) } - const matches = - func.toString().match(/^\s*function\s*(\w+)\s*\(/) || - func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); - - return matches ? matches[1] : ''; - }; - - j$.isPending_ = function(promise) { - const sentinel = {}; - return Promise.race([promise, Promise.resolve(sentinel)]).then( - function(result) { - return result === sentinel; - }, - function() { - return false; - } - ); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is an instance of the specified class/constructor. - * @name jasmine.any - * @since 1.3.0 - * @function - * @param {Constructor} clazz - The constructor to check against. - */ - j$.any = function(clazz) { - return new j$.Any(clazz); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is not `null` and not `undefined`. - * @name jasmine.anything - * @since 2.2.0 - * @function - */ - j$.anything = function() { - return new j$.Anything(); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is `true` or anything truthy. - * @name jasmine.truthy - * @since 3.1.0 - * @function - */ - j$.truthy = function() { - return new j$.Truthy(); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is `null`, `undefined`, `0`, `false` or anything falsey. - * @name jasmine.falsy - * @since 3.1.0 - * @function - */ - j$.falsy = function() { - return new j$.Falsy(); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is empty. - * @name jasmine.empty - * @since 3.1.0 - * @function - */ - j$.empty = function() { - return new j$.Empty(); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} - * that passes if the actual value is the same as the sample as determined - * by the `===` operator. - * @name jasmine.is - * @function - * @param {Object} sample - The value to compare the actual to. - */ - j$.is = function(sample) { - return new j$.Is(sample); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared is not empty. - * @name jasmine.notEmpty - * @since 3.1.0 - * @function - */ - j$.notEmpty = function() { - return new j$.NotEmpty(); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value being compared contains at least the keys and values. - * @name jasmine.objectContaining - * @since 1.3.0 - * @function - * @param {Object} sample - The subset of properties that _must_ be in the actual. - */ - j$.objectContaining = function(sample) { - return new j$.ObjectContaining(sample); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value is a `String` that matches the `RegExp` or `String`. - * @name jasmine.stringMatching - * @since 2.2.0 - * @function - * @param {RegExp|String} expected - */ - j$.stringMatching = function(expected) { - return new j$.StringMatching(expected); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value is a `String` that contains the specified `String`. - * @name jasmine.stringContaining - * @since 3.10.0 - * @function - * @param {String} expected - */ - j$.stringContaining = function(expected) { - return new j$.StringContaining(expected); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value is an `Array` that contains at least the elements in the sample. - * @name jasmine.arrayContaining - * @since 2.2.0 - * @function - * @param {Array} sample - */ - j$.arrayContaining = function(sample) { - return new j$.ArrayContaining(sample); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if the actual value is an `Array` that contains all of the elements in the sample in any order. - * @name jasmine.arrayWithExactContents - * @since 2.8.0 - * @function - * @param {Array} sample - */ - j$.arrayWithExactContents = function(sample) { - return new j$.ArrayWithExactContents(sample); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if every key/value pair in the sample passes the deep equality comparison - * with at least one key/value pair in the actual value being compared - * @name jasmine.mapContaining - * @since 3.5.0 - * @function - * @param {Map} sample - The subset of items that _must_ be in the actual. - */ - j$.mapContaining = function(sample) { - return new j$.MapContaining(sample); - }; - - /** - * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), - * that will succeed if every item in the sample passes the deep equality comparison - * with at least one item in the actual value being compared - * @name jasmine.setContaining - * @since 3.5.0 - * @function - * @param {Set} sample - The subset of items that _must_ be in the actual. - */ - j$.setContaining = function(sample) { - return new j$.SetContaining(sample); - }; - - /** - * Determines whether the provided function is a Jasmine spy. - * @name jasmine.isSpy - * @since 2.0.0 - * @function - * @param {Function} putativeSpy - The function to check. - * @return {Boolean} - */ - j$.isSpy = function(putativeSpy) { - if (!putativeSpy) { - return false; + j$.isObject_ = function(value) { + return !j$.util.isUndefined(value) && value !== null && j$.isA_("Object", value) } - return ( - putativeSpy.and instanceof j$.SpyStrategy && - putativeSpy.calls instanceof j$.CallTracker - ); - }; - /** - * Logs a message for use in debugging. If the spec fails, trace messages - * will be included in the {@link SpecResult|result} passed to the - * reporter's specDone method. - * - * This method should be called only when a spec (including any associated - * beforeEach or afterEach functions) is running. - * @function - * @name jasmine.debugLog - * @since 4.0.0 - * @param {String} msg - The message to log - */ - j$.debugLog = function(msg) { - j$.getEnv().debugLog(msg); - }; + j$.isString_ = function(value) { + return j$.isA_("String", value) + } - /** - * Replaces Jasmine's global error handling with a spy. This prevents Jasmine - * from treating uncaught exceptions and unhandled promise rejections - * as spec failures and allows them to be inspected using the spy's - * {@link Spy#calls|calls property} and related matchers such as - * {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}. - * - * After installing the spy, spyOnGlobalErrorsAsync immediately calls its - * argument, which must be an async or promise-returning function. The spy - * will be passed as the first argument to that callback. Normal error - * handling will be restored when the promise returned from the callback is - * settled. - * - * Note: The JavaScript runtime may deliver uncaught error events and unhandled - * rejection events asynchronously, especially in browsers. If the event - * occurs after the promise returned from the callback is settled, it won't - * be routed to the spy even if the underlying error occurred previously. - * It's up to you to ensure that the returned promise isn't resolved until - * all of the error/rejection events that you want to handle have occurred. - * - * You must await the return value of spyOnGlobalErrorsAsync. - * @name jasmine.spyOnGlobalErrorsAsync - * @function - * @async - * @param {AsyncFunction} fn - A function to run, during which the global error spy will be effective - * @example - * it('demonstrates global error spies', async function() { - * await jasmine.spyOnGlobalErrorsAsync(async function(globalErrorSpy) { - * setTimeout(function() { - * throw new Error('the expected error'); - * }); - * await new Promise(function(resolve) { - * setTimeout(resolve); - * }); - * const expected = new Error('the expected error'); - * expect(globalErrorSpy).toHaveBeenCalledWith(expected); - * }); - * }); - */ - j$.spyOnGlobalErrorsAsync = async function(fn) { - await jasmine.getEnv().spyOnGlobalErrorsAsync(fn); - }; -}; + j$.isNumber_ = function(value) { + return j$.isA_("Number", value) + } + + j$.isFunction_ = function(value) { + return j$.isA_("Function", value) + } + + j$.isAsyncFunction_ = function(value) { + return j$.isA_("AsyncFunction", value) + } + + j$.isGeneratorFunction_ = function(value) { + return j$.isA_("GeneratorFunction", value) + } + + j$.isTypedArray_ = function(value) { + return ( + j$.isA_("Float32Array", value) || + j$.isA_("Float64Array", value) || + j$.isA_("Int16Array", value) || + j$.isA_("Int32Array", value) || + j$.isA_("Int8Array", value) || + j$.isA_("Uint16Array", value) || + j$.isA_("Uint32Array", value) || + j$.isA_("Uint8Array", value) || + j$.isA_("Uint8ClampedArray", value) + ) + } + + j$.isA_ = function(typeName, value) { + return j$.getType_(value) === "[object " + typeName + "]" + } + + j$.isError_ = function(value) { + if (!value) { + return false + } + + if (value instanceof Error) { + return true + } + + return typeof value.stack === "string" && typeof value.message === "string" + } + + j$.isAsymmetricEqualityTester_ = function(obj) { + return obj ? j$.isA_("Function", obj.asymmetricMatch) : false + } + + j$.getType_ = function(value) { + return Object.prototype.toString.apply(value) + } + + j$.isDomNode = function(obj) { + // Node is a function, because constructors + return typeof jasmineGlobal.Node !== "undefined" + ? obj instanceof jasmineGlobal.Node + : obj !== null && + typeof obj === "object" && + typeof obj.nodeType === "number" && + typeof obj.nodeName === "string" + // return obj.nodeType > 0; + } + + j$.isMap = function(obj) { + return obj !== null && typeof obj !== "undefined" && obj.constructor === jasmineGlobal.Map + } + + j$.isSet = function(obj) { + return obj !== null && typeof obj !== "undefined" && obj.constructor === jasmineGlobal.Set + } + + j$.isWeakMap = function(obj) { + return obj !== null && typeof obj !== "undefined" && obj.constructor === jasmineGlobal.WeakMap + } + + j$.isURL = function(obj) { + return obj !== null && typeof obj !== "undefined" && obj.constructor === jasmineGlobal.URL + } + + j$.isIterable_ = function(value) { + return value && !!value[Symbol.iterator] + } + + j$.isDataView = function(obj) { + return obj !== null && typeof obj !== "undefined" && obj.constructor === jasmineGlobal.DataView + } + + j$.isPromise = function(obj) { + return !!obj && obj.constructor === jasmineGlobal.Promise + } + + j$.isPromiseLike = function(obj) { + return !!obj && j$.isFunction_(obj.then) + } + + j$.fnNameFor = function(func) { + if (func.name) { + return func.name + } + + const matches = + func.toString().match(/^\s*function\s*(\w+)\s*\(/) || + func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/) + + return matches ? matches[1] : "" + } + + j$.isPending_ = function(promise) { + const sentinel = {} + return Promise.race([promise, Promise.resolve(sentinel)]).then( + function(result) { + return result === sentinel + }, + function() { + return false + } + ) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is an instance of the specified class/constructor. + * @name jasmine.any + * @since 1.3.0 + * @function + * @param {Constructor} clazz - The constructor to check against. + */ + j$.any = function(clazz) { + return new j$.Any(clazz) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is not `null` and not `undefined`. + * @name jasmine.anything + * @since 2.2.0 + * @function + */ + j$.anything = function() { + return new j$.Anything() + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is `true` or anything truthy. + * @name jasmine.truthy + * @since 3.1.0 + * @function + */ + j$.truthy = function() { + return new j$.Truthy() + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is `null`, `undefined`, `0`, `false` or anything falsey. + * @name jasmine.falsy + * @since 3.1.0 + * @function + */ + j$.falsy = function() { + return new j$.Falsy() + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is empty. + * @name jasmine.empty + * @since 3.1.0 + * @function + */ + j$.empty = function() { + return new j$.Empty() + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} + * that passes if the actual value is the same as the sample as determined + * by the `===` operator. + * @name jasmine.is + * @function + * @param {Object} sample - The value to compare the actual to. + */ + j$.is = function(sample) { + return new j$.Is(sample) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is not empty. + * @name jasmine.notEmpty + * @since 3.1.0 + * @function + */ + j$.notEmpty = function() { + return new j$.NotEmpty() + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared contains at least the keys and values. + * @name jasmine.objectContaining + * @since 1.3.0 + * @function + * @param {Object} sample - The subset of properties that _must_ be in the actual. + */ + j$.objectContaining = function(sample) { + return new j$.ObjectContaining(sample) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is a `String` that matches the `RegExp` or `String`. + * @name jasmine.stringMatching + * @since 2.2.0 + * @function + * @param {RegExp|String} expected + */ + j$.stringMatching = function(expected) { + return new j$.StringMatching(expected) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is a `String` that contains the specified `String`. + * @name jasmine.stringContaining + * @since 3.10.0 + * @function + * @param {String} expected + */ + j$.stringContaining = function(expected) { + return new j$.StringContaining(expected) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is an `Array` that contains at least the elements in the sample. + * @name jasmine.arrayContaining + * @since 2.2.0 + * @function + * @param {Array} sample + */ + j$.arrayContaining = function(sample) { + return new j$.ArrayContaining(sample) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is an `Array` that contains all of the elements in the sample in any order. + * @name jasmine.arrayWithExactContents + * @since 2.8.0 + * @function + * @param {Array} sample + */ + j$.arrayWithExactContents = function(sample) { + return new j$.ArrayWithExactContents(sample) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if every key/value pair in the sample passes the deep equality comparison + * with at least one key/value pair in the actual value being compared + * @name jasmine.mapContaining + * @since 3.5.0 + * @function + * @param {Map} sample - The subset of items that _must_ be in the actual. + */ + j$.mapContaining = function(sample) { + return new j$.MapContaining(sample) + } + + /** + * Get an {@link AsymmetricEqualityTester}, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if every item in the sample passes the deep equality comparison + * with at least one item in the actual value being compared + * @name jasmine.setContaining + * @since 3.5.0 + * @function + * @param {Set} sample - The subset of items that _must_ be in the actual. + */ + j$.setContaining = function(sample) { + return new j$.SetContaining(sample) + } + + /** + * Determines whether the provided function is a Jasmine spy. + * @name jasmine.isSpy + * @since 2.0.0 + * @function + * @param {Function} putativeSpy - The function to check. + * @return {Boolean} + */ + j$.isSpy = function(putativeSpy) { + if (!putativeSpy) { + return false + } + return putativeSpy.and instanceof j$.SpyStrategy && putativeSpy.calls instanceof j$.CallTracker + } + + /** + * Logs a message for use in debugging. If the spec fails, trace messages + * will be included in the {@link SpecResult|result} passed to the + * reporter's specDone method. + * + * This method should be called only when a spec (including any associated + * beforeEach or afterEach functions) is running. + * @function + * @name jasmine.debugLog + * @since 4.0.0 + * @param {String} msg - The message to log + */ + j$.debugLog = function(msg) { + j$.getEnv().debugLog(msg) + } + + /** + * Replaces Jasmine's global error handling with a spy. This prevents Jasmine + * from treating uncaught exceptions and unhandled promise rejections + * as spec failures and allows them to be inspected using the spy's + * {@link Spy#calls|calls property} and related matchers such as + * {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}. + * + * After installing the spy, spyOnGlobalErrorsAsync immediately calls its + * argument, which must be an async or promise-returning function. The spy + * will be passed as the first argument to that callback. Normal error + * handling will be restored when the promise returned from the callback is + * settled. + * + * Note: The JavaScript runtime may deliver uncaught error events and unhandled + * rejection events asynchronously, especially in browsers. If the event + * occurs after the promise returned from the callback is settled, it won't + * be routed to the spy even if the underlying error occurred previously. + * It's up to you to ensure that the returned promise isn't resolved until + * all of the error/rejection events that you want to handle have occurred. + * + * You must await the return value of spyOnGlobalErrorsAsync. + * @name jasmine.spyOnGlobalErrorsAsync + * @function + * @async + * @param {AsyncFunction} fn - A function to run, during which the global error spy will be effective + * @example + * it('demonstrates global error spies', async function() { + * await jasmine.spyOnGlobalErrorsAsync(async function(globalErrorSpy) { + * setTimeout(function() { + * throw new Error('the expected error'); + * }); + * await new Promise(function(resolve) { + * setTimeout(resolve); + * }); + * const expected = new Error('the expected error'); + * expect(globalErrorSpy).toHaveBeenCalledWith(expected); + * }); + * }); + */ + j$.spyOnGlobalErrorsAsync = async function(fn) { + await jasmine.getEnv().spyOnGlobalErrorsAsync(fn) + } +} getJasmineRequireObj().util = function(j$) { - const util = {}; + const util = {} - util.isUndefined = function(obj) { - return obj === void 0; - }; - - util.clone = function(obj) { - if (Object.prototype.toString.apply(obj) === '[object Array]') { - return obj.slice(); + util.isUndefined = function(obj) { + return obj === void 0 } - const cloned = {}; - for (const prop in obj) { - if (obj.hasOwnProperty(prop)) { - cloned[prop] = obj[prop]; - } + util.clone = function(obj) { + if (Object.prototype.toString.apply(obj) === "[object Array]") { + return obj.slice() + } + + const cloned = {} + for (const prop in obj) { + if (obj.hasOwnProperty(prop)) { + cloned[prop] = obj[prop] + } + } + + return cloned } - return cloned; - }; + util.cloneArgs = function(args) { + return Array.from(args).map(function(arg) { + const str = Object.prototype.toString.apply(arg), + primitives = /^\[object (Boolean|String|RegExp|Number)/ - util.cloneArgs = function(args) { - return Array.from(args).map(function(arg) { - const str = Object.prototype.toString.apply(arg), - primitives = /^\[object (Boolean|String|RegExp|Number)/; - - // All falsey values are either primitives, `null`, or `undefined. - if (!arg || str.match(primitives)) { - return arg; - } else if (str === '[object Date]') { - return new Date(arg.valueOf()); - } else { - return j$.util.clone(arg); - } - }); - }; - - util.getPropertyDescriptor = function(obj, methodName) { - let descriptor, - proto = obj; - - do { - descriptor = Object.getOwnPropertyDescriptor(proto, methodName); - proto = Object.getPrototypeOf(proto); - } while (!descriptor && proto); - - return descriptor; - }; - - util.has = function(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); - }; - - util.errorWithStack = function errorWithStack() { - // Don't throw and catch. That makes it harder for users to debug their - // code with exception breakpoints, and it's unnecessary since all - // supported environments populate new Error().stack - return new Error(); - }; - - function callerFile() { - const trace = new j$.StackTrace(util.errorWithStack()); - return trace.frames[2].file; - } - - util.jasmineFile = (function() { - let result; - - return function() { - if (!result) { - result = callerFile(); - } - - return result; - }; - })(); - - util.validateTimeout = function(timeout, msgPrefix) { - // Timeouts are implemented with setTimeout, which only supports a limited - // range of values. The limit is unspecified, as is the behavior when it's - // exceeded. But on all currently supported JS runtimes, setTimeout calls - // the callback immediately when the timeout is greater than 2147483647 - // (the maximum value of a signed 32 bit integer). - const max = 2147483647; - - if (timeout > max) { - throw new Error( - (msgPrefix || 'Timeout value') + ' cannot be greater than ' + max - ); + // All falsey values are either primitives, `null`, or `undefined. + if (!arg || str.match(primitives)) { + return arg + } else if (str === "[object Date]") { + return new Date(arg.valueOf()) + } else { + return j$.util.clone(arg) + } + }) } - }; - return util; -}; + util.getPropertyDescriptor = function(obj, methodName) { + let descriptor, + proto = obj + + do { + descriptor = Object.getOwnPropertyDescriptor(proto, methodName) + proto = Object.getPrototypeOf(proto) + } while (!descriptor && proto) + + return descriptor + } + + util.has = function(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key) + } + + util.errorWithStack = function errorWithStack() { + // Don't throw and catch. That makes it harder for users to debug their + // code with exception breakpoints, and it's unnecessary since all + // supported environments populate new Error().stack + return new Error() + } + + function callerFile() { + const trace = new j$.StackTrace(util.errorWithStack()) + return trace.frames[2].file + } + + util.jasmineFile = (function() { + let result + + return function() { + if (!result) { + result = callerFile() + } + + return result + } + })() + + util.validateTimeout = function(timeout, msgPrefix) { + // Timeouts are implemented with setTimeout, which only supports a limited + // range of values. The limit is unspecified, as is the behavior when it's + // exceeded. But on all currently supported JS runtimes, setTimeout calls + // the callback immediately when the timeout is greater than 2147483647 + // (the maximum value of a signed 32 bit integer). + const max = 2147483647 + + if (timeout > max) { + throw new Error((msgPrefix || "Timeout value") + " cannot be greater than " + max) + } + } + + return util +} getJasmineRequireObj().Spec = function(j$) { - function Spec(attrs) { - this.expectationFactory = attrs.expectationFactory; - this.asyncExpectationFactory = attrs.asyncExpectationFactory; - this.resultCallback = attrs.resultCallback || function() {}; - this.id = attrs.id; - this.description = attrs.description || ''; - this.queueableFn = attrs.queueableFn; - this.beforeAndAfterFns = - attrs.beforeAndAfterFns || - function() { - return { befores: [], afters: [] }; - }; - this.userContext = - attrs.userContext || - function() { - return {}; - }; - this.onStart = attrs.onStart || function() {}; - this.autoCleanClosures = - attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures; - this.getSpecName = - attrs.getSpecName || - function() { - return ''; - }; - this.onLateError = attrs.onLateError || function() {}; - this.catchingExceptions = - attrs.catchingExceptions || - function() { - return true; - }; - this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; - this.timer = attrs.timer || new j$.Timer(); + function Spec(attrs) { + this.expectationFactory = attrs.expectationFactory + this.asyncExpectationFactory = attrs.asyncExpectationFactory + this.resultCallback = attrs.resultCallback || function() {} + this.id = attrs.id + this.description = attrs.description || "" + this.queueableFn = attrs.queueableFn + this.beforeAndAfterFns = + attrs.beforeAndAfterFns || + function() { + return { befores: [], afters: [] } + } + this.userContext = + attrs.userContext || + function() { + return {} + } + this.onStart = attrs.onStart || function() {} + this.autoCleanClosures = attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures + this.getSpecName = + attrs.getSpecName || + function() { + return "" + } + this.onLateError = attrs.onLateError || function() {} + this.catchingExceptions = + attrs.catchingExceptions || + function() { + return true + } + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure + this.timer = attrs.timer || new j$.Timer() - if (!this.queueableFn.fn) { - this.exclude(); + if (!this.queueableFn.fn) { + this.exclude() + } + + /** + * @typedef SpecResult + * @property {String} id - The unique id of this spec. + * @property {String} description - The description passed to the {@link it} that created this spec. + * @property {String} fullName - The full description including all ancestors of this spec. + * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. + * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. + * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. + * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. + * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. + * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. + * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} + * @property {DebugLogEntry[]|null} debugLogs - Messages, if any, that were logged using {@link jasmine.debugLog} during a failing spec. + * @since 2.0.0 + */ + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [], + deprecationWarnings: [], + pendingReason: "", + duration: null, + properties: null, + debugLogs: null, + } + + this.reportedDone = false + } + + Spec.prototype.addExpectationResult = function(passed, data, isError) { + const expectationResult = j$.buildExpectationResult(data) + + if (passed) { + this.result.passedExpectations.push(expectationResult) + } else { + if (this.reportedDone) { + this.onLateError(expectationResult) + } else { + this.result.failedExpectations.push(expectationResult) + + // TODO: refactor so that we don't need to override cached status + if (this.result.status) { + this.result.status = "failed" + } + } + + if (this.throwOnExpectationFailure && !isError) { + throw new j$.errors.ExpectationFailed() + } + } + } + + Spec.prototype.setSpecProperty = function(key, value) { + this.result.properties = this.result.properties || {} + this.result.properties[key] = value + } + + Spec.prototype.expect = function(actual) { + return this.expectationFactory(actual, this) + } + + Spec.prototype.expectAsync = function(actual) { + return this.asyncExpectationFactory(actual, this) + } + + Spec.prototype.execute = function(queueRunnerFactory, onComplete, excluded, failSpecWithNoExp) { + const onStart = { + fn: (done) => { + this.timer.start() + this.onStart(this, done) + }, + } + + const complete = { + fn: (done) => { + if (this.autoCleanClosures) { + this.queueableFn.fn = null + } + this.result.status = this.status(excluded, failSpecWithNoExp) + this.result.duration = this.timer.elapsed() + + if (this.result.status !== "failed") { + this.result.debugLogs = null + } + + this.resultCallback(this.result, done) + }, + type: "specCleanup", + } + + const fns = this.beforeAndAfterFns() + + const runnerConfig = { + isLeaf: true, + queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], + onException: (e) => this.handleException(e), + onMultipleDone: () => { + // Issue a deprecation. Include the context ourselves and pass + // ignoreRunnable: true, since getting here always means that we've already + // moved on and the current runnable isn't the one that caused the problem. + this.onLateError( + new Error( + "An asynchronous spec, beforeEach, or afterEach function called its " + + "'done' callback more than once.\n(in spec: " + + this.getFullName() + + ")" + ) + ) + }, + onComplete: () => { + if (this.result.status === "failed") { + onComplete(new j$.StopExecutionError("spec failed")) + } else { + onComplete() + } + }, + userContext: this.userContext(), + runnableName: this.getFullName.bind(this), + } + + if (this.markedPending || excluded === true) { + runnerConfig.queueableFns = [] + } + + runnerConfig.queueableFns.unshift(onStart) + runnerConfig.queueableFns.push(complete) + + queueRunnerFactory(runnerConfig) + } + + Spec.prototype.reset = function() { + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [], + deprecationWarnings: [], + pendingReason: this.excludeMessage, + duration: null, + properties: null, + debugLogs: null, + } + this.markedPending = this.markedExcluding + this.reportedDone = false + } + + Spec.prototype.handleException = function handleException(e) { + if (Spec.isPendingSpecException(e)) { + this.pend(extractCustomPendingMessage(e)) + return + } + + if (e instanceof j$.errors.ExpectationFailed) { + return + } + + this.addExpectationResult( + false, + { + matcherName: "", + passed: false, + expected: "", + actual: "", + error: e, + }, + true + ) + } + + /* + * Marks state as pending + * @param {string} [message] An optional reason message + */ + Spec.prototype.pend = function(message) { + this.markedPending = true + if (message) { + this.result.pendingReason = message + } + } + + /* + * Like {@link Spec#pend}, but pending state will survive {@link Spec#reset} + * Useful for fit, xit, where pending state remains. + * @param {string} [message] An optional reason message + */ + Spec.prototype.exclude = function(message) { + this.markedExcluding = true + if (this.message) { + this.excludeMessage = message + } + this.pend(message) + } + + Spec.prototype.getResult = function() { + this.result.status = this.status() + return this.result + } + + Spec.prototype.status = function(excluded, failSpecWithNoExpectations) { + if (excluded === true) { + return "excluded" + } + + if (this.markedPending) { + return "pending" + } + + if ( + this.result.failedExpectations.length > 0 || + (failSpecWithNoExpectations && + this.result.failedExpectations.length + this.result.passedExpectations.length === 0) + ) { + return "failed" + } + + return "passed" + } + + Spec.prototype.getFullName = function() { + return this.getSpecName(this) + } + + Spec.prototype.addDeprecationWarning = function(deprecation) { + if (typeof deprecation === "string") { + deprecation = { message: deprecation } + } + this.result.deprecationWarnings.push(j$.buildExpectationResult(deprecation)) + } + + Spec.prototype.debugLog = function(msg) { + if (!this.result.debugLogs) { + this.result.debugLogs = [] + } + + /** + * @typedef DebugLogEntry + * @property {String} message - The message that was passed to {@link jasmine.debugLog}. + * @property {number} timestamp - The time when the entry was added, in + * milliseconds from the spec's start time + */ + this.result.debugLogs.push({ + message: msg, + timestamp: this.timer.elapsed(), + }) + } + + const extractCustomPendingMessage = function(e) { + const fullMessage = e.toString(), + boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), + boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length + + return fullMessage.slice(boilerplateEnd) + } + + Spec.pendingSpecExceptionMessage = "=> marked Pending" + + Spec.isPendingSpecException = function(e) { + return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1) } /** - * @typedef SpecResult - * @property {String} id - The unique id of this spec. - * @property {String} description - The description passed to the {@link it} that created this spec. - * @property {String} fullName - The full description including all ancestors of this spec. - * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. - * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. - * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. - * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. - * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. - * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. - * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} - * @property {DebugLogEntry[]|null} debugLogs - Messages, if any, that were logged using {@link jasmine.debugLog} during a failing spec. + * @interface Spec + * @see Configuration#specFilter * @since 2.0.0 */ - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [], - passedExpectations: [], - deprecationWarnings: [], - pendingReason: '', - duration: null, - properties: null, - debugLogs: null - }; + Object.defineProperty(Spec.prototype, "metadata", { + get: function() { + if (!this.metadata_) { + this.metadata_ = { + /** + * The unique ID of this spec. + * @name Spec#id + * @readonly + * @type {string} + * @since 2.0.0 + */ + id: this.id, - this.reportedDone = false; - } + /** + * The description passed to the {@link it} that created this spec. + * @name Spec#description + * @readonly + * @type {string} + * @since 2.0.0 + */ + description: this.description, - Spec.prototype.addExpectationResult = function(passed, data, isError) { - const expectationResult = j$.buildExpectationResult(data); + /** + * The full description including all ancestors of this spec. + * @name Spec#getFullName + * @function + * @returns {string} + * @since 2.0.0 + */ + getFullName: this.getFullName.bind(this), + } + } - if (passed) { - this.result.passedExpectations.push(expectationResult); - } else { - if (this.reportedDone) { - this.onLateError(expectationResult); - } else { - this.result.failedExpectations.push(expectationResult); + return this.metadata_ + }, + }) - // TODO: refactor so that we don't need to override cached status - if (this.result.status) { - this.result.status = 'failed'; - } - } - - if (this.throwOnExpectationFailure && !isError) { - throw new j$.errors.ExpectationFailed(); - } - } - }; - - Spec.prototype.setSpecProperty = function(key, value) { - this.result.properties = this.result.properties || {}; - this.result.properties[key] = value; - }; - - Spec.prototype.expect = function(actual) { - return this.expectationFactory(actual, this); - }; - - Spec.prototype.expectAsync = function(actual) { - return this.asyncExpectationFactory(actual, this); - }; - - Spec.prototype.execute = function( - queueRunnerFactory, - onComplete, - excluded, - failSpecWithNoExp - ) { - const onStart = { - fn: done => { - this.timer.start(); - this.onStart(this, done); - } - }; - - const complete = { - fn: done => { - if (this.autoCleanClosures) { - this.queueableFn.fn = null; - } - this.result.status = this.status(excluded, failSpecWithNoExp); - this.result.duration = this.timer.elapsed(); - - if (this.result.status !== 'failed') { - this.result.debugLogs = null; - } - - this.resultCallback(this.result, done); - }, - type: 'specCleanup' - }; - - const fns = this.beforeAndAfterFns(); - - const runnerConfig = { - isLeaf: true, - queueableFns: [...fns.befores, this.queueableFn, ...fns.afters], - onException: e => this.handleException(e), - onMultipleDone: () => { - // Issue a deprecation. Include the context ourselves and pass - // ignoreRunnable: true, since getting here always means that we've already - // moved on and the current runnable isn't the one that caused the problem. - this.onLateError( - new Error( - 'An asynchronous spec, beforeEach, or afterEach function called its ' + - "'done' callback more than once.\n(in spec: " + - this.getFullName() + - ')' - ) - ); - }, - onComplete: () => { - if (this.result.status === 'failed') { - onComplete(new j$.StopExecutionError('spec failed')); - } else { - onComplete(); - } - }, - userContext: this.userContext(), - runnableName: this.getFullName.bind(this) - }; - - if (this.markedPending || excluded === true) { - runnerConfig.queueableFns = []; - } - - runnerConfig.queueableFns.unshift(onStart); - runnerConfig.queueableFns.push(complete); - - queueRunnerFactory(runnerConfig); - }; - - Spec.prototype.reset = function() { - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [], - passedExpectations: [], - deprecationWarnings: [], - pendingReason: this.excludeMessage, - duration: null, - properties: null, - debugLogs: null - }; - this.markedPending = this.markedExcluding; - this.reportedDone = false; - }; - - Spec.prototype.handleException = function handleException(e) { - if (Spec.isPendingSpecException(e)) { - this.pend(extractCustomPendingMessage(e)); - return; - } - - if (e instanceof j$.errors.ExpectationFailed) { - return; - } - - this.addExpectationResult( - false, - { - matcherName: '', - passed: false, - expected: '', - actual: '', - error: e - }, - true - ); - }; - - /* - * Marks state as pending - * @param {string} [message] An optional reason message - */ - Spec.prototype.pend = function(message) { - this.markedPending = true; - if (message) { - this.result.pendingReason = message; - } - }; - - /* - * Like {@link Spec#pend}, but pending state will survive {@link Spec#reset} - * Useful for fit, xit, where pending state remains. - * @param {string} [message] An optional reason message - */ - Spec.prototype.exclude = function(message) { - this.markedExcluding = true; - if (this.message) { - this.excludeMessage = message; - } - this.pend(message); - }; - - Spec.prototype.getResult = function() { - this.result.status = this.status(); - return this.result; - }; - - Spec.prototype.status = function(excluded, failSpecWithNoExpectations) { - if (excluded === true) { - return 'excluded'; - } - - if (this.markedPending) { - return 'pending'; - } - - if ( - this.result.failedExpectations.length > 0 || - (failSpecWithNoExpectations && - this.result.failedExpectations.length + - this.result.passedExpectations.length === - 0) - ) { - return 'failed'; - } - - return 'passed'; - }; - - Spec.prototype.getFullName = function() { - return this.getSpecName(this); - }; - - Spec.prototype.addDeprecationWarning = function(deprecation) { - if (typeof deprecation === 'string') { - deprecation = { message: deprecation }; - } - this.result.deprecationWarnings.push( - j$.buildExpectationResult(deprecation) - ); - }; - - Spec.prototype.debugLog = function(msg) { - if (!this.result.debugLogs) { - this.result.debugLogs = []; - } - - /** - * @typedef DebugLogEntry - * @property {String} message - The message that was passed to {@link jasmine.debugLog}. - * @property {number} timestamp - The time when the entry was added, in - * milliseconds from the spec's start time - */ - this.result.debugLogs.push({ - message: msg, - timestamp: this.timer.elapsed() - }); - }; - - const extractCustomPendingMessage = function(e) { - const fullMessage = e.toString(), - boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), - boilerplateEnd = - boilerplateStart + Spec.pendingSpecExceptionMessage.length; - - return fullMessage.slice(boilerplateEnd); - }; - - Spec.pendingSpecExceptionMessage = '=> marked Pending'; - - Spec.isPendingSpecException = function(e) { - return !!( - e && - e.toString && - e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 - ); - }; - - /** - * @interface Spec - * @see Configuration#specFilter - * @since 2.0.0 - */ - Object.defineProperty(Spec.prototype, 'metadata', { - get: function() { - if (!this.metadata_) { - this.metadata_ = { - /** - * The unique ID of this spec. - * @name Spec#id - * @readonly - * @type {string} - * @since 2.0.0 - */ - id: this.id, - - /** - * The description passed to the {@link it} that created this spec. - * @name Spec#description - * @readonly - * @type {string} - * @since 2.0.0 - */ - description: this.description, - - /** - * The full description including all ancestors of this spec. - * @name Spec#getFullName - * @function - * @returns {string} - * @since 2.0.0 - */ - getFullName: this.getFullName.bind(this) - }; - } - - return this.metadata_; - } - }); - - return Spec; -}; + return Spec +} getJasmineRequireObj().Order = function() { - function Order(options) { - this.random = 'random' in options ? options.random : true; - const seed = (this.seed = options.seed || generateSeed()); - this.sort = this.random ? randomOrder : naturalOrder; + function Order(options) { + this.random = "random" in options ? options.random : true + const seed = (this.seed = options.seed || generateSeed()) + this.sort = this.random ? randomOrder : naturalOrder - function naturalOrder(items) { - return items; + function naturalOrder(items) { + return items + } + + function randomOrder(items) { + const copy = items.slice() + copy.sort(function(a, b) { + return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id) + }) + return copy + } + + function generateSeed() { + return String(Math.random()).slice(-5) + } + + // Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function + // used to get a different output when the key changes slightly. + // We use your return to sort the children randomly in a consistent way when + // used in conjunction with a seed + + function jenkinsHash(key) { + let hash, i + for (hash = i = 0; i < key.length; ++i) { + hash += key.charCodeAt(i) + hash += hash << 10 + hash ^= hash >> 6 + } + hash += hash << 3 + hash ^= hash >> 11 + hash += hash << 15 + return hash + } } - function randomOrder(items) { - const copy = items.slice(); - copy.sort(function(a, b) { - return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); - }); - return copy; - } - - function generateSeed() { - return String(Math.random()).slice(-5); - } - - // Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function - // used to get a different output when the key changes slightly. - // We use your return to sort the children randomly in a consistent way when - // used in conjunction with a seed - - function jenkinsHash(key) { - let hash, i; - for (hash = i = 0; i < key.length; ++i) { - hash += key.charCodeAt(i); - hash += hash << 10; - hash ^= hash >> 6; - } - hash += hash << 3; - hash ^= hash >> 11; - hash += hash << 15; - return hash; - } - } - - return Order; -}; + return Order +} getJasmineRequireObj().Env = function(j$) { - /** - * @class Env - * @since 2.0.0 - * @classdesc The Jasmine environment.
    - * _Note:_ Do not construct this directly. You can obtain the Env instance by - * calling {@link jasmine.getEnv}. - * @hideconstructor - */ - function Env(options) { - options = options || {}; - - const self = this; - const global = options.global || j$.getGlobal(); - - const realSetTimeout = global.setTimeout; - const realClearTimeout = global.clearTimeout; - const clearStack = j$.getClearStack(global); - this.clock = new j$.Clock( - global, - function() { - return new j$.DelayedFunctionScheduler(); - }, - new j$.MockDate(global) - ); - - const globalErrors = new j$.GlobalErrors(); - const installGlobalErrors = (function() { - let installed = false; - return function() { - if (!installed) { - globalErrors.install(); - installed = true; - } - }; - })(); - - const runableResources = new j$.RunableResources({ - getCurrentRunableId: function() { - const r = runner.currentRunable(); - return r ? r.id : null; - }, - globalErrors - }); - - let reporter; - let topSuite; - let runner; - /** - * This represents the available options to configure Jasmine. - * Options that are not provided will use their default values. - * @see Env#configure - * @interface Configuration - * @since 3.3.0 - */ - const config = { - /** - * Whether to randomize spec execution order - * @name Configuration#random - * @since 3.3.0 - * @type Boolean - * @default true - */ - random: true, - /** - * Seed to use as the basis of randomization. - * Null causes the seed to be determined randomly at the start of execution. - * @name Configuration#seed - * @since 3.3.0 - * @type (number|string) - * @default null - */ - seed: null, - /** - * Whether to stop execution of the suite after the first spec failure - * @name Configuration#stopOnSpecFailure - * @since 3.9.0 - * @type Boolean - * @default false - */ - stopOnSpecFailure: false, - /** - * Whether to fail the spec if it ran no expectations. By default - * a spec that ran no expectations is reported as passed. Setting this - * to true will report such spec as a failure. - * @name Configuration#failSpecWithNoExpectations - * @since 3.5.0 - * @type Boolean - * @default false - */ - failSpecWithNoExpectations: false, - /** - * Whether to cause specs to only have one expectation failure. - * @name Configuration#stopSpecOnExpectationFailure - * @since 3.3.0 - * @type Boolean - * @default false - */ - stopSpecOnExpectationFailure: false, - /** - * A function that takes a spec and returns true if it should be executed - * or false if it should be skipped. - * @callback SpecFilter - * @param {Spec} spec - The spec that the filter is being applied to. - * @return boolean - */ - /** - * Function to use to filter specs - * @name Configuration#specFilter - * @since 3.3.0 - * @type SpecFilter - * @default A function that always returns true. - */ - specFilter: function() { - return true; - }, - /** - * Whether or not reporters should hide disabled specs from their output. - * Currently only supported by Jasmine's HTMLReporter - * @name Configuration#hideDisabled - * @since 3.3.0 - * @type Boolean - * @default false - */ - hideDisabled: false, - /** - * Clean closures when a suite is done running (done by clearing the stored function reference). - * This prevents memory leaks, but you won't be able to run jasmine multiple times. - * @name Configuration#autoCleanClosures - * @since 3.10.0 - * @type boolean - * @default true - */ - autoCleanClosures: true, - /** - * Whether or not to issue warnings for certain deprecated functionality - * every time it's used. If not set or set to false, deprecation warnings - * for methods that tend to be called frequently will be issued only once - * or otherwise throttled to to prevent the suite output from being flooded - * with warnings. - * @name Configuration#verboseDeprecations - * @since 3.6.0 - * @type Boolean - * @default false - */ - verboseDeprecations: false - }; - - if (!options.suppressLoadErrors) { - installGlobalErrors(); - globalErrors.pushListener(function loadtimeErrorHandler( - message, - filename, - lineno, - colNo, - err - ) { - topSuite.result.failedExpectations.push({ - passed: false, - globalErrorType: 'load', - message: message, - stack: err && err.stack, - filename: filename, - lineno: lineno - }); - }); - } - - /** - * Configure your jasmine environment - * @name Env#configure - * @since 3.3.0 - * @argument {Configuration} configuration - * @function - */ - this.configure = function(configuration) { - const booleanProps = [ - 'random', - 'failSpecWithNoExpectations', - 'hideDisabled', - 'stopOnSpecFailure', - 'stopSpecOnExpectationFailure', - 'autoCleanClosures' - ]; - - booleanProps.forEach(function(prop) { - if (typeof configuration[prop] !== 'undefined') { - config[prop] = !!configuration[prop]; - } - }); - - if (configuration.specFilter) { - config.specFilter = configuration.specFilter; - } - - if (typeof configuration.seed !== 'undefined') { - config.seed = configuration.seed; - } - - if (configuration.hasOwnProperty('verboseDeprecations')) { - config.verboseDeprecations = configuration.verboseDeprecations; - deprecator.verboseDeprecations(config.verboseDeprecations); - } - }; - - /** - * Get the current configuration for your jasmine environment - * @name Env#configuration - * @since 3.3.0 - * @function - * @returns {Configuration} - */ - this.configuration = function() { - const result = {}; - for (const property in config) { - result[property] = config[property]; - } - return result; - }; - - this.setDefaultSpyStrategy = function(defaultStrategyFn) { - runableResources.setDefaultSpyStrategy(defaultStrategyFn); - }; - - this.addSpyStrategy = function(name, fn) { - runableResources.customSpyStrategies()[name] = fn; - }; - - this.addCustomEqualityTester = function(tester) { - runableResources.customEqualityTesters().push(tester); - }; - - this.addMatchers = function(matchersToAdd) { - runableResources.addCustomMatchers(matchersToAdd); - }; - - this.addAsyncMatchers = function(matchersToAdd) { - runableResources.addCustomAsyncMatchers(matchersToAdd); - }; - - this.addCustomObjectFormatter = function(formatter) { - runableResources.customObjectFormatters().push(formatter); - }; - - j$.Expectation.addCoreMatchers(j$.matchers); - j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); - - const expectationFactory = function(actual, spec) { - return j$.Expectation.factory({ - matchersUtil: runableResources.makeMatchersUtil(), - customMatchers: runableResources.customMatchers(), - actual: actual, - addExpectationResult: addExpectationResult - }); - - function addExpectationResult(passed, result) { - return spec.addExpectationResult(passed, result); - } - }; - - // TODO: Unify recordLateError with recordLateExpectation? The extra - // diagnostic info added by the latter is probably useful in most cases. - function recordLateError(error) { - const isExpectationResult = - error.matcherName !== undefined && error.passed !== undefined; - const result = isExpectationResult - ? error - : j$.buildExpectationResult({ - error, - passed: false, - matcherName: '', - expected: '', - actual: '' - }); - routeLateFailure(result); - } - - function recordLateExpectation(runable, runableType, result) { - const delayedExpectationResult = {}; - Object.keys(result).forEach(function(k) { - delayedExpectationResult[k] = result[k]; - }); - delayedExpectationResult.passed = false; - delayedExpectationResult.globalErrorType = 'lateExpectation'; - delayedExpectationResult.message = - runableType + - ' "' + - runable.getFullName() + - '" ran a "' + - result.matcherName + - '" expectation after it finished.\n'; - - if (result.message) { - delayedExpectationResult.message += - 'Message: "' + result.message + '"\n'; - } - - delayedExpectationResult.message += - '1. Did you forget to return or await the result of expectAsync?\n' + - '2. Was done() invoked before an async operation completed?\n' + - '3. Did an expectation follow a call to done()?'; - - topSuite.result.failedExpectations.push(delayedExpectationResult); - } - - function routeLateFailure(expectationResult) { - // Report the result on the nearest ancestor suite that hasn't already - // been reported done. - for (let r = runner.currentRunable(); r; r = r.parentSuite) { - if (!r.reportedDone) { - if (r === topSuite) { - expectationResult.globalErrorType = 'lateError'; - } - - r.result.failedExpectations.push(expectationResult); - return; - } - } - - // If we get here, all results have been reported and there's nothing we - // can do except log the result and hope the user sees it. - console.error('Jasmine received a result after the suite finished:'); - console.error(expectationResult); - } - - const asyncExpectationFactory = function(actual, spec, runableType) { - return j$.Expectation.asyncFactory({ - matchersUtil: runableResources.makeMatchersUtil(), - customAsyncMatchers: runableResources.customAsyncMatchers(), - actual: actual, - addExpectationResult: addExpectationResult - }); - - function addExpectationResult(passed, result) { - if (runner.currentRunable() !== spec) { - recordLateExpectation(spec, runableType, result); - } - return spec.addExpectationResult(passed, result); - } - }; - - /** - * Causes a deprecation warning to be logged to the console and reported to - * reporters. - * - * The optional second parameter is an object that can have either of the - * following properties: - * - * omitStackTrace: Whether to omit the stack trace. Optional. Defaults to - * false. This option is ignored if the deprecation is an Error. Set this - * when the stack trace will not contain anything that helps the user find - * the source of the deprecation. - * - * ignoreRunnable: Whether to log the deprecation on the root suite, ignoring - * the spec or suite that's running when it happens. Optional. Defaults to - * false. - * - * @name Env#deprecated - * @since 2.99 - * @function - * @param {String|Error} deprecation The deprecation message - * @param {Object} [options] Optional extra options, as described above - */ - this.deprecated = function(deprecation, options) { - const runable = runner.currentRunable() || topSuite; - deprecator.addDeprecationWarning(runable, deprecation, options); - }; - - function queueRunnerFactory(options) { - options.clearStack = options.clearStack || clearStack; - options.timeout = { - setTimeout: realSetTimeout, - clearTimeout: realClearTimeout - }; - options.fail = self.fail; - options.globalErrors = globalErrors; - options.onException = - options.onException || - function(e) { - (runner.currentRunable() || topSuite).handleException(e); - }; - options.deprecated = self.deprecated; - - new j$.QueueRunner(options).execute(); - } - - const suiteBuilder = new j$.SuiteBuilder({ - env: this, - expectationFactory, - asyncExpectationFactory, - onLateError: recordLateError, - specResultCallback, - specStarted, - queueRunnerFactory - }); - topSuite = suiteBuilder.topSuite; - const deprecator = new j$.Deprecator(topSuite); - - /** - * Provides the root suite, through which all suites and specs can be - * accessed. - * @function - * @name Env#topSuite - * @return {Suite} the root suite + * @class Env * @since 2.0.0 + * @classdesc The Jasmine environment.
    + * _Note:_ Do not construct this directly. You can obtain the Env instance by + * calling {@link jasmine.getEnv}. + * @hideconstructor */ - this.topSuite = function() { - return topSuite.metadata; - }; + function Env(options) { + options = options || {} + + const self = this + const global = options.global || j$.getGlobal() + + const realSetTimeout = global.setTimeout + const realClearTimeout = global.clearTimeout + const clearStack = j$.getClearStack(global) + this.clock = new j$.Clock( + global, + function() { + return new j$.DelayedFunctionScheduler() + }, + new j$.MockDate(global) + ) + + const globalErrors = new j$.GlobalErrors() + const installGlobalErrors = (function() { + let installed = false + return function() { + if (!installed) { + globalErrors.install() + installed = true + } + } + })() + + const runableResources = new j$.RunableResources({ + getCurrentRunableId: function() { + const r = runner.currentRunable() + return r ? r.id : null + }, + globalErrors, + }) + + let reporter + let topSuite + let runner - /** - * This represents the available reporter callback for an object passed to {@link Env#addReporter}. - * @interface Reporter - * @see custom_reporter - */ - reporter = new j$.ReportDispatcher( - [ /** - * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. - * @function - * @name Reporter#jasmineStarted - * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async + * This represents the available options to configure Jasmine. + * Options that are not provided will use their default values. + * @see Env#configure + * @interface Configuration + * @since 3.3.0 */ - 'jasmineStarted', + const config = { + /** + * Whether to randomize spec execution order + * @name Configuration#random + * @since 3.3.0 + * @type Boolean + * @default true + */ + random: true, + /** + * Seed to use as the basis of randomization. + * Null causes the seed to be determined randomly at the start of execution. + * @name Configuration#seed + * @since 3.3.0 + * @type (number|string) + * @default null + */ + seed: null, + /** + * Whether to stop execution of the suite after the first spec failure + * @name Configuration#stopOnSpecFailure + * @since 3.9.0 + * @type Boolean + * @default false + */ + stopOnSpecFailure: false, + /** + * Whether to fail the spec if it ran no expectations. By default + * a spec that ran no expectations is reported as passed. Setting this + * to true will report such spec as a failure. + * @name Configuration#failSpecWithNoExpectations + * @since 3.5.0 + * @type Boolean + * @default false + */ + failSpecWithNoExpectations: false, + /** + * Whether to cause specs to only have one expectation failure. + * @name Configuration#stopSpecOnExpectationFailure + * @since 3.3.0 + * @type Boolean + * @default false + */ + stopSpecOnExpectationFailure: false, + /** + * A function that takes a spec and returns true if it should be executed + * or false if it should be skipped. + * @callback SpecFilter + * @param {Spec} spec - The spec that the filter is being applied to. + * @return boolean + */ + /** + * Function to use to filter specs + * @name Configuration#specFilter + * @since 3.3.0 + * @type SpecFilter + * @default A function that always returns true. + */ + specFilter: function() { + return true + }, + /** + * Whether or not reporters should hide disabled specs from their output. + * Currently only supported by Jasmine's HTMLReporter + * @name Configuration#hideDisabled + * @since 3.3.0 + * @type Boolean + * @default false + */ + hideDisabled: false, + /** + * Clean closures when a suite is done running (done by clearing the stored function reference). + * This prevents memory leaks, but you won't be able to run jasmine multiple times. + * @name Configuration#autoCleanClosures + * @since 3.10.0 + * @type boolean + * @default true + */ + autoCleanClosures: true, + /** + * Whether or not to issue warnings for certain deprecated functionality + * every time it's used. If not set or set to false, deprecation warnings + * for methods that tend to be called frequently will be issued only once + * or otherwise throttled to to prevent the suite output from being flooded + * with warnings. + * @name Configuration#verboseDeprecations + * @since 3.6.0 + * @type Boolean + * @default false + */ + verboseDeprecations: false, + } + + if (!options.suppressLoadErrors) { + installGlobalErrors() + globalErrors.pushListener(function loadtimeErrorHandler(message, filename, lineno, colNo, err) { + topSuite.result.failedExpectations.push({ + passed: false, + globalErrorType: "load", + message: message, + stack: err && err.stack, + filename: filename, + lineno: lineno, + }) + }) + } + /** - * When the entire suite has finished execution `jasmineDone` is called + * Configure your jasmine environment + * @name Env#configure + * @since 3.3.0 + * @argument {Configuration} configuration * @function - * @name Reporter#jasmineDone - * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async */ - 'jasmineDone', + this.configure = function(configuration) { + const booleanProps = [ + "random", + "failSpecWithNoExpectations", + "hideDisabled", + "stopOnSpecFailure", + "stopSpecOnExpectationFailure", + "autoCleanClosures", + ] + + booleanProps.forEach(function(prop) { + if (typeof configuration[prop] !== "undefined") { + config[prop] = !!configuration[prop] + } + }) + + if (configuration.specFilter) { + config.specFilter = configuration.specFilter + } + + if (typeof configuration.seed !== "undefined") { + config.seed = configuration.seed + } + + if (configuration.hasOwnProperty("verboseDeprecations")) { + config.verboseDeprecations = configuration.verboseDeprecations + deprecator.verboseDeprecations(config.verboseDeprecations) + } + } + /** - * `suiteStarted` is invoked when a `describe` starts to run + * Get the current configuration for your jasmine environment + * @name Env#configuration + * @since 3.3.0 * @function - * @name Reporter#suiteStarted - * @param {SuiteResult} result Information about the individual {@link describe} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async + * @returns {Configuration} */ - 'suiteStarted', + this.configuration = function() { + const result = {} + for (const property in config) { + result[property] = config[property] + } + return result + } + + this.setDefaultSpyStrategy = function(defaultStrategyFn) { + runableResources.setDefaultSpyStrategy(defaultStrategyFn) + } + + this.addSpyStrategy = function(name, fn) { + runableResources.customSpyStrategies()[name] = fn + } + + this.addCustomEqualityTester = function(tester) { + runableResources.customEqualityTesters().push(tester) + } + + this.addMatchers = function(matchersToAdd) { + runableResources.addCustomMatchers(matchersToAdd) + } + + this.addAsyncMatchers = function(matchersToAdd) { + runableResources.addCustomAsyncMatchers(matchersToAdd) + } + + this.addCustomObjectFormatter = function(formatter) { + runableResources.customObjectFormatters().push(formatter) + } + + j$.Expectation.addCoreMatchers(j$.matchers) + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers) + + const expectationFactory = function(actual, spec) { + return j$.Expectation.factory({ + matchersUtil: runableResources.makeMatchersUtil(), + customMatchers: runableResources.customMatchers(), + actual: actual, + addExpectationResult: addExpectationResult, + }) + + function addExpectationResult(passed, result) { + return spec.addExpectationResult(passed, result) + } + } + + // TODO: Unify recordLateError with recordLateExpectation? The extra + // diagnostic info added by the latter is probably useful in most cases. + function recordLateError(error) { + const isExpectationResult = error.matcherName !== undefined && error.passed !== undefined + const result = isExpectationResult + ? error + : j$.buildExpectationResult({ + error, + passed: false, + matcherName: "", + expected: "", + actual: "", + }) + routeLateFailure(result) + } + + function recordLateExpectation(runable, runableType, result) { + const delayedExpectationResult = {} + Object.keys(result).forEach(function(k) { + delayedExpectationResult[k] = result[k] + }) + delayedExpectationResult.passed = false + delayedExpectationResult.globalErrorType = "lateExpectation" + delayedExpectationResult.message = + runableType + + ' "' + + runable.getFullName() + + '" ran a "' + + result.matcherName + + '" expectation after it finished.\n' + + if (result.message) { + delayedExpectationResult.message += 'Message: "' + result.message + '"\n' + } + + delayedExpectationResult.message += + "1. Did you forget to return or await the result of expectAsync?\n" + + "2. Was done() invoked before an async operation completed?\n" + + "3. Did an expectation follow a call to done()?" + + topSuite.result.failedExpectations.push(delayedExpectationResult) + } + + function routeLateFailure(expectationResult) { + // Report the result on the nearest ancestor suite that hasn't already + // been reported done. + for (let r = runner.currentRunable(); r; r = r.parentSuite) { + if (!r.reportedDone) { + if (r === topSuite) { + expectationResult.globalErrorType = "lateError" + } + + r.result.failedExpectations.push(expectationResult) + return + } + } + + // If we get here, all results have been reported and there's nothing we + // can do except log the result and hope the user sees it. + console.error("Jasmine received a result after the suite finished:") + console.error(expectationResult) + } + + const asyncExpectationFactory = function(actual, spec, runableType) { + return j$.Expectation.asyncFactory({ + matchersUtil: runableResources.makeMatchersUtil(), + customAsyncMatchers: runableResources.customAsyncMatchers(), + actual: actual, + addExpectationResult: addExpectationResult, + }) + + function addExpectationResult(passed, result) { + if (runner.currentRunable() !== spec) { + recordLateExpectation(spec, runableType, result) + } + return spec.addExpectationResult(passed, result) + } + } + /** - * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run + * Causes a deprecation warning to be logged to the console and reported to + * reporters. * - * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. - * @function - * @name Reporter#suiteDone - * @param {SuiteResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'suiteDone', - /** - * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) - * @function - * @name Reporter#specStarted - * @param {SpecResult} result Information about the individual {@link it} being run - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async - */ - 'specStarted', - /** - * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. + * The optional second parameter is an object that can have either of the + * following properties: * - * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. + * omitStackTrace: Whether to omit the stack trace. Optional. Defaults to + * false. This option is ignored if the deprecation is an Error. Set this + * when the stack trace will not contain anything that helps the user find + * the source of the deprecation. + * + * ignoreRunnable: Whether to log the deprecation on the root suite, ignoring + * the spec or suite that's running when it happens. Optional. Defaults to + * false. + * + * @name Env#deprecated + * @since 2.99 * @function - * @name Reporter#specDone - * @param {SpecResult} result - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - * @see async + * @param {String|Error} deprecation The deprecation message + * @param {Object} [options] Optional extra options, as described above */ - 'specDone' - ], - function(options) { - options.SkipPolicy = j$.NeverSkipPolicy; - return queueRunnerFactory(options); - }, - recordLateError - ); - - runner = new j$.Runner({ - topSuite, - totalSpecsDefined: () => suiteBuilder.totalSpecsDefined, - focusedRunables: () => suiteBuilder.focusedRunables, - runableResources, - reporter, - queueRunnerFactory, - getConfig: () => config, - reportSpecDone - }); - - /** - * Executes the specs. - * - * If called with no parameters or with a falsy value as the first parameter, - * all specs will be executed except those that are excluded by a - * [spec filter]{@link Configuration#specFilter} or other mechanism. If the - * first parameter is a list of spec/suite IDs, only those specs/suites will - * be run. - * - * Both parameters are optional, but a completion callback is only valid as - * the second parameter. To specify a completion callback but not a list of - * specs/suites to run, pass null or undefined as the first parameter. The - * completion callback is supported for backward compatibility. In most - * cases it will be more convenient to use the returned promise instead. - * - * execute should not be called more than once unless the env has been - * configured with `{autoCleanClosures: false}`. - * - * execute returns a promise. The promise will be resolved to the same - * {@link JasmineDoneInfo|overall result} that's passed to a reporter's - * `jasmineDone` method, even if the suite did not pass. To determine - * whether the suite passed, check the value that the promise resolves to - * or use a {@link Reporter}. - * - * @name Env#execute - * @since 2.0.0 - * @function - * @param {(string[])=} runablesToRun IDs of suites and/or specs to run - * @param {Function=} onComplete Function that will be called after all specs have run - * @return {Promise} - */ - this.execute = function(runablesToRun, onComplete) { - installGlobalErrors(); - - return runner.execute(runablesToRun).then(function(jasmineDoneInfo) { - if (onComplete) { - onComplete(); + this.deprecated = function(deprecation, options) { + const runable = runner.currentRunable() || topSuite + deprecator.addDeprecationWarning(runable, deprecation, options) } - return jasmineDoneInfo; - }); - }; + function queueRunnerFactory(options) { + options.clearStack = options.clearStack || clearStack + options.timeout = { + setTimeout: realSetTimeout, + clearTimeout: realClearTimeout, + } + options.fail = self.fail + options.globalErrors = globalErrors + options.onException = + options.onException || + function(e) { + ;(runner.currentRunable() || topSuite).handleException(e) + } + options.deprecated = self.deprecated - /** - * Add a custom reporter to the Jasmine environment. - * @name Env#addReporter - * @since 2.0.0 - * @function - * @param {Reporter} reporterToAdd The reporter to be added. - * @see custom_reporter - */ - this.addReporter = function(reporterToAdd) { - reporter.addReporter(reporterToAdd); - }; - - /** - * Provide a fallback reporter if no other reporters have been specified. - * @name Env#provideFallbackReporter - * @since 2.5.0 - * @function - * @param {Reporter} reporterToAdd The reporter - * @see custom_reporter - */ - this.provideFallbackReporter = function(reporterToAdd) { - reporter.provideFallbackReporter(reporterToAdd); - }; - - /** - * Clear all registered reporters - * @name Env#clearReporters - * @since 2.5.2 - * @function - */ - this.clearReporters = function() { - reporter.clearReporters(); - }; - - /** - * Configures whether Jasmine should allow the same function to be spied on - * more than once during the execution of a spec. By default, spying on - * a function that is already a spy will cause an error. - * @name Env#allowRespy - * @function - * @since 2.5.0 - * @param {boolean} allow Whether to allow respying - */ - this.allowRespy = function(allow) { - runableResources.spyRegistry.allowRespy(allow); - }; - - this.spyOn = function() { - return runableResources.spyRegistry.spyOn.apply( - runableResources.spyRegistry, - arguments - ); - }; - - this.spyOnProperty = function() { - return runableResources.spyRegistry.spyOnProperty.apply( - runableResources.spyRegistry, - arguments - ); - }; - - this.spyOnAllFunctions = function() { - return runableResources.spyRegistry.spyOnAllFunctions.apply( - runableResources.spyRegistry, - arguments - ); - }; - - this.createSpy = function(name, originalFn) { - return runableResources.spyFactory.createSpy(name, originalFn); - }; - - this.createSpyObj = function(baseName, methodNames, propertyNames) { - return runableResources.spyFactory.createSpyObj( - baseName, - methodNames, - propertyNames - ); - }; - - this.spyOnGlobalErrorsAsync = async function(fn) { - const spy = this.createSpy('global error handler'); - const associatedRunable = runner.currentRunable(); - let cleanedUp = false; - - globalErrors.setOverrideListener(spy, () => { - if (!cleanedUp) { - const message = - 'Global error spy was not uninstalled. (Did you ' + - 'forget to await the return value of spyOnGlobalErrorsAsync?)'; - associatedRunable.addExpectationResult(false, { - matcherName: '', - passed: false, - expected: '', - actual: '', - message, - error: null - }); + new j$.QueueRunner(options).execute() } - cleanedUp = true; - }); + const suiteBuilder = new j$.SuiteBuilder({ + env: this, + expectationFactory, + asyncExpectationFactory, + onLateError: recordLateError, + specResultCallback, + specStarted, + queueRunnerFactory, + }) + topSuite = suiteBuilder.topSuite + const deprecator = new j$.Deprecator(topSuite) - try { - const maybePromise = fn(spy); - - if (!j$.isPromiseLike(maybePromise)) { - throw new Error( - 'The callback to spyOnGlobalErrorsAsync must be an async or promise-returning function' - ); + /** + * Provides the root suite, through which all suites and specs can be + * accessed. + * @function + * @name Env#topSuite + * @return {Suite} the root suite + * @since 2.0.0 + */ + this.topSuite = function() { + return topSuite.metadata } - await maybePromise; - } finally { - if (!cleanedUp) { - cleanedUp = true; - globalErrors.removeOverrideListener(); - } - } - }; + /** + * This represents the available reporter callback for an object passed to {@link Env#addReporter}. + * @interface Reporter + * @see custom_reporter + */ + reporter = new j$.ReportDispatcher( + [ + /** + * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. + * @function + * @name Reporter#jasmineStarted + * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "jasmineStarted", + /** + * When the entire suite has finished execution `jasmineDone` is called + * @function + * @name Reporter#jasmineDone + * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "jasmineDone", + /** + * `suiteStarted` is invoked when a `describe` starts to run + * @function + * @name Reporter#suiteStarted + * @param {SuiteResult} result Information about the individual {@link describe} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "suiteStarted", + /** + * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run + * + * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. + * @function + * @name Reporter#suiteDone + * @param {SuiteResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "suiteDone", + /** + * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) + * @function + * @name Reporter#specStarted + * @param {SpecResult} result Information about the individual {@link it} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "specStarted", + /** + * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. + * + * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. + * @function + * @name Reporter#specDone + * @param {SpecResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + "specDone", + ], + function(options) { + options.SkipPolicy = j$.NeverSkipPolicy + return queueRunnerFactory(options) + }, + recordLateError + ) - function ensureIsNotNested(method) { - const runable = runner.currentRunable(); - if (runable !== null && runable !== undefined) { - throw new Error( - "'" + method + "' should only be used in 'describe' function" - ); - } + runner = new j$.Runner({ + topSuite, + totalSpecsDefined: () => suiteBuilder.totalSpecsDefined, + focusedRunables: () => suiteBuilder.focusedRunables, + runableResources, + reporter, + queueRunnerFactory, + getConfig: () => config, + reportSpecDone, + }) + + /** + * Executes the specs. + * + * If called with no parameters or with a falsy value as the first parameter, + * all specs will be executed except those that are excluded by a + * [spec filter]{@link Configuration#specFilter} or other mechanism. If the + * first parameter is a list of spec/suite IDs, only those specs/suites will + * be run. + * + * Both parameters are optional, but a completion callback is only valid as + * the second parameter. To specify a completion callback but not a list of + * specs/suites to run, pass null or undefined as the first parameter. The + * completion callback is supported for backward compatibility. In most + * cases it will be more convenient to use the returned promise instead. + * + * execute should not be called more than once unless the env has been + * configured with `{autoCleanClosures: false}`. + * + * execute returns a promise. The promise will be resolved to the same + * {@link JasmineDoneInfo|overall result} that's passed to a reporter's + * `jasmineDone` method, even if the suite did not pass. To determine + * whether the suite passed, check the value that the promise resolves to + * or use a {@link Reporter}. + * + * @name Env#execute + * @since 2.0.0 + * @function + * @param {(string[])=} runablesToRun IDs of suites and/or specs to run + * @param {Function=} onComplete Function that will be called after all specs have run + * @return {Promise} + */ + this.execute = function(runablesToRun, onComplete) { + installGlobalErrors() + + return runner.execute(runablesToRun).then(function(jasmineDoneInfo) { + if (onComplete) { + onComplete() + } + + return jasmineDoneInfo + }) + } + + /** + * Add a custom reporter to the Jasmine environment. + * @name Env#addReporter + * @since 2.0.0 + * @function + * @param {Reporter} reporterToAdd The reporter to be added. + * @see custom_reporter + */ + this.addReporter = function(reporterToAdd) { + reporter.addReporter(reporterToAdd) + } + + /** + * Provide a fallback reporter if no other reporters have been specified. + * @name Env#provideFallbackReporter + * @since 2.5.0 + * @function + * @param {Reporter} reporterToAdd The reporter + * @see custom_reporter + */ + this.provideFallbackReporter = function(reporterToAdd) { + reporter.provideFallbackReporter(reporterToAdd) + } + + /** + * Clear all registered reporters + * @name Env#clearReporters + * @since 2.5.2 + * @function + */ + this.clearReporters = function() { + reporter.clearReporters() + } + + /** + * Configures whether Jasmine should allow the same function to be spied on + * more than once during the execution of a spec. By default, spying on + * a function that is already a spy will cause an error. + * @name Env#allowRespy + * @function + * @since 2.5.0 + * @param {boolean} allow Whether to allow respying + */ + this.allowRespy = function(allow) { + runableResources.spyRegistry.allowRespy(allow) + } + + this.spyOn = function() { + return runableResources.spyRegistry.spyOn.apply(runableResources.spyRegistry, arguments) + } + + this.spyOnProperty = function() { + return runableResources.spyRegistry.spyOnProperty.apply(runableResources.spyRegistry, arguments) + } + + this.spyOnAllFunctions = function() { + return runableResources.spyRegistry.spyOnAllFunctions.apply(runableResources.spyRegistry, arguments) + } + + this.createSpy = function(name, originalFn) { + return runableResources.spyFactory.createSpy(name, originalFn) + } + + this.createSpyObj = function(baseName, methodNames, propertyNames) { + return runableResources.spyFactory.createSpyObj(baseName, methodNames, propertyNames) + } + + this.spyOnGlobalErrorsAsync = async function(fn) { + const spy = this.createSpy("global error handler") + const associatedRunable = runner.currentRunable() + let cleanedUp = false + + globalErrors.setOverrideListener(spy, () => { + if (!cleanedUp) { + const message = + "Global error spy was not uninstalled. (Did you " + + "forget to await the return value of spyOnGlobalErrorsAsync?)" + associatedRunable.addExpectationResult(false, { + matcherName: "", + passed: false, + expected: "", + actual: "", + message, + error: null, + }) + } + + cleanedUp = true + }) + + try { + const maybePromise = fn(spy) + + if (!j$.isPromiseLike(maybePromise)) { + throw new Error( + "The callback to spyOnGlobalErrorsAsync must be an async or promise-returning function" + ) + } + + await maybePromise + } finally { + if (!cleanedUp) { + cleanedUp = true + globalErrors.removeOverrideListener() + } + } + } + + function ensureIsNotNested(method) { + const runable = runner.currentRunable() + if (runable !== null && runable !== undefined) { + throw new Error("'" + method + "' should only be used in 'describe' function") + } + } + + this.describe = function(description, definitionFn) { + ensureIsNotNested("describe") + return suiteBuilder.describe(description, definitionFn).metadata + } + + this.xdescribe = function(description, definitionFn) { + ensureIsNotNested("xdescribe") + return suiteBuilder.xdescribe(description, definitionFn).metadata + } + + this.fdescribe = function(description, definitionFn) { + ensureIsNotNested("fdescribe") + return suiteBuilder.fdescribe(description, definitionFn).metadata + } + + function specResultCallback(spec, result, next) { + runableResources.clearForRunable(spec.id) + runner.currentSpec = null + + if (result.status === "failed") { + runner.hasFailures = true + } + + reportSpecDone(spec, result, next) + } + + function specStarted(spec, suite, next) { + runner.currentSpec = spec + runableResources.initForRunable(spec.id, suite.id) + reporter.specStarted(spec.result).then(next) + } + + function reportSpecDone(spec, result, next) { + spec.reportedDone = true + reporter.specDone(result).then(next) + } + + this.it = function(description, fn, timeout) { + ensureIsNotNested("it") + return suiteBuilder.it(description, fn, timeout).metadata + } + + this.xit = function(description, fn, timeout) { + ensureIsNotNested("xit") + return suiteBuilder.xit(description, fn, timeout).metadata + } + + this.fit = function(description, fn, timeout) { + ensureIsNotNested("fit") + return suiteBuilder.fit(description, fn, timeout).metadata + } + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} + * @name Env#setSpecProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + this.setSpecProperty = function(key, value) { + if (!runner.currentRunable() || runner.currentRunable() == runner.currentSuite()) { + throw new Error("'setSpecProperty' was used when there was no current spec") + } + runner.currentRunable().setSpecProperty(key, value) + } + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} + * @name Env#setSuiteProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + this.setSuiteProperty = function(key, value) { + if (!runner.currentSuite()) { + throw new Error("'setSuiteProperty' was used when there was no current suite") + } + runner.currentSuite().setSuiteProperty(key, value) + } + + this.debugLog = function(msg) { + const maybeSpec = runner.currentRunable() + + if (!maybeSpec || !maybeSpec.debugLog) { + throw new Error("'debugLog' was called when there was no current spec") + } + + maybeSpec.debugLog(msg) + } + + this.expect = function(actual) { + if (!runner.currentRunable()) { + throw new Error( + "'expect' was used when there was no current spec, this could be because an asynchronous test timed out" + ) + } + + return runner.currentRunable().expect(actual) + } + + this.expectAsync = function(actual) { + if (!runner.currentRunable()) { + throw new Error( + "'expectAsync' was used when there was no current spec, this could be because an asynchronous test timed out" + ) + } + + return runner.currentRunable().expectAsync(actual) + } + + this.beforeEach = function(beforeEachFunction, timeout) { + ensureIsNotNested("beforeEach") + suiteBuilder.beforeEach(beforeEachFunction, timeout) + } + + this.beforeAll = function(beforeAllFunction, timeout) { + ensureIsNotNested("beforeAll") + suiteBuilder.beforeAll(beforeAllFunction, timeout) + } + + this.afterEach = function(afterEachFunction, timeout) { + ensureIsNotNested("afterEach") + suiteBuilder.afterEach(afterEachFunction, timeout) + } + + this.afterAll = function(afterAllFunction, timeout) { + ensureIsNotNested("afterAll") + suiteBuilder.afterAll(afterAllFunction, timeout) + } + + this.pending = function(message) { + let fullMessage = j$.Spec.pendingSpecExceptionMessage + if (message) { + fullMessage += message + } + throw fullMessage + } + + this.fail = function(error) { + if (!runner.currentRunable()) { + throw new Error( + "'fail' was used when there was no current spec, this could be because an asynchronous test timed out" + ) + } + + let message = "Failed" + if (error) { + message += ": " + if (error.message) { + message += error.message + } else if (j$.isString_(error)) { + message += error + } else { + // pretty print all kind of objects. This includes arrays. + const pp = runableResources.makePrettyPrinter() + message += pp(error) + } + } + + runner.currentRunable().addExpectationResult(false, { + matcherName: "", + passed: false, + expected: "", + actual: "", + message: message, + error: error && error.message ? error : null, + }) + + if (config.stopSpecOnExpectationFailure) { + throw new Error(message) + } + } + + this.cleanup_ = function() { + if (globalErrors) { + globalErrors.uninstall() + } + } } - this.describe = function(description, definitionFn) { - ensureIsNotNested('describe'); - return suiteBuilder.describe(description, definitionFn).metadata; - }; - - this.xdescribe = function(description, definitionFn) { - ensureIsNotNested('xdescribe'); - return suiteBuilder.xdescribe(description, definitionFn).metadata; - }; - - this.fdescribe = function(description, definitionFn) { - ensureIsNotNested('fdescribe'); - return suiteBuilder.fdescribe(description, definitionFn).metadata; - }; - - function specResultCallback(spec, result, next) { - runableResources.clearForRunable(spec.id); - runner.currentSpec = null; - - if (result.status === 'failed') { - runner.hasFailures = true; - } - - reportSpecDone(spec, result, next); - } - - function specStarted(spec, suite, next) { - runner.currentSpec = spec; - runableResources.initForRunable(spec.id, suite.id); - reporter.specStarted(spec.result).then(next); - } - - function reportSpecDone(spec, result, next) { - spec.reportedDone = true; - reporter.specDone(result).then(next); - } - - this.it = function(description, fn, timeout) { - ensureIsNotNested('it'); - return suiteBuilder.it(description, fn, timeout).metadata; - }; - - this.xit = function(description, fn, timeout) { - ensureIsNotNested('xit'); - return suiteBuilder.xit(description, fn, timeout).metadata; - }; - - this.fit = function(description, fn, timeout) { - ensureIsNotNested('fit'); - return suiteBuilder.fit(description, fn, timeout).metadata; - }; - - /** - * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} - * @name Env#setSpecProperty - * @since 3.6.0 - * @function - * @param {String} key The name of the property - * @param {*} value The value of the property - */ - this.setSpecProperty = function(key, value) { - if ( - !runner.currentRunable() || - runner.currentRunable() == runner.currentSuite() - ) { - throw new Error( - "'setSpecProperty' was used when there was no current spec" - ); - } - runner.currentRunable().setSpecProperty(key, value); - }; - - /** - * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} - * @name Env#setSuiteProperty - * @since 3.6.0 - * @function - * @param {String} key The name of the property - * @param {*} value The value of the property - */ - this.setSuiteProperty = function(key, value) { - if (!runner.currentSuite()) { - throw new Error( - "'setSuiteProperty' was used when there was no current suite" - ); - } - runner.currentSuite().setSuiteProperty(key, value); - }; - - this.debugLog = function(msg) { - const maybeSpec = runner.currentRunable(); - - if (!maybeSpec || !maybeSpec.debugLog) { - throw new Error("'debugLog' was called when there was no current spec"); - } - - maybeSpec.debugLog(msg); - }; - - this.expect = function(actual) { - if (!runner.currentRunable()) { - throw new Error( - "'expect' was used when there was no current spec, this could be because an asynchronous test timed out" - ); - } - - return runner.currentRunable().expect(actual); - }; - - this.expectAsync = function(actual) { - if (!runner.currentRunable()) { - throw new Error( - "'expectAsync' was used when there was no current spec, this could be because an asynchronous test timed out" - ); - } - - return runner.currentRunable().expectAsync(actual); - }; - - this.beforeEach = function(beforeEachFunction, timeout) { - ensureIsNotNested('beforeEach'); - suiteBuilder.beforeEach(beforeEachFunction, timeout); - }; - - this.beforeAll = function(beforeAllFunction, timeout) { - ensureIsNotNested('beforeAll'); - suiteBuilder.beforeAll(beforeAllFunction, timeout); - }; - - this.afterEach = function(afterEachFunction, timeout) { - ensureIsNotNested('afterEach'); - suiteBuilder.afterEach(afterEachFunction, timeout); - }; - - this.afterAll = function(afterAllFunction, timeout) { - ensureIsNotNested('afterAll'); - suiteBuilder.afterAll(afterAllFunction, timeout); - }; - - this.pending = function(message) { - let fullMessage = j$.Spec.pendingSpecExceptionMessage; - if (message) { - fullMessage += message; - } - throw fullMessage; - }; - - this.fail = function(error) { - if (!runner.currentRunable()) { - throw new Error( - "'fail' was used when there was no current spec, this could be because an asynchronous test timed out" - ); - } - - let message = 'Failed'; - if (error) { - message += ': '; - if (error.message) { - message += error.message; - } else if (j$.isString_(error)) { - message += error; - } else { - // pretty print all kind of objects. This includes arrays. - const pp = runableResources.makePrettyPrinter(); - message += pp(error); - } - } - - runner.currentRunable().addExpectationResult(false, { - matcherName: '', - passed: false, - expected: '', - actual: '', - message: message, - error: error && error.message ? error : null - }); - - if (config.stopSpecOnExpectationFailure) { - throw new Error(message); - } - }; - - this.cleanup_ = function() { - if (globalErrors) { - globalErrors.uninstall(); - } - }; - } - - return Env; -}; + return Env +} getJasmineRequireObj().JsApiReporter = function(j$) { - /** - * @name jsApiReporter - * @classdesc {@link Reporter} added by default in `boot.js` to record results for retrieval in javascript code. An instance is made available as `jsApiReporter` on the global object. - * @class - * @hideconstructor - */ - function JsApiReporter(options) { - const timer = options.timer || new j$.Timer(); - let status = 'loaded'; - - this.started = false; - this.finished = false; - this.runDetails = {}; - - this.jasmineStarted = function() { - this.started = true; - status = 'started'; - timer.start(); - }; - - let executionTime; - - this.jasmineDone = function(runDetails) { - this.finished = true; - this.runDetails = runDetails; - executionTime = timer.elapsed(); - status = 'done'; - }; - /** - * Get the current status for the Jasmine environment. - * @name jsApiReporter#status - * @since 2.0.0 - * @function - * @return {String} - One of `loaded`, `started`, or `done` + * @name jsApiReporter + * @classdesc {@link Reporter} added by default in `boot.js` to record results for retrieval in javascript code. An instance is made available as `jsApiReporter` on the global object. + * @class + * @hideconstructor */ - this.status = function() { - return status; - }; + function JsApiReporter(options) { + const timer = options.timer || new j$.Timer() + let status = "loaded" - const suites = [], - suites_hash = {}; + this.started = false + this.finished = false + this.runDetails = {} - this.suiteStarted = function(result) { - suites_hash[result.id] = result; - }; + this.jasmineStarted = function() { + this.started = true + status = "started" + timer.start() + } - this.suiteDone = function(result) { - storeSuite(result); - }; + let executionTime - /** - * Get the results for a set of suites. - * - * Retrievable in slices for easier serialization. - * @name jsApiReporter#suiteResults - * @since 2.1.0 - * @function - * @param {Number} index - The position in the suites list to start from. - * @param {Number} length - Maximum number of suite results to return. - * @return {SuiteResult[]} - */ - this.suiteResults = function(index, length) { - return suites.slice(index, index + length); - }; + this.jasmineDone = function(runDetails) { + this.finished = true + this.runDetails = runDetails + executionTime = timer.elapsed() + status = "done" + } - function storeSuite(result) { - suites.push(result); - suites_hash[result.id] = result; + /** + * Get the current status for the Jasmine environment. + * @name jsApiReporter#status + * @since 2.0.0 + * @function + * @return {String} - One of `loaded`, `started`, or `done` + */ + this.status = function() { + return status + } + + const suites = [], + suites_hash = {} + + this.suiteStarted = function(result) { + suites_hash[result.id] = result + } + + this.suiteDone = function(result) { + storeSuite(result) + } + + /** + * Get the results for a set of suites. + * + * Retrievable in slices for easier serialization. + * @name jsApiReporter#suiteResults + * @since 2.1.0 + * @function + * @param {Number} index - The position in the suites list to start from. + * @param {Number} length - Maximum number of suite results to return. + * @return {SuiteResult[]} + */ + this.suiteResults = function(index, length) { + return suites.slice(index, index + length) + } + + function storeSuite(result) { + suites.push(result) + suites_hash[result.id] = result + } + + /** + * Get all of the suites in a single object, with their `id` as the key. + * @name jsApiReporter#suites + * @since 2.0.0 + * @function + * @return {Object} - Map of suite id to {@link SuiteResult} + */ + this.suites = function() { + return suites_hash + } + + const specs = [] + + this.specDone = function(result) { + specs.push(result) + } + + /** + * Get the results for a set of specs. + * + * Retrievable in slices for easier serialization. + * @name jsApiReporter#specResults + * @since 2.0.0 + * @function + * @param {Number} index - The position in the specs list to start from. + * @param {Number} length - Maximum number of specs results to return. + * @return {SpecResult[]} + */ + this.specResults = function(index, length) { + return specs.slice(index, index + length) + } + + /** + * Get all spec results. + * @name jsApiReporter#specs + * @since 2.0.0 + * @function + * @return {SpecResult[]} + */ + this.specs = function() { + return specs + } + + /** + * Get the number of milliseconds it took for the full Jasmine suite to run. + * @name jsApiReporter#executionTime + * @since 2.0.0 + * @function + * @return {Number} + */ + this.executionTime = function() { + return executionTime + } } - /** - * Get all of the suites in a single object, with their `id` as the key. - * @name jsApiReporter#suites - * @since 2.0.0 - * @function - * @return {Object} - Map of suite id to {@link SuiteResult} - */ - this.suites = function() { - return suites_hash; - }; - - const specs = []; - - this.specDone = function(result) { - specs.push(result); - }; - - /** - * Get the results for a set of specs. - * - * Retrievable in slices for easier serialization. - * @name jsApiReporter#specResults - * @since 2.0.0 - * @function - * @param {Number} index - The position in the specs list to start from. - * @param {Number} length - Maximum number of specs results to return. - * @return {SpecResult[]} - */ - this.specResults = function(index, length) { - return specs.slice(index, index + length); - }; - - /** - * Get all spec results. - * @name jsApiReporter#specs - * @since 2.0.0 - * @function - * @return {SpecResult[]} - */ - this.specs = function() { - return specs; - }; - - /** - * Get the number of milliseconds it took for the full Jasmine suite to run. - * @name jsApiReporter#executionTime - * @since 2.0.0 - * @function - * @return {Number} - */ - this.executionTime = function() { - return executionTime; - }; - } - - return JsApiReporter; -}; + return JsApiReporter +} getJasmineRequireObj().Any = function(j$) { - function Any(expectedObject) { - if (typeof expectedObject === 'undefined') { - throw new TypeError( - 'jasmine.any() expects to be passed a constructor function. ' + - 'Please pass one or use jasmine.anything() to match any object.' - ); - } - this.expectedObject = expectedObject; - } - - Any.prototype.asymmetricMatch = function(other) { - if (this.expectedObject == String) { - return typeof other == 'string' || other instanceof String; + function Any(expectedObject) { + if (typeof expectedObject === "undefined") { + throw new TypeError( + "jasmine.any() expects to be passed a constructor function. " + + "Please pass one or use jasmine.anything() to match any object." + ) + } + this.expectedObject = expectedObject } - if (this.expectedObject == Number) { - return typeof other == 'number' || other instanceof Number; + Any.prototype.asymmetricMatch = function(other) { + if (this.expectedObject == String) { + return typeof other == "string" || other instanceof String + } + + if (this.expectedObject == Number) { + return typeof other == "number" || other instanceof Number + } + + if (this.expectedObject == Function) { + return typeof other == "function" || other instanceof Function + } + + if (this.expectedObject == Object) { + return other !== null && typeof other == "object" + } + + if (this.expectedObject == Boolean) { + return typeof other == "boolean" + } + + if (typeof Symbol != "undefined" && this.expectedObject == Symbol) { + return typeof other == "symbol" + } + + return other instanceof this.expectedObject } - if (this.expectedObject == Function) { - return typeof other == 'function' || other instanceof Function; + Any.prototype.jasmineToString = function() { + return "" } - if (this.expectedObject == Object) { - return other !== null && typeof other == 'object'; - } - - if (this.expectedObject == Boolean) { - return typeof other == 'boolean'; - } - - if (typeof Symbol != 'undefined' && this.expectedObject == Symbol) { - return typeof other == 'symbol'; - } - - return other instanceof this.expectedObject; - }; - - Any.prototype.jasmineToString = function() { - return ''; - }; - - return Any; -}; + return Any +} getJasmineRequireObj().Anything = function(j$) { - function Anything() {} + function Anything() {} - Anything.prototype.asymmetricMatch = function(other) { - return !j$.util.isUndefined(other) && other !== null; - }; + Anything.prototype.asymmetricMatch = function(other) { + return !j$.util.isUndefined(other) && other !== null + } - Anything.prototype.jasmineToString = function() { - return ''; - }; + Anything.prototype.jasmineToString = function() { + return "" + } - return Anything; -}; + return Anything +} getJasmineRequireObj().ArrayContaining = function(j$) { - function ArrayContaining(sample) { - this.sample = sample; - } - - ArrayContaining.prototype.asymmetricMatch = function(other, matchersUtil) { - if (!j$.isArray_(this.sample)) { - throw new Error( - 'You must provide an array to arrayContaining, not ' + - j$.basicPrettyPrinter_(this.sample) + - '.' - ); + function ArrayContaining(sample) { + this.sample = sample } - // If the actual parameter is not an array, we can fail immediately, since it couldn't - // possibly be an "array containing" anything. However, we also want an empty sample - // array to match anything, so we need to double-check we aren't in that case - if (!j$.isArray_(other) && this.sample.length > 0) { - return false; + ArrayContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isArray_(this.sample)) { + throw new Error( + "You must provide an array to arrayContaining, not " + j$.basicPrettyPrinter_(this.sample) + "." + ) + } + + // If the actual parameter is not an array, we can fail immediately, since it couldn't + // possibly be an "array containing" anything. However, we also want an empty sample + // array to match anything, so we need to double-check we aren't in that case + if (!j$.isArray_(other) && this.sample.length > 0) { + return false + } + + for (const item of this.sample) { + if (!matchersUtil.contains(other, item)) { + return false + } + } + + return true } - for (const item of this.sample) { - if (!matchersUtil.contains(other, item)) { - return false; - } + ArrayContaining.prototype.jasmineToString = function(pp) { + return "" } - return true; - }; - - ArrayContaining.prototype.jasmineToString = function(pp) { - return ''; - }; - - return ArrayContaining; -}; + return ArrayContaining +} getJasmineRequireObj().ArrayWithExactContents = function(j$) { - function ArrayWithExactContents(sample) { - this.sample = sample; - } - - ArrayWithExactContents.prototype.asymmetricMatch = function( - other, - matchersUtil - ) { - if (!j$.isArray_(this.sample)) { - throw new Error( - 'You must provide an array to arrayWithExactContents, not ' + - j$.basicPrettyPrinter_(this.sample) + - '.' - ); + function ArrayWithExactContents(sample) { + this.sample = sample } - if (this.sample.length !== other.length) { - return false; + ArrayWithExactContents.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isArray_(this.sample)) { + throw new Error( + "You must provide an array to arrayWithExactContents, not " + j$.basicPrettyPrinter_(this.sample) + "." + ) + } + + if (this.sample.length !== other.length) { + return false + } + + for (const item of this.sample) { + if (!matchersUtil.contains(other, item)) { + return false + } + } + + return true } - for (const item of this.sample) { - if (!matchersUtil.contains(other, item)) { - return false; - } + ArrayWithExactContents.prototype.jasmineToString = function(pp) { + return "" } - return true; - }; - - ArrayWithExactContents.prototype.jasmineToString = function(pp) { - return ''; - }; - - return ArrayWithExactContents; -}; + return ArrayWithExactContents +} getJasmineRequireObj().Empty = function(j$) { - function Empty() {} + function Empty() {} - Empty.prototype.asymmetricMatch = function(other) { - if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { - return other.length === 0; + Empty.prototype.asymmetricMatch = function(other) { + if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { + return other.length === 0 + } + + if (j$.isMap(other) || j$.isSet(other)) { + return other.size === 0 + } + + if (j$.isObject_(other)) { + return Object.keys(other).length === 0 + } + return false } - if (j$.isMap(other) || j$.isSet(other)) { - return other.size === 0; + Empty.prototype.jasmineToString = function() { + return "" } - if (j$.isObject_(other)) { - return Object.keys(other).length === 0; - } - return false; - }; - - Empty.prototype.jasmineToString = function() { - return ''; - }; - - return Empty; -}; + return Empty +} getJasmineRequireObj().Falsy = function(j$) { - function Falsy() {} + function Falsy() {} - Falsy.prototype.asymmetricMatch = function(other) { - return !other; - }; + Falsy.prototype.asymmetricMatch = function(other) { + return !other + } - Falsy.prototype.jasmineToString = function() { - return ''; - }; + Falsy.prototype.jasmineToString = function() { + return "" + } - return Falsy; -}; + return Falsy +} getJasmineRequireObj().Is = function(j$) { - class Is { - constructor(expected) { - this.expected_ = expected; + class Is { + constructor(expected) { + this.expected_ = expected + } + + asymmetricMatch(actual) { + return actual === this.expected_ + } + + jasmineToString(pp) { + return `` + } } - asymmetricMatch(actual) { - return actual === this.expected_; - } - - jasmineToString(pp) { - return ``; - } - } - - return Is; -}; + return Is +} getJasmineRequireObj().MapContaining = function(j$) { - function MapContaining(sample) { - if (!j$.isMap(sample)) { - throw new Error( - 'You must provide a map to `mapContaining`, not ' + - j$.basicPrettyPrinter_(sample) - ); - } - - this.sample = sample; - } - - MapContaining.prototype.asymmetricMatch = function(other, matchersUtil) { - if (!j$.isMap(other)) return false; - - for (const [key, value] of this.sample) { - // for each key/value pair in `sample` - // there should be at least one pair in `other` whose key and value both match - let hasMatch = false; - for (const [oKey, oValue] of other) { - if ( - matchersUtil.equals(oKey, key) && - matchersUtil.equals(oValue, value) - ) { - hasMatch = true; - break; + function MapContaining(sample) { + if (!j$.isMap(sample)) { + throw new Error("You must provide a map to `mapContaining`, not " + j$.basicPrettyPrinter_(sample)) } - } - if (!hasMatch) { - return false; - } + this.sample = sample } - return true; - }; + MapContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isMap(other)) return false - MapContaining.prototype.jasmineToString = function(pp) { - return ''; - }; + for (const [key, value] of this.sample) { + // for each key/value pair in `sample` + // there should be at least one pair in `other` whose key and value both match + let hasMatch = false + for (const [oKey, oValue] of other) { + if (matchersUtil.equals(oKey, key) && matchersUtil.equals(oValue, value)) { + hasMatch = true + break + } + } - return MapContaining; -}; + if (!hasMatch) { + return false + } + } + + return true + } + + MapContaining.prototype.jasmineToString = function(pp) { + return "" + } + + return MapContaining +} getJasmineRequireObj().NotEmpty = function(j$) { - function NotEmpty() {} + function NotEmpty() {} - NotEmpty.prototype.asymmetricMatch = function(other) { - if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { - return other.length !== 0; + NotEmpty.prototype.asymmetricMatch = function(other) { + if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { + return other.length !== 0 + } + + if (j$.isMap(other) || j$.isSet(other)) { + return other.size !== 0 + } + + if (j$.isObject_(other)) { + return Object.keys(other).length !== 0 + } + + return false } - if (j$.isMap(other) || j$.isSet(other)) { - return other.size !== 0; + NotEmpty.prototype.jasmineToString = function() { + return "" } - if (j$.isObject_(other)) { - return Object.keys(other).length !== 0; - } - - return false; - }; - - NotEmpty.prototype.jasmineToString = function() { - return ''; - }; - - return NotEmpty; -}; + return NotEmpty +} getJasmineRequireObj().ObjectContaining = function(j$) { - function ObjectContaining(sample) { - this.sample = sample; - } - - function hasProperty(obj, property) { - if (!obj || typeof obj !== 'object') { - return false; + function ObjectContaining(sample) { + this.sample = sample } - if (Object.prototype.hasOwnProperty.call(obj, property)) { - return true; + function hasProperty(obj, property) { + if (!obj || typeof obj !== "object") { + return false + } + + if (Object.prototype.hasOwnProperty.call(obj, property)) { + return true + } + + return hasProperty(Object.getPrototypeOf(obj), property) } - return hasProperty(Object.getPrototypeOf(obj), property); - } + ObjectContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (typeof this.sample !== "object") { + throw new Error("You must provide an object to objectContaining, not '" + this.sample + "'.") + } + if (typeof other !== "object") { + return false + } - ObjectContaining.prototype.asymmetricMatch = function(other, matchersUtil) { - if (typeof this.sample !== 'object') { - throw new Error( - "You must provide an object to objectContaining, not '" + - this.sample + - "'." - ); - } - if (typeof other !== 'object') { - return false; + for (const property in this.sample) { + if (!hasProperty(other, property) || !matchersUtil.equals(this.sample[property], other[property])) { + return false + } + } + + return true } - for (const property in this.sample) { - if ( - !hasProperty(other, property) || - !matchersUtil.equals(this.sample[property], other[property]) - ) { - return false; - } + ObjectContaining.prototype.valuesForDiff_ = function(other, pp) { + if (!j$.isObject_(other)) { + return { + self: this.jasmineToString(pp), + other: other, + } + } + + const filteredOther = {} + Object.keys(this.sample).forEach(function(k) { + // eq short-circuits comparison of objects that have different key sets, + // so include all keys even if undefined. + filteredOther[k] = other[k] + }) + + return { + self: this.sample, + other: filteredOther, + } } - return true; - }; - - ObjectContaining.prototype.valuesForDiff_ = function(other, pp) { - if (!j$.isObject_(other)) { - return { - self: this.jasmineToString(pp), - other: other - }; + ObjectContaining.prototype.jasmineToString = function(pp) { + return "" } - const filteredOther = {}; - Object.keys(this.sample).forEach(function(k) { - // eq short-circuits comparison of objects that have different key sets, - // so include all keys even if undefined. - filteredOther[k] = other[k]; - }); - - return { - self: this.sample, - other: filteredOther - }; - }; - - ObjectContaining.prototype.jasmineToString = function(pp) { - return ''; - }; - - return ObjectContaining; -}; + return ObjectContaining +} getJasmineRequireObj().SetContaining = function(j$) { - function SetContaining(sample) { - if (!j$.isSet(sample)) { - throw new Error( - 'You must provide a set to `setContaining`, not ' + - j$.basicPrettyPrinter_(sample) - ); - } - - this.sample = sample; - } - - SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) { - if (!j$.isSet(other)) return false; - - for (const item of this.sample) { - // for each item in `sample` there should be at least one matching item in `other` - // (not using `matchersUtil.contains` because it compares set members by reference, - // not by deep value equality) - let hasMatch = false; - for (const oItem of other) { - if (matchersUtil.equals(oItem, item)) { - hasMatch = true; - break; + function SetContaining(sample) { + if (!j$.isSet(sample)) { + throw new Error("You must provide a set to `setContaining`, not " + j$.basicPrettyPrinter_(sample)) } - } - if (!hasMatch) { - return false; - } + this.sample = sample } - return true; - }; + SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isSet(other)) return false - SetContaining.prototype.jasmineToString = function(pp) { - return ''; - }; + for (const item of this.sample) { + // for each item in `sample` there should be at least one matching item in `other` + // (not using `matchersUtil.contains` because it compares set members by reference, + // not by deep value equality) + let hasMatch = false + for (const oItem of other) { + if (matchersUtil.equals(oItem, item)) { + hasMatch = true + break + } + } - return SetContaining; -}; + if (!hasMatch) { + return false + } + } + + return true + } + + SetContaining.prototype.jasmineToString = function(pp) { + return "" + } + + return SetContaining +} getJasmineRequireObj().StringContaining = function(j$) { - function StringContaining(expected) { - if (!j$.isString_(expected)) { - throw new Error('Expected is not a String'); + function StringContaining(expected) { + if (!j$.isString_(expected)) { + throw new Error("Expected is not a String") + } + + this.expected = expected } - this.expected = expected; - } + StringContaining.prototype.asymmetricMatch = function(other) { + if (!j$.isString_(other)) { + // Arrays, etc. don't match no matter what their indexOf returns. + return false + } - StringContaining.prototype.asymmetricMatch = function(other) { - if (!j$.isString_(other)) { - // Arrays, etc. don't match no matter what their indexOf returns. - return false; + return other.indexOf(this.expected) !== -1 } - return other.indexOf(this.expected) !== -1; - }; + StringContaining.prototype.jasmineToString = function() { + return '' + } - StringContaining.prototype.jasmineToString = function() { - return ''; - }; - - return StringContaining; -}; + return StringContaining +} getJasmineRequireObj().StringMatching = function(j$) { - function StringMatching(expected) { - if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { - throw new Error('Expected is not a String or a RegExp'); + function StringMatching(expected) { + if (!j$.isString_(expected) && !j$.isA_("RegExp", expected)) { + throw new Error("Expected is not a String or a RegExp") + } + + this.regexp = new RegExp(expected) } - this.regexp = new RegExp(expected); - } + StringMatching.prototype.asymmetricMatch = function(other) { + return this.regexp.test(other) + } - StringMatching.prototype.asymmetricMatch = function(other) { - return this.regexp.test(other); - }; + StringMatching.prototype.jasmineToString = function() { + return "" + } - StringMatching.prototype.jasmineToString = function() { - return ''; - }; - - return StringMatching; -}; + return StringMatching +} getJasmineRequireObj().Truthy = function(j$) { - function Truthy() {} + function Truthy() {} - Truthy.prototype.asymmetricMatch = function(other) { - return !!other; - }; + Truthy.prototype.asymmetricMatch = function(other) { + return !!other + } - Truthy.prototype.jasmineToString = function() { - return ''; - }; + Truthy.prototype.jasmineToString = function() { + return "" + } - return Truthy; -}; + return Truthy +} //TODO: expectation result may make more sense as a presentation of an expectation. getJasmineRequireObj().buildExpectationResult = function(j$) { - function buildExpectationResult(options) { - const exceptionFormatter = new j$.ExceptionFormatter(); + function buildExpectationResult(options) { + const exceptionFormatter = new j$.ExceptionFormatter() - /** - * @typedef Expectation - * @property {String} matcherName - The name of the matcher that was executed for this expectation. - * @property {String} message - The failure message for the expectation. - * @property {String} stack - The stack trace for the failure if available. - * @property {Boolean} passed - Whether the expectation passed or failed. - * @property {Object} expected - If the expectation failed, what was the expected value. - * @property {Object} actual - If the expectation failed, what actual value was produced. - * @property {String|undefined} globalErrorType - The type of an error that - * is reported on the top suite. Valid values are undefined, "afterAll", - * "load", "lateExpectation", and "lateError". - */ - const result = { - matcherName: options.matcherName, - message: message(), - stack: options.omitStackTrace ? '' : stack(), - passed: options.passed - }; - - if (!result.passed) { - result.expected = options.expected; - result.actual = options.actual; - - if (options.error && !j$.isString_(options.error)) { - if ('code' in options.error) { - result.code = options.error.code; + /** + * @typedef Expectation + * @property {String} matcherName - The name of the matcher that was executed for this expectation. + * @property {String} message - The failure message for the expectation. + * @property {String} stack - The stack trace for the failure if available. + * @property {Boolean} passed - Whether the expectation passed or failed. + * @property {Object} expected - If the expectation failed, what was the expected value. + * @property {Object} actual - If the expectation failed, what actual value was produced. + * @property {String|undefined} globalErrorType - The type of an error that + * is reported on the top suite. Valid values are undefined, "afterAll", + * "load", "lateExpectation", and "lateError". + */ + const result = { + matcherName: options.matcherName, + message: message(), + stack: options.omitStackTrace ? "" : stack(), + passed: options.passed, } - if ( - options.error.code === 'ERR_ASSERTION' && - options.expected === '' && - options.actual === '' - ) { - result.expected = options.error.expected; - result.actual = options.error.actual; - result.matcherName = 'assert ' + options.error.operator; + if (!result.passed) { + result.expected = options.expected + result.actual = options.actual + + if (options.error && !j$.isString_(options.error)) { + if ("code" in options.error) { + result.code = options.error.code + } + + if (options.error.code === "ERR_ASSERTION" && options.expected === "" && options.actual === "") { + result.expected = options.error.expected + result.actual = options.error.actual + result.matcherName = "assert " + options.error.operator + } + } } - } - } - return result; + return result - function message() { - if (options.passed) { - return 'Passed.'; - } else if (options.message) { - return options.message; - } else if (options.error) { - return exceptionFormatter.message(options.error); - } - return ''; - } - - function stack() { - if (options.passed) { - return ''; - } - - let error = options.error; - - if (!error) { - if (options.errorForStack) { - error = options.errorForStack; - } else if (options.stack) { - error = options; - } else { - try { - throw new Error(message()); - } catch (e) { - error = e; - } + function message() { + if (options.passed) { + return "Passed." + } else if (options.message) { + return options.message + } else if (options.error) { + return exceptionFormatter.message(options.error) + } + return "" } - } - // Omit the message from the stack trace because it will be - // included elsewhere. - return exceptionFormatter.stack(error, { omitMessage: true }); - } - } - return buildExpectationResult; -}; + function stack() { + if (options.passed) { + return "" + } + + let error = options.error + + if (!error) { + if (options.errorForStack) { + error = options.errorForStack + } else if (options.stack) { + error = options + } else { + try { + throw new Error(message()) + } catch (e) { + error = e + } + } + } + // Omit the message from the stack trace because it will be + // included elsewhere. + return exceptionFormatter.stack(error, { omitMessage: true }) + } + } + + return buildExpectationResult +} getJasmineRequireObj().CallTracker = function(j$) { - /** - * @namespace Spy#calls - * @since 2.0.0 - */ - function CallTracker() { - let calls = []; - const opts = {}; - - this.track = function(context) { - if (opts.cloneArgs) { - context.args = j$.util.cloneArgs(context.args); - } - calls.push(context); - }; - /** - * Check whether this spy has been invoked. - * @name Spy#calls#any + * @namespace Spy#calls * @since 2.0.0 - * @function - * @return {Boolean} */ - this.any = function() { - return !!calls.length; - }; + function CallTracker() { + let calls = [] + const opts = {} - /** - * Get the number of invocations of this spy. - * @name Spy#calls#count - * @since 2.0.0 - * @function - * @return {Integer} - */ - this.count = function() { - return calls.length; - }; + this.track = function(context) { + if (opts.cloneArgs) { + context.args = j$.util.cloneArgs(context.args) + } + calls.push(context) + } - /** - * Get the arguments that were passed to a specific invocation of this spy. - * @name Spy#calls#argsFor - * @since 2.0.0 - * @function - * @param {Integer} index The 0-based invocation index. - * @return {Array} - */ - this.argsFor = function(index) { - const call = calls[index]; - return call ? call.args : []; - }; + /** + * Check whether this spy has been invoked. + * @name Spy#calls#any + * @since 2.0.0 + * @function + * @return {Boolean} + */ + this.any = function() { + return !!calls.length + } - /** - * Get the "this" object that was passed to a specific invocation of this spy. - * @name Spy#calls#thisFor - * @since 3.8.0 - * @function - * @param {Integer} index The 0-based invocation index. - * @return {Object?} - */ - this.thisFor = function(index) { - const call = calls[index]; - return call ? call.object : undefined; - }; + /** + * Get the number of invocations of this spy. + * @name Spy#calls#count + * @since 2.0.0 + * @function + * @return {Integer} + */ + this.count = function() { + return calls.length + } - /** - * Get the raw calls array for this spy. - * @name Spy#calls#all - * @since 2.0.0 - * @function - * @return {Spy.callData[]} - */ - this.all = function() { - return calls; - }; + /** + * Get the arguments that were passed to a specific invocation of this spy. + * @name Spy#calls#argsFor + * @since 2.0.0 + * @function + * @param {Integer} index The 0-based invocation index. + * @return {Array} + */ + this.argsFor = function(index) { + const call = calls[index] + return call ? call.args : [] + } - /** - * Get all of the arguments for each invocation of this spy in the order they were received. - * @name Spy#calls#allArgs - * @since 2.0.0 - * @function - * @return {Array} - */ - this.allArgs = function() { - return calls.map(c => c.args); - }; + /** + * Get the "this" object that was passed to a specific invocation of this spy. + * @name Spy#calls#thisFor + * @since 3.8.0 + * @function + * @param {Integer} index The 0-based invocation index. + * @return {Object?} + */ + this.thisFor = function(index) { + const call = calls[index] + return call ? call.object : undefined + } - /** - * Get the first invocation of this spy. - * @name Spy#calls#first - * @since 2.0.0 - * @function - * @return {ObjecSpy.callData} - */ - this.first = function() { - return calls[0]; - }; + /** + * Get the raw calls array for this spy. + * @name Spy#calls#all + * @since 2.0.0 + * @function + * @return {Spy.callData[]} + */ + this.all = function() { + return calls + } - /** - * Get the most recent invocation of this spy. - * @name Spy#calls#mostRecent - * @since 2.0.0 - * @function - * @return {ObjecSpy.callData} - */ - this.mostRecent = function() { - return calls[calls.length - 1]; - }; + /** + * Get all of the arguments for each invocation of this spy in the order they were received. + * @name Spy#calls#allArgs + * @since 2.0.0 + * @function + * @return {Array} + */ + this.allArgs = function() { + return calls.map((c) => c.args) + } - /** - * Reset this spy as if it has never been called. - * @name Spy#calls#reset - * @since 2.0.0 - * @function - */ - this.reset = function() { - calls = []; - }; + /** + * Get the first invocation of this spy. + * @name Spy#calls#first + * @since 2.0.0 + * @function + * @return {ObjecSpy.callData} + */ + this.first = function() { + return calls[0] + } - /** - * Set this spy to do a shallow clone of arguments passed to each invocation. - * @name Spy#calls#saveArgumentsByValue - * @since 2.5.0 - * @function - */ - this.saveArgumentsByValue = function() { - opts.cloneArgs = true; - }; - } + /** + * Get the most recent invocation of this spy. + * @name Spy#calls#mostRecent + * @since 2.0.0 + * @function + * @return {ObjecSpy.callData} + */ + this.mostRecent = function() { + return calls[calls.length - 1] + } - return CallTracker; -}; + /** + * Reset this spy as if it has never been called. + * @name Spy#calls#reset + * @since 2.0.0 + * @function + */ + this.reset = function() { + calls = [] + } + + /** + * Set this spy to do a shallow clone of arguments passed to each invocation. + * @name Spy#calls#saveArgumentsByValue + * @since 2.5.0 + * @function + */ + this.saveArgumentsByValue = function() { + opts.cloneArgs = true + } + } + + return CallTracker +} getJasmineRequireObj().clearStack = function(j$) { - const maxInlineCallCount = 10; + const maxInlineCallCount = 10 - function browserQueueMicrotaskImpl(global) { - const { setTimeout, queueMicrotask } = global; - let currentCallCount = 0; - return function clearStack(fn) { - currentCallCount++; + function browserQueueMicrotaskImpl(global) { + const { setTimeout, queueMicrotask } = global + let currentCallCount = 0 + return function clearStack(fn) { + currentCallCount++ - if (currentCallCount < maxInlineCallCount) { - queueMicrotask(fn); - } else { - currentCallCount = 0; - setTimeout(fn); - } - }; - } - - function nodeQueueMicrotaskImpl(global) { - const { queueMicrotask } = global; - - return function(fn) { - queueMicrotask(fn); - }; - } - - function messageChannelImpl(global) { - const { MessageChannel, setTimeout } = global; - const channel = new MessageChannel(); - let head = {}; - let tail = head; - - let taskRunning = false; - channel.port1.onmessage = function() { - head = head.next; - const task = head.task; - delete head.task; - - if (taskRunning) { - setTimeout(task, 0); - } else { - try { - taskRunning = true; - task(); - } finally { - taskRunning = false; + if (currentCallCount < maxInlineCallCount) { + queueMicrotask(fn) + } else { + currentCallCount = 0 + setTimeout(fn) + } } - } - }; - - let currentCallCount = 0; - return function clearStack(fn) { - currentCallCount++; - - if (currentCallCount < maxInlineCallCount) { - tail = tail.next = { task: fn }; - channel.port2.postMessage(0); - } else { - currentCallCount = 0; - setTimeout(fn); - } - }; - } - - function getClearStack(global) { - const NODE_JS = - global.process && - global.process.versions && - typeof global.process.versions.node === 'string'; - - const SAFARI = - global.navigator && - /^((?!chrome|android).)*safari/i.test(global.navigator.userAgent); - - if (NODE_JS) { - // Unlike browsers, Node doesn't require us to do a periodic setTimeout - // so we avoid the overhead. - return nodeQueueMicrotaskImpl(global); - } else if ( - SAFARI || - j$.util.isUndefined(global.MessageChannel) /* tests */ - ) { - // queueMicrotask is dramatically faster than MessageChannel in Safari, - // at least through version 16. - // Some of our own integration tests provide a mock queueMicrotask in all - // environments because it's simpler to mock than MessageChannel. - return browserQueueMicrotaskImpl(global); - } else { - // MessageChannel is faster than queueMicrotask in supported browsers - // other than Safari. - return messageChannelImpl(global); } - } - return getClearStack; -}; + function nodeQueueMicrotaskImpl(global) { + const { queueMicrotask } = global + + return function(fn) { + queueMicrotask(fn) + } + } + + function messageChannelImpl(global) { + const { MessageChannel, setTimeout } = global + const channel = new MessageChannel() + let head = {} + let tail = head + + let taskRunning = false + channel.port1.onmessage = function() { + head = head.next + const task = head.task + delete head.task + + if (taskRunning) { + setTimeout(task, 0) + } else { + try { + taskRunning = true + task() + } finally { + taskRunning = false + } + } + } + + let currentCallCount = 0 + return function clearStack(fn) { + currentCallCount++ + + if (currentCallCount < maxInlineCallCount) { + tail = tail.next = { task: fn } + channel.port2.postMessage(0) + } else { + currentCallCount = 0 + setTimeout(fn) + } + } + } + + function getClearStack(global) { + const NODE_JS = global.process && global.process.versions && typeof global.process.versions.node === "string" + + const SAFARI = global.navigator && /^((?!chrome|android).)*safari/i.test(global.navigator.userAgent) + + if (NODE_JS) { + // Unlike browsers, Node doesn't require us to do a periodic setTimeout + // so we avoid the overhead. + return nodeQueueMicrotaskImpl(global) + } else if (SAFARI || j$.util.isUndefined(global.MessageChannel) /* tests */) { + // queueMicrotask is dramatically faster than MessageChannel in Safari, + // at least through version 16. + // Some of our own integration tests provide a mock queueMicrotask in all + // environments because it's simpler to mock than MessageChannel. + return browserQueueMicrotaskImpl(global) + } else { + // MessageChannel is faster than queueMicrotask in supported browsers + // other than Safari. + return messageChannelImpl(global) + } + } + + return getClearStack +} getJasmineRequireObj().Clock = function() { - /* global process */ - const NODE_JS = - typeof process !== 'undefined' && - process.versions && - typeof process.versions.node === 'string'; - - /** - * @class Clock - * @since 1.3.0 - * @classdesc Jasmine's mock clock is used when testing time dependent code.
    - * _Note:_ Do not construct this directly. You can get the current clock with - * {@link jasmine.clock}. - * @hideconstructor - */ - function Clock(global, delayedFunctionSchedulerFactory, mockDate) { - const realTimingFunctions = { - setTimeout: global.setTimeout, - clearTimeout: global.clearTimeout, - setInterval: global.setInterval, - clearInterval: global.clearInterval - }; - const fakeTimingFunctions = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setInterval: setInterval, - clearInterval: clearInterval - }; - let installed = false; - let delayedFunctionScheduler; - let timer; - - this.FakeTimeout = FakeTimeout; + /* global process */ + const NODE_JS = typeof process !== "undefined" && process.versions && typeof process.versions.node === "string" /** - * Install the mock clock over the built-in methods. - * @name Clock#install - * @since 2.0.0 - * @function - * @return {Clock} - */ - this.install = function() { - if (!originalTimingFunctionsIntact()) { - throw new Error( - 'Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?' - ); - } - replace(global, fakeTimingFunctions); - timer = fakeTimingFunctions; - delayedFunctionScheduler = delayedFunctionSchedulerFactory(); - installed = true; - - return this; - }; - - /** - * Uninstall the mock clock, returning the built-in methods to their places. - * @name Clock#uninstall - * @since 2.0.0 - * @function - */ - this.uninstall = function() { - delayedFunctionScheduler = null; - mockDate.uninstall(); - replace(global, realTimingFunctions); - - timer = realTimingFunctions; - installed = false; - }; - - /** - * Execute a function with a mocked Clock - * - * The clock will be {@link Clock#install|install}ed before the function is called and {@link Clock#uninstall|uninstall}ed in a `finally` after the function completes. - * @name Clock#withMock - * @since 2.3.0 - * @function - * @param {Function} closure The function to be called. - */ - this.withMock = function(closure) { - this.install(); - try { - closure(); - } finally { - this.uninstall(); - } - }; - - /** - * Instruct the installed Clock to also mock the date returned by `new Date()` - * @name Clock#mockDate - * @since 2.1.0 - * @function - * @param {Date} [initialDate=now] The `Date` to provide. - */ - this.mockDate = function(initialDate) { - mockDate.install(initialDate); - }; - - this.setTimeout = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setTimeout, [ - global, - arguments - ]); - }; - - this.setInterval = function(fn, delay, params) { - return Function.prototype.apply.apply(timer.setInterval, [ - global, - arguments - ]); - }; - - this.clearTimeout = function(id) { - return Function.prototype.call.apply(timer.clearTimeout, [global, id]); - }; - - this.clearInterval = function(id) { - return Function.prototype.call.apply(timer.clearInterval, [global, id]); - }; - - /** - * Tick the Clock forward, running any enqueued timeouts along the way - * @name Clock#tick + * @class Clock * @since 1.3.0 - * @function - * @param {int} millis The number of milliseconds to tick. + * @classdesc Jasmine's mock clock is used when testing time dependent code.
    + * _Note:_ Do not construct this directly. You can get the current clock with + * {@link jasmine.clock}. + * @hideconstructor */ - this.tick = function(millis) { - if (installed) { - delayedFunctionScheduler.tick(millis, function(millis) { - mockDate.tick(millis); - }); - } else { - throw new Error( - 'Mock clock is not installed, use jasmine.clock().install()' - ); - } - }; + function Clock(global, delayedFunctionSchedulerFactory, mockDate) { + const realTimingFunctions = { + setTimeout: global.setTimeout, + clearTimeout: global.clearTimeout, + setInterval: global.setInterval, + clearInterval: global.clearInterval, + } + const fakeTimingFunctions = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setInterval: setInterval, + clearInterval: clearInterval, + } + let installed = false + let delayedFunctionScheduler + let timer - return this; + this.FakeTimeout = FakeTimeout - function originalTimingFunctionsIntact() { - return ( - global.setTimeout === realTimingFunctions.setTimeout && - global.clearTimeout === realTimingFunctions.clearTimeout && - global.setInterval === realTimingFunctions.setInterval && - global.clearInterval === realTimingFunctions.clearInterval - ); + /** + * Install the mock clock over the built-in methods. + * @name Clock#install + * @since 2.0.0 + * @function + * @return {Clock} + */ + this.install = function() { + if (!originalTimingFunctionsIntact()) { + throw new Error( + "Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?" + ) + } + replace(global, fakeTimingFunctions) + timer = fakeTimingFunctions + delayedFunctionScheduler = delayedFunctionSchedulerFactory() + installed = true + + return this + } + + /** + * Uninstall the mock clock, returning the built-in methods to their places. + * @name Clock#uninstall + * @since 2.0.0 + * @function + */ + this.uninstall = function() { + delayedFunctionScheduler = null + mockDate.uninstall() + replace(global, realTimingFunctions) + + timer = realTimingFunctions + installed = false + } + + /** + * Execute a function with a mocked Clock + * + * The clock will be {@link Clock#install|install}ed before the function is called and {@link Clock#uninstall|uninstall}ed in a `finally` after the function completes. + * @name Clock#withMock + * @since 2.3.0 + * @function + * @param {Function} closure The function to be called. + */ + this.withMock = function(closure) { + this.install() + try { + closure() + } finally { + this.uninstall() + } + } + + /** + * Instruct the installed Clock to also mock the date returned by `new Date()` + * @name Clock#mockDate + * @since 2.1.0 + * @function + * @param {Date} [initialDate=now] The `Date` to provide. + */ + this.mockDate = function(initialDate) { + mockDate.install(initialDate) + } + + this.setTimeout = function(fn, delay, params) { + return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]) + } + + this.setInterval = function(fn, delay, params) { + return Function.prototype.apply.apply(timer.setInterval, [global, arguments]) + } + + this.clearTimeout = function(id) { + return Function.prototype.call.apply(timer.clearTimeout, [global, id]) + } + + this.clearInterval = function(id) { + return Function.prototype.call.apply(timer.clearInterval, [global, id]) + } + + /** + * Tick the Clock forward, running any enqueued timeouts along the way + * @name Clock#tick + * @since 1.3.0 + * @function + * @param {int} millis The number of milliseconds to tick. + */ + this.tick = function(millis) { + if (installed) { + delayedFunctionScheduler.tick(millis, function(millis) { + mockDate.tick(millis) + }) + } else { + throw new Error("Mock clock is not installed, use jasmine.clock().install()") + } + } + + return this + + function originalTimingFunctionsIntact() { + return ( + global.setTimeout === realTimingFunctions.setTimeout && + global.clearTimeout === realTimingFunctions.clearTimeout && + global.setInterval === realTimingFunctions.setInterval && + global.clearInterval === realTimingFunctions.clearInterval + ) + } + + function replace(dest, source) { + for (const prop in source) { + dest[prop] = source[prop] + } + } + + function setTimeout(fn, delay) { + if (!NODE_JS) { + return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)) + } + + const timeout = new FakeTimeout() + + delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2), false, timeout) + + return timeout + } + + function clearTimeout(id) { + return delayedFunctionScheduler.removeFunctionWithId(id) + } + + function setInterval(fn, interval) { + if (!NODE_JS) { + return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true) + } + + const timeout = new FakeTimeout() + + delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true, timeout) + + return timeout + } + + function clearInterval(id) { + return delayedFunctionScheduler.removeFunctionWithId(id) + } + + function argSlice(argsObj, n) { + return Array.prototype.slice.call(argsObj, n) + } } - function replace(dest, source) { - for (const prop in source) { - dest[prop] = source[prop]; - } + /** + * Mocks Node.js Timeout class + */ + function FakeTimeout() {} + + FakeTimeout.prototype.ref = function() { + return this } - function setTimeout(fn, delay) { - if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction( - fn, - delay, - argSlice(arguments, 2) - ); - } - - const timeout = new FakeTimeout(); - - delayedFunctionScheduler.scheduleFunction( - fn, - delay, - argSlice(arguments, 2), - false, - timeout - ); - - return timeout; + FakeTimeout.prototype.unref = function() { + return this } - function clearTimeout(id) { - return delayedFunctionScheduler.removeFunctionWithId(id); - } - - function setInterval(fn, interval) { - if (!NODE_JS) { - return delayedFunctionScheduler.scheduleFunction( - fn, - interval, - argSlice(arguments, 2), - true - ); - } - - const timeout = new FakeTimeout(); - - delayedFunctionScheduler.scheduleFunction( - fn, - interval, - argSlice(arguments, 2), - true, - timeout - ); - - return timeout; - } - - function clearInterval(id) { - return delayedFunctionScheduler.removeFunctionWithId(id); - } - - function argSlice(argsObj, n) { - return Array.prototype.slice.call(argsObj, n); - } - } - - /** - * Mocks Node.js Timeout class - */ - function FakeTimeout() {} - - FakeTimeout.prototype.ref = function() { - return this; - }; - - FakeTimeout.prototype.unref = function() { - return this; - }; - - return Clock; -}; + return Clock +} getJasmineRequireObj().CompleteOnFirstErrorSkipPolicy = function(j$) { - function CompleteOnFirstErrorSkipPolicy(queueableFns) { - this.queueableFns_ = queueableFns; - this.erroredFnIx_ = null; - } - - CompleteOnFirstErrorSkipPolicy.prototype.skipTo = function(lastRanFnIx) { - let i; - - for ( - i = lastRanFnIx + 1; - i < this.queueableFns_.length && this.shouldSkip_(i); - i++ - ) {} - return i; - }; - - CompleteOnFirstErrorSkipPolicy.prototype.fnErrored = function(fnIx) { - this.erroredFnIx_ = fnIx; - }; - - CompleteOnFirstErrorSkipPolicy.prototype.shouldSkip_ = function(fnIx) { - if (this.erroredFnIx_ === null) { - return false; + function CompleteOnFirstErrorSkipPolicy(queueableFns) { + this.queueableFns_ = queueableFns + this.erroredFnIx_ = null } - const fn = this.queueableFns_[fnIx]; - const candidateSuite = fn.suite; - const errorSuite = this.queueableFns_[this.erroredFnIx_].suite; - const wasCleanupFn = - fn.type === 'afterEach' || - fn.type === 'afterAll' || - fn.type === 'specCleanup'; - return ( - !wasCleanupFn || - (candidateSuite && isDescendent(candidateSuite, errorSuite)) - ); - }; + CompleteOnFirstErrorSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + let i - function isDescendent(candidate, ancestor) { - if (!candidate.parentSuite) { - return false; - } else if (candidate.parentSuite === ancestor) { - return true; - } else { - return isDescendent(candidate.parentSuite, ancestor); + for (i = lastRanFnIx + 1; i < this.queueableFns_.length && this.shouldSkip_(i); i++) {} + return i } - } - return CompleteOnFirstErrorSkipPolicy; -}; + CompleteOnFirstErrorSkipPolicy.prototype.fnErrored = function(fnIx) { + this.erroredFnIx_ = fnIx + } + + CompleteOnFirstErrorSkipPolicy.prototype.shouldSkip_ = function(fnIx) { + if (this.erroredFnIx_ === null) { + return false + } + + const fn = this.queueableFns_[fnIx] + const candidateSuite = fn.suite + const errorSuite = this.queueableFns_[this.erroredFnIx_].suite + const wasCleanupFn = fn.type === "afterEach" || fn.type === "afterAll" || fn.type === "specCleanup" + return !wasCleanupFn || (candidateSuite && isDescendent(candidateSuite, errorSuite)) + } + + function isDescendent(candidate, ancestor) { + if (!candidate.parentSuite) { + return false + } else if (candidate.parentSuite === ancestor) { + return true + } else { + return isDescendent(candidate.parentSuite, ancestor) + } + } + + return CompleteOnFirstErrorSkipPolicy +} getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { - function DelayedFunctionScheduler() { - this.scheduledLookup_ = []; - this.scheduledFunctions_ = {}; - this.currentTime_ = 0; - this.delayedFnCount_ = 0; - this.deletedKeys_ = []; + function DelayedFunctionScheduler() { + this.scheduledLookup_ = [] + this.scheduledFunctions_ = {} + this.currentTime_ = 0 + this.delayedFnCount_ = 0 + this.deletedKeys_ = [] - this.tick = function(millis, tickDate) { - millis = millis || 0; - const endTime = this.currentTime_ + millis; + this.tick = function(millis, tickDate) { + millis = millis || 0 + const endTime = this.currentTime_ + millis - this.runScheduledFunctions_(endTime, tickDate); - }; + this.runScheduledFunctions_(endTime, tickDate) + } - this.scheduleFunction = function( - funcToCall, - millis, - params, - recurring, - timeoutKey, - runAtMillis - ) { - let f; - if (typeof funcToCall === 'string') { - f = function() { - // eslint-disable-next-line no-eval - return eval(funcToCall); - }; - } else { - f = funcToCall; - } + this.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { + let f + if (typeof funcToCall === "string") { + f = function() { + // eslint-disable-next-line no-eval + return eval(funcToCall) + } + } else { + f = funcToCall + } - millis = millis || 0; - timeoutKey = timeoutKey || ++this.delayedFnCount_; - runAtMillis = runAtMillis || this.currentTime_ + millis; + millis = millis || 0 + timeoutKey = timeoutKey || ++this.delayedFnCount_ + runAtMillis = runAtMillis || this.currentTime_ + millis - const funcToSchedule = { - runAtMillis: runAtMillis, - funcToCall: f, - recurring: recurring, - params: params, - timeoutKey: timeoutKey, - millis: millis - }; + const funcToSchedule = { + runAtMillis: runAtMillis, + funcToCall: f, + recurring: recurring, + params: params, + timeoutKey: timeoutKey, + millis: millis, + } - if (runAtMillis in this.scheduledFunctions_) { - this.scheduledFunctions_[runAtMillis].push(funcToSchedule); - } else { - this.scheduledFunctions_[runAtMillis] = [funcToSchedule]; - this.scheduledLookup_.push(runAtMillis); - this.scheduledLookup_.sort(function(a, b) { - return a - b; - }); - } + if (runAtMillis in this.scheduledFunctions_) { + this.scheduledFunctions_[runAtMillis].push(funcToSchedule) + } else { + this.scheduledFunctions_[runAtMillis] = [funcToSchedule] + this.scheduledLookup_.push(runAtMillis) + this.scheduledLookup_.sort(function(a, b) { + return a - b + }) + } - return timeoutKey; - }; + return timeoutKey + } - this.removeFunctionWithId = function(timeoutKey) { - this.deletedKeys_.push(timeoutKey); + this.removeFunctionWithId = function(timeoutKey) { + this.deletedKeys_.push(timeoutKey) - for (const runAtMillis in this.scheduledFunctions_) { - const funcs = this.scheduledFunctions_[runAtMillis]; - const i = indexOfFirstToPass(funcs, function(func) { - return func.timeoutKey === timeoutKey; - }); + for (const runAtMillis in this.scheduledFunctions_) { + const funcs = this.scheduledFunctions_[runAtMillis] + const i = indexOfFirstToPass(funcs, function(func) { + return func.timeoutKey === timeoutKey + }) + + if (i > -1) { + if (funcs.length === 1) { + delete this.scheduledFunctions_[runAtMillis] + this.deleteFromLookup_(runAtMillis) + } else { + funcs.splice(i, 1) + } + + // intervals get rescheduled when executed, so there's never more + // than a single scheduled function with a given timeoutKey + break + } + } + } + + return this + } + + DelayedFunctionScheduler.prototype.runScheduledFunctions_ = function(endTime, tickDate) { + tickDate = tickDate || function() {} + if (this.scheduledLookup_.length === 0 || this.scheduledLookup_[0] > endTime) { + if (endTime >= this.currentTime_) { + tickDate(endTime - this.currentTime_) + this.currentTime_ = endTime + } + return + } + + do { + this.deletedKeys_ = [] + const newCurrentTime = this.scheduledLookup_.shift() + if (newCurrentTime >= this.currentTime_) { + tickDate(newCurrentTime - this.currentTime_) + this.currentTime_ = newCurrentTime + } + + const funcsToRun = this.scheduledFunctions_[this.currentTime_] + + delete this.scheduledFunctions_[this.currentTime_] + + for (const fn of funcsToRun) { + if (fn.recurring) { + this.reschedule_(fn) + } + } + + for (const fn of funcsToRun) { + if (this.deletedKeys_.includes(fn.timeoutKey)) { + // skip a timeoutKey deleted whilst we were running + return + } + fn.funcToCall.apply(null, fn.params || []) + } + this.deletedKeys_ = [] + } while ( + this.scheduledLookup_.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + this.currentTime_ !== endTime && + this.scheduledLookup_[0] <= endTime + ) + + // ran out of functions to call, but still time left on the clock + if (endTime >= this.currentTime_) { + tickDate(endTime - this.currentTime_) + this.currentTime_ = endTime + } + } + + DelayedFunctionScheduler.prototype.reschedule_ = function(scheduledFn) { + this.scheduleFunction( + scheduledFn.funcToCall, + scheduledFn.millis, + scheduledFn.params, + true, + scheduledFn.timeoutKey, + scheduledFn.runAtMillis + scheduledFn.millis + ) + } + + DelayedFunctionScheduler.prototype.deleteFromLookup_ = function(key) { + const value = Number(key) + const i = indexOfFirstToPass(this.scheduledLookup_, function(millis) { + return millis === value + }) if (i > -1) { - if (funcs.length === 1) { - delete this.scheduledFunctions_[runAtMillis]; - this.deleteFromLookup_(runAtMillis); - } else { - funcs.splice(i, 1); - } - - // intervals get rescheduled when executed, so there's never more - // than a single scheduled function with a given timeoutKey - break; + this.scheduledLookup_.splice(i, 1) } - } - }; - - return this; - } - - DelayedFunctionScheduler.prototype.runScheduledFunctions_ = function( - endTime, - tickDate - ) { - tickDate = tickDate || function() {}; - if ( - this.scheduledLookup_.length === 0 || - this.scheduledLookup_[0] > endTime - ) { - if (endTime >= this.currentTime_) { - tickDate(endTime - this.currentTime_); - this.currentTime_ = endTime; - } - return; } - do { - this.deletedKeys_ = []; - const newCurrentTime = this.scheduledLookup_.shift(); - if (newCurrentTime >= this.currentTime_) { - tickDate(newCurrentTime - this.currentTime_); - this.currentTime_ = newCurrentTime; - } + function indexOfFirstToPass(array, testFn) { + let index = -1 - const funcsToRun = this.scheduledFunctions_[this.currentTime_]; - - delete this.scheduledFunctions_[this.currentTime_]; - - for (const fn of funcsToRun) { - if (fn.recurring) { - this.reschedule_(fn); + for (let i = 0; i < array.length; ++i) { + if (testFn(array[i])) { + index = i + break + } } - } - for (const fn of funcsToRun) { - if (this.deletedKeys_.includes(fn.timeoutKey)) { - // skip a timeoutKey deleted whilst we were running - return; - } - fn.funcToCall.apply(null, fn.params || []); - } - this.deletedKeys_ = []; - } while ( - this.scheduledLookup_.length > 0 && - // checking first if we're out of time prevents setTimeout(0) - // scheduled in a funcToRun from forcing an extra iteration - this.currentTime_ !== endTime && - this.scheduledLookup_[0] <= endTime - ); - - // ran out of functions to call, but still time left on the clock - if (endTime >= this.currentTime_) { - tickDate(endTime - this.currentTime_); - this.currentTime_ = endTime; - } - }; - - DelayedFunctionScheduler.prototype.reschedule_ = function(scheduledFn) { - this.scheduleFunction( - scheduledFn.funcToCall, - scheduledFn.millis, - scheduledFn.params, - true, - scheduledFn.timeoutKey, - scheduledFn.runAtMillis + scheduledFn.millis - ); - }; - - DelayedFunctionScheduler.prototype.deleteFromLookup_ = function(key) { - const value = Number(key); - const i = indexOfFirstToPass(this.scheduledLookup_, function(millis) { - return millis === value; - }); - - if (i > -1) { - this.scheduledLookup_.splice(i, 1); - } - }; - - function indexOfFirstToPass(array, testFn) { - let index = -1; - - for (let i = 0; i < array.length; ++i) { - if (testFn(array[i])) { - index = i; - break; - } + return index } - return index; - } - - return DelayedFunctionScheduler; -}; + return DelayedFunctionScheduler +} getJasmineRequireObj().Deprecator = function(j$) { - function Deprecator(topSuite) { - this.topSuite_ = topSuite; - this.verbose_ = false; - this.toSuppress_ = []; - } - - const verboseNote = - 'Note: This message will be shown only once. Set the verboseDeprecations ' + - 'config property to true to see every occurrence.'; - - Deprecator.prototype.verboseDeprecations = function(enabled) { - this.verbose_ = enabled; - }; - - // runnable is a spec or a suite. - // deprecation is a string or an Error. - // See Env#deprecated for a description of the options argument. - Deprecator.prototype.addDeprecationWarning = function( - runnable, - deprecation, - options - ) { - options = options || {}; - - if (!this.verbose_ && !j$.isError_(deprecation)) { - if (this.toSuppress_.indexOf(deprecation) !== -1) { - return; - } - this.toSuppress_.push(deprecation); + function Deprecator(topSuite) { + this.topSuite_ = topSuite + this.verbose_ = false + this.toSuppress_ = [] } - this.log_(runnable, deprecation, options); - this.report_(runnable, deprecation, options); - }; + const verboseNote = + "Note: This message will be shown only once. Set the verboseDeprecations " + + "config property to true to see every occurrence." - Deprecator.prototype.log_ = function(runnable, deprecation, options) { - if (j$.isError_(deprecation)) { - console.error(deprecation); - return; + Deprecator.prototype.verboseDeprecations = function(enabled) { + this.verbose_ = enabled } - let context; + // runnable is a spec or a suite. + // deprecation is a string or an Error. + // See Env#deprecated for a description of the options argument. + Deprecator.prototype.addDeprecationWarning = function(runnable, deprecation, options) { + options = options || {} - if (runnable === this.topSuite_ || options.ignoreRunnable) { - context = ''; - } else if (runnable.children) { - context = ' (in suite: ' + runnable.getFullName() + ')'; - } else { - context = ' (in spec: ' + runnable.getFullName() + ')'; + if (!this.verbose_ && !j$.isError_(deprecation)) { + if (this.toSuppress_.indexOf(deprecation) !== -1) { + return + } + this.toSuppress_.push(deprecation) + } + + this.log_(runnable, deprecation, options) + this.report_(runnable, deprecation, options) } - if (!options.omitStackTrace) { - context += '\n' + this.stackTrace_(); + Deprecator.prototype.log_ = function(runnable, deprecation, options) { + if (j$.isError_(deprecation)) { + console.error(deprecation) + return + } + + let context + + if (runnable === this.topSuite_ || options.ignoreRunnable) { + context = "" + } else if (runnable.children) { + context = " (in suite: " + runnable.getFullName() + ")" + } else { + context = " (in spec: " + runnable.getFullName() + ")" + } + + if (!options.omitStackTrace) { + context += "\n" + this.stackTrace_() + } + + if (!this.verbose_) { + context += "\n" + verboseNote + } + + console.error("DEPRECATION: " + deprecation + context) } - if (!this.verbose_) { - context += '\n' + verboseNote; + Deprecator.prototype.stackTrace_ = function() { + const formatter = new j$.ExceptionFormatter() + return formatter.stack(j$.util.errorWithStack()).replace(/^Error\n/m, "") } - console.error('DEPRECATION: ' + deprecation + context); - }; + Deprecator.prototype.report_ = function(runnable, deprecation, options) { + if (options.ignoreRunnable) { + runnable = this.topSuite_ + } - Deprecator.prototype.stackTrace_ = function() { - const formatter = new j$.ExceptionFormatter(); - return formatter.stack(j$.util.errorWithStack()).replace(/^Error\n/m, ''); - }; + if (j$.isError_(deprecation)) { + runnable.addDeprecationWarning(deprecation) + return + } - Deprecator.prototype.report_ = function(runnable, deprecation, options) { - if (options.ignoreRunnable) { - runnable = this.topSuite_; + if (!this.verbose_) { + deprecation += "\n" + verboseNote + } + + runnable.addDeprecationWarning({ + message: deprecation, + omitStackTrace: options.omitStackTrace || false, + }) } - if (j$.isError_(deprecation)) { - runnable.addDeprecationWarning(deprecation); - return; - } - - if (!this.verbose_) { - deprecation += '\n' + verboseNote; - } - - runnable.addDeprecationWarning({ - message: deprecation, - omitStackTrace: options.omitStackTrace || false - }); - }; - - return Deprecator; -}; + return Deprecator +} getJasmineRequireObj().errors = function() { - function ExpectationFailed() {} + function ExpectationFailed() {} - ExpectationFailed.prototype = new Error(); - ExpectationFailed.prototype.constructor = ExpectationFailed; + ExpectationFailed.prototype = new Error() + ExpectationFailed.prototype.constructor = ExpectationFailed - return { - ExpectationFailed: ExpectationFailed - }; -}; + return { + ExpectationFailed: ExpectationFailed, + } +} getJasmineRequireObj().ExceptionFormatter = function(j$) { - const ignoredProperties = [ - 'name', - 'message', - 'stack', - 'fileName', - 'sourceURL', - 'line', - 'lineNumber', - 'column', - 'description', - 'jasmineMessage' - ]; + const ignoredProperties = [ + "name", + "message", + "stack", + "fileName", + "sourceURL", + "line", + "lineNumber", + "column", + "description", + "jasmineMessage", + ] - function ExceptionFormatter(options) { - const jasmineFile = - (options && options.jasmineFile) || j$.util.jasmineFile(); - this.message = function(error) { - let message = ''; + function ExceptionFormatter(options) { + const jasmineFile = (options && options.jasmineFile) || j$.util.jasmineFile() + this.message = function(error) { + let message = "" - if (error.jasmineMessage) { - message += error.jasmineMessage; - } else if (error.name && error.message) { - message += error.name + ': ' + error.message; - } else if (error.message) { - message += error.message; - } else { - message += error.toString() + ' thrown'; - } + if (error.jasmineMessage) { + message += error.jasmineMessage + } else if (error.name && error.message) { + message += error.name + ": " + error.message + } else if (error.message) { + message += error.message + } else { + message += error.toString() + " thrown" + } - if (error.fileName || error.sourceURL) { - message += ' in ' + (error.fileName || error.sourceURL); - } + if (error.fileName || error.sourceURL) { + message += " in " + (error.fileName || error.sourceURL) + } - if (error.line || error.lineNumber) { - message += ' (line ' + (error.line || error.lineNumber) + ')'; - } + if (error.line || error.lineNumber) { + message += " (line " + (error.line || error.lineNumber) + ")" + } - return message; - }; - - this.stack = function(error, { omitMessage } = {}) { - if (!error || !error.stack) { - return null; - } - - const lines = this.stack_(error, { - messageHandling: omitMessage ? 'omit' : undefined - }); - return lines.join('\n'); - }; - - // messageHandling can be falsy (unspecified), 'omit', or 'require' - this.stack_ = function(error, { messageHandling }) { - let lines = formatProperties(error).split('\n'); - - if (lines[lines.length - 1] === '') { - lines.pop(); - } - - const stackTrace = new j$.StackTrace(error); - lines = lines.concat(filterJasmine(stackTrace)); - - if (messageHandling === 'require') { - lines.unshift(stackTrace.message || 'Error: ' + error.message); - } else if (messageHandling !== 'omit' && stackTrace.message) { - lines.unshift(stackTrace.message); - } - - if (error.cause) { - const substack = this.stack_(error.cause, { - messageHandling: 'require' - }); - substack[0] = 'Caused by: ' + substack[0]; - lines = lines.concat(substack); - } - - return lines; - }; - - function filterJasmine(stackTrace) { - const result = []; - const jasmineMarker = - stackTrace.style === 'webkit' ? '' : ' at '; - - stackTrace.frames.forEach(function(frame) { - if (frame.file !== jasmineFile) { - result.push(frame.raw); - } else if (result[result.length - 1] !== jasmineMarker) { - result.push(jasmineMarker); + return message } - }); - return result; + this.stack = function(error, { omitMessage } = {}) { + if (!error || !error.stack) { + return null + } + + const lines = this.stack_(error, { + messageHandling: omitMessage ? "omit" : undefined, + }) + return lines.join("\n") + } + + // messageHandling can be falsy (unspecified), 'omit', or 'require' + this.stack_ = function(error, { messageHandling }) { + let lines = formatProperties(error).split("\n") + + if (lines[lines.length - 1] === "") { + lines.pop() + } + + const stackTrace = new j$.StackTrace(error) + lines = lines.concat(filterJasmine(stackTrace)) + + if (messageHandling === "require") { + lines.unshift(stackTrace.message || "Error: " + error.message) + } else if (messageHandling !== "omit" && stackTrace.message) { + lines.unshift(stackTrace.message) + } + + if (error.cause) { + const substack = this.stack_(error.cause, { + messageHandling: "require", + }) + substack[0] = "Caused by: " + substack[0] + lines = lines.concat(substack) + } + + return lines + } + + function filterJasmine(stackTrace) { + const result = [] + const jasmineMarker = stackTrace.style === "webkit" ? "" : " at " + + stackTrace.frames.forEach(function(frame) { + if (frame.file !== jasmineFile) { + result.push(frame.raw) + } else if (result[result.length - 1] !== jasmineMarker) { + result.push(jasmineMarker) + } + }) + + return result + } + + function formatProperties(error) { + if (!(error instanceof Object)) { + return + } + + const result = {} + let empty = true + + for (const prop in error) { + if (ignoredProperties.includes(prop)) { + continue + } + result[prop] = error[prop] + empty = false + } + + if (!empty) { + return "error properties: " + j$.basicPrettyPrinter_(result) + "\n" + } + + return "" + } } - function formatProperties(error) { - if (!(error instanceof Object)) { - return; - } - - const result = {}; - let empty = true; - - for (const prop in error) { - if (ignoredProperties.includes(prop)) { - continue; - } - result[prop] = error[prop]; - empty = false; - } - - if (!empty) { - return 'error properties: ' + j$.basicPrettyPrinter_(result) + '\n'; - } - - return ''; - } - } - - return ExceptionFormatter; -}; + return ExceptionFormatter +} getJasmineRequireObj().Expectation = function(j$) { - /** - * Matchers that come with Jasmine out of the box. - * @namespace matchers - */ - function Expectation(options) { - this.expector = new j$.Expector(options); + /** + * Matchers that come with Jasmine out of the box. + * @namespace matchers + */ + function Expectation(options) { + this.expector = new j$.Expector(options) - const customMatchers = options.customMatchers || {}; - for (const matcherName in customMatchers) { - this[matcherName] = wrapSyncCompare( - matcherName, - customMatchers[matcherName] - ); - } - } - - /** - * Add some context for an {@link expect} - * @function - * @name matchers#withContext - * @since 3.3.0 - * @param {String} message - Additional context to show when the matcher fails - * @return {matchers} - */ - Expectation.prototype.withContext = function withContext(message) { - return addFilter(this, new ContextAddingFilter(message)); - }; - - /** - * Invert the matcher following this {@link expect} - * @member - * @name matchers#not - * @since 1.3.0 - * @type {matchers} - * @example - * expect(something).not.toBe(true); - */ - Object.defineProperty(Expectation.prototype, 'not', { - get: function() { - return addFilter(this, syncNegatingFilter); - } - }); - - /** - * Asynchronous matchers that operate on an actual value which is a promise, - * and return a promise. - * - * Most async matchers will wait indefinitely for the promise to be resolved - * or rejected, resulting in a spec timeout if that never happens. If you - * expect that the promise will already be resolved or rejected at the time - * the matcher is called, you can use the {@link async-matchers#already} - * modifier to get a faster failure with a more helpful message. - * - * Note: Specs must await the result of each async matcher, return the - * promise returned by the matcher, or return a promise that's derived from - * the one returned by the matcher. Otherwise the matcher will not be - * evaluated before the spec completes. - * - * @example - * // Good - * await expectAsync(aPromise).toBeResolved(); - * @example - * // Good - * return expectAsync(aPromise).toBeResolved(); - * @example - * // Good - * return expectAsync(aPromise).toBeResolved() - * .then(function() { - * // more spec code - * }); - * @example - * // Bad - * expectAsync(aPromise).toBeResolved(); - * @namespace async-matchers - */ - function AsyncExpectation(options) { - this.expector = new j$.Expector(options); - - const customAsyncMatchers = options.customAsyncMatchers || {}; - for (const matcherName in customAsyncMatchers) { - this[matcherName] = wrapAsyncCompare( - matcherName, - customAsyncMatchers[matcherName] - ); - } - } - - /** - * Add some context for an {@link expectAsync} - * @function - * @name async-matchers#withContext - * @since 3.3.0 - * @param {String} message - Additional context to show when the async matcher fails - * @return {async-matchers} - */ - AsyncExpectation.prototype.withContext = function withContext(message) { - return addFilter(this, new ContextAddingFilter(message)); - }; - - /** - * Invert the matcher following this {@link expectAsync} - * @member - * @name async-matchers#not - * @type {async-matchers} - * @example - * await expectAsync(myPromise).not.toBeResolved(); - * @example - * return expectAsync(myPromise).not.toBeResolved(); - */ - Object.defineProperty(AsyncExpectation.prototype, 'not', { - get: function() { - return addFilter(this, asyncNegatingFilter); - } - }); - - /** - * Fail as soon as possible if the actual is pending. - * Otherwise evaluate the matcher. - * @member - * @name async-matchers#already - * @since 3.8.0 - * @type {async-matchers} - * @example - * await expectAsync(myPromise).already.toBeResolved(); - * @example - * return expectAsync(myPromise).already.toBeResolved(); - */ - Object.defineProperty(AsyncExpectation.prototype, 'already', { - get: function() { - return addFilter(this, expectSettledPromiseFilter); - } - }); - - function wrapSyncCompare(name, matcherFactory) { - return function() { - const result = this.expector.compare(name, matcherFactory, arguments); - this.expector.processResult(result); - }; - } - - function wrapAsyncCompare(name, matcherFactory) { - return function() { - // Capture the call stack here, before we go async, so that it will contain - // frames that are relevant to the user instead of just parts of Jasmine. - const errorForStack = j$.util.errorWithStack(); - - return this.expector - .compare(name, matcherFactory, arguments) - .then(result => { - this.expector.processResult(result, errorForStack); - }); - }; - } - - function addCoreMatchers(prototype, matchers, wrapper) { - for (const matcherName in matchers) { - const matcher = matchers[matcherName]; - prototype[matcherName] = wrapper(matcherName, matcher); - } - } - - function addFilter(source, filter) { - const result = Object.create(source); - result.expector = source.expector.addFilter(filter); - return result; - } - - function negatedFailureMessage(result, matcherName, args, matchersUtil) { - if (result.message) { - if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } + const customMatchers = options.customMatchers || {} + for (const matcherName in customMatchers) { + this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]) + } } - args = args.slice(); - args.unshift(true); - args.unshift(matcherName); - return matchersUtil.buildFailureMessage.apply(matchersUtil, args); - } - - function negate(result) { - result.pass = !result.pass; - return result; - } - - const syncNegatingFilter = { - selectComparisonFunc: function(matcher) { - function defaultNegativeCompare() { - return negate(matcher.compare.apply(null, arguments)); - } - - return matcher.negativeCompare || defaultNegativeCompare; - }, - buildFailureMessage: negatedFailureMessage - }; - - const asyncNegatingFilter = { - selectComparisonFunc: function(matcher) { - function defaultNegativeCompare() { - return matcher.compare.apply(this, arguments).then(negate); - } - - return matcher.negativeCompare || defaultNegativeCompare; - }, - buildFailureMessage: negatedFailureMessage - }; - - const expectSettledPromiseFilter = { - selectComparisonFunc: function(matcher) { - return function(actual) { - const matcherArgs = arguments; - - return j$.isPending_(actual).then(function(isPending) { - if (isPending) { - return { - pass: false, - message: - 'Expected a promise to be settled (via ' + - 'expectAsync(...).already) but it was pending.' - }; - } else { - return matcher.compare.apply(null, matcherArgs); - } - }); - }; + /** + * Add some context for an {@link expect} + * @function + * @name matchers#withContext + * @since 3.3.0 + * @param {String} message - Additional context to show when the matcher fails + * @return {matchers} + */ + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)) } - }; - function ContextAddingFilter(message) { - this.message = message; - } + /** + * Invert the matcher following this {@link expect} + * @member + * @name matchers#not + * @since 1.3.0 + * @type {matchers} + * @example + * expect(something).not.toBe(true); + */ + Object.defineProperty(Expectation.prototype, "not", { + get: function() { + return addFilter(this, syncNegatingFilter) + }, + }) - ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { - if (msg.indexOf('\n') === -1) { - return this.message + ': ' + msg; - } else { - return this.message + ':\n' + indent(msg); + /** + * Asynchronous matchers that operate on an actual value which is a promise, + * and return a promise. + * + * Most async matchers will wait indefinitely for the promise to be resolved + * or rejected, resulting in a spec timeout if that never happens. If you + * expect that the promise will already be resolved or rejected at the time + * the matcher is called, you can use the {@link async-matchers#already} + * modifier to get a faster failure with a more helpful message. + * + * Note: Specs must await the result of each async matcher, return the + * promise returned by the matcher, or return a promise that's derived from + * the one returned by the matcher. Otherwise the matcher will not be + * evaluated before the spec completes. + * + * @example + * // Good + * await expectAsync(aPromise).toBeResolved(); + * @example + * // Good + * return expectAsync(aPromise).toBeResolved(); + * @example + * // Good + * return expectAsync(aPromise).toBeResolved() + * .then(function() { + * // more spec code + * }); + * @example + * // Bad + * expectAsync(aPromise).toBeResolved(); + * @namespace async-matchers + */ + function AsyncExpectation(options) { + this.expector = new j$.Expector(options) + + const customAsyncMatchers = options.customAsyncMatchers || {} + for (const matcherName in customAsyncMatchers) { + this[matcherName] = wrapAsyncCompare(matcherName, customAsyncMatchers[matcherName]) + } } - }; - function indent(s) { - return s.replace(/^/gm, ' '); - } - - return { - factory: function(options) { - return new Expectation(options || {}); - }, - addCoreMatchers: function(matchers) { - addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare); - }, - asyncFactory: function(options) { - return new AsyncExpectation(options || {}); - }, - addAsyncCoreMatchers: function(matchers) { - addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare); + /** + * Add some context for an {@link expectAsync} + * @function + * @name async-matchers#withContext + * @since 3.3.0 + * @param {String} message - Additional context to show when the async matcher fails + * @return {async-matchers} + */ + AsyncExpectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)) } - }; -}; + + /** + * Invert the matcher following this {@link expectAsync} + * @member + * @name async-matchers#not + * @type {async-matchers} + * @example + * await expectAsync(myPromise).not.toBeResolved(); + * @example + * return expectAsync(myPromise).not.toBeResolved(); + */ + Object.defineProperty(AsyncExpectation.prototype, "not", { + get: function() { + return addFilter(this, asyncNegatingFilter) + }, + }) + + /** + * Fail as soon as possible if the actual is pending. + * Otherwise evaluate the matcher. + * @member + * @name async-matchers#already + * @since 3.8.0 + * @type {async-matchers} + * @example + * await expectAsync(myPromise).already.toBeResolved(); + * @example + * return expectAsync(myPromise).already.toBeResolved(); + */ + Object.defineProperty(AsyncExpectation.prototype, "already", { + get: function() { + return addFilter(this, expectSettledPromiseFilter) + }, + }) + + function wrapSyncCompare(name, matcherFactory) { + return function() { + const result = this.expector.compare(name, matcherFactory, arguments) + this.expector.processResult(result) + } + } + + function wrapAsyncCompare(name, matcherFactory) { + return function() { + // Capture the call stack here, before we go async, so that it will contain + // frames that are relevant to the user instead of just parts of Jasmine. + const errorForStack = j$.util.errorWithStack() + + return this.expector.compare(name, matcherFactory, arguments).then((result) => { + this.expector.processResult(result, errorForStack) + }) + } + } + + function addCoreMatchers(prototype, matchers, wrapper) { + for (const matcherName in matchers) { + const matcher = matchers[matcherName] + prototype[matcherName] = wrapper(matcherName, matcher) + } + } + + function addFilter(source, filter) { + const result = Object.create(source) + result.expector = source.expector.addFilter(filter) + return result + } + + function negatedFailureMessage(result, matcherName, args, matchersUtil) { + if (result.message) { + if (j$.isFunction_(result.message)) { + return result.message() + } else { + return result.message + } + } + + args = args.slice() + args.unshift(true) + args.unshift(matcherName) + return matchersUtil.buildFailureMessage.apply(matchersUtil, args) + } + + function negate(result) { + result.pass = !result.pass + return result + } + + const syncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return negate(matcher.compare.apply(null, arguments)) + } + + return matcher.negativeCompare || defaultNegativeCompare + }, + buildFailureMessage: negatedFailureMessage, + } + + const asyncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return matcher.compare.apply(this, arguments).then(negate) + } + + return matcher.negativeCompare || defaultNegativeCompare + }, + buildFailureMessage: negatedFailureMessage, + } + + const expectSettledPromiseFilter = { + selectComparisonFunc: function(matcher) { + return function(actual) { + const matcherArgs = arguments + + return j$.isPending_(actual).then(function(isPending) { + if (isPending) { + return { + pass: false, + message: + "Expected a promise to be settled (via " + + "expectAsync(...).already) but it was pending.", + } + } else { + return matcher.compare.apply(null, matcherArgs) + } + }) + } + }, + } + + function ContextAddingFilter(message) { + this.message = message + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + if (msg.indexOf("\n") === -1) { + return this.message + ": " + msg + } else { + return this.message + ":\n" + indent(msg) + } + } + + function indent(s) { + return s.replace(/^/gm, " ") + } + + return { + factory: function(options) { + return new Expectation(options || {}) + }, + addCoreMatchers: function(matchers) { + addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare) + }, + asyncFactory: function(options) { + return new AsyncExpectation(options || {}) + }, + addAsyncCoreMatchers: function(matchers) { + addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare) + }, + } +} getJasmineRequireObj().ExpectationFilterChain = function() { - function ExpectationFilterChain(maybeFilter, prev) { - this.filter_ = maybeFilter; - this.prev_ = prev; - } - - ExpectationFilterChain.prototype.addFilter = function(filter) { - return new ExpectationFilterChain(filter, this); - }; - - ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { - return this.callFirst_('selectComparisonFunc', arguments).result; - }; - - ExpectationFilterChain.prototype.buildFailureMessage = function( - result, - matcherName, - args, - matchersUtil - ) { - return this.callFirst_('buildFailureMessage', arguments).result; - }; - - ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { - const result = this.callFirst_('modifyFailureMessage', arguments).result; - return result || msg; - }; - - ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { - if (this.prev_) { - const prevResult = this.prev_.callFirst_(fname, args); - - if (prevResult.found) { - return prevResult; - } + function ExpectationFilterChain(maybeFilter, prev) { + this.filter_ = maybeFilter + this.prev_ = prev } - if (this.filter_ && this.filter_[fname]) { - return { - found: true, - result: this.filter_[fname].apply(this.filter_, args) - }; + ExpectationFilterChain.prototype.addFilter = function(filter) { + return new ExpectationFilterChain(filter, this) } - return { found: false }; - }; + ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { + return this.callFirst_("selectComparisonFunc", arguments).result + } - return ExpectationFilterChain; -}; + ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, matchersUtil) { + return this.callFirst_("buildFailureMessage", arguments).result + } + + ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { + const result = this.callFirst_("modifyFailureMessage", arguments).result + return result || msg + } + + ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { + if (this.prev_) { + const prevResult = this.prev_.callFirst_(fname, args) + + if (prevResult.found) { + return prevResult + } + } + + if (this.filter_ && this.filter_[fname]) { + return { + found: true, + result: this.filter_[fname].apply(this.filter_, args), + } + } + + return { found: false } + } + + return ExpectationFilterChain +} getJasmineRequireObj().Expector = function(j$) { - function Expector(options) { - this.matchersUtil = options.matchersUtil || { - buildFailureMessage: function() {} - }; - this.actual = options.actual; - this.addExpectationResult = options.addExpectationResult || function() {}; - this.filters = new j$.ExpectationFilterChain(); - } - - Expector.prototype.instantiateMatcher = function( - matcherName, - matcherFactory, - args - ) { - this.matcherName = matcherName; - this.args = Array.prototype.slice.call(args, 0); - this.expected = this.args.slice(0); - - this.args.unshift(this.actual); - - const matcher = matcherFactory(this.matchersUtil); - - const comparisonFunc = this.filters.selectComparisonFunc(matcher); - return comparisonFunc || matcher.compare; - }; - - Expector.prototype.buildMessage = function(result) { - if (result.pass) { - return ''; + function Expector(options) { + this.matchersUtil = options.matchersUtil || { + buildFailureMessage: function() {}, + } + this.actual = options.actual + this.addExpectationResult = options.addExpectationResult || function() {} + this.filters = new j$.ExpectationFilterChain() } - const defaultMessage = () => { - if (!result.message) { - const args = this.args.slice(); - args.unshift(false); - args.unshift(this.matcherName); - return this.matchersUtil.buildFailureMessage.apply( - this.matchersUtil, - args - ); - } else if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } - }; + Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { + this.matcherName = matcherName + this.args = Array.prototype.slice.call(args, 0) + this.expected = this.args.slice(0) - const msg = this.filters.buildFailureMessage( - result, - this.matcherName, - this.args, - this.matchersUtil, - defaultMessage - ); - return this.filters.modifyFailureMessage(msg || defaultMessage()); - }; + this.args.unshift(this.actual) - Expector.prototype.compare = function(matcherName, matcherFactory, args) { - const matcherCompare = this.instantiateMatcher( - matcherName, - matcherFactory, - args - ); - return matcherCompare.apply(null, this.args); - }; + const matcher = matcherFactory(this.matchersUtil) - Expector.prototype.addFilter = function(filter) { - const result = Object.create(this); - result.filters = this.filters.addFilter(filter); - return result; - }; - - Expector.prototype.processResult = function(result, errorForStack) { - const message = this.buildMessage(result); - - if (this.expected.length === 1) { - this.expected = this.expected[0]; + const comparisonFunc = this.filters.selectComparisonFunc(matcher) + return comparisonFunc || matcher.compare } - this.addExpectationResult(result.pass, { - matcherName: this.matcherName, - passed: result.pass, - message: message, - error: errorForStack ? undefined : result.error, - errorForStack: errorForStack || undefined, - actual: this.actual, - expected: this.expected // TODO: this may need to be arrayified/sliced - }); - }; + Expector.prototype.buildMessage = function(result) { + if (result.pass) { + return "" + } - return Expector; -}; + const defaultMessage = () => { + if (!result.message) { + const args = this.args.slice() + args.unshift(false) + args.unshift(this.matcherName) + return this.matchersUtil.buildFailureMessage.apply(this.matchersUtil, args) + } else if (j$.isFunction_(result.message)) { + return result.message() + } else { + return result.message + } + } + + const msg = this.filters.buildFailureMessage( + result, + this.matcherName, + this.args, + this.matchersUtil, + defaultMessage + ) + return this.filters.modifyFailureMessage(msg || defaultMessage()) + } + + Expector.prototype.compare = function(matcherName, matcherFactory, args) { + const matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args) + return matcherCompare.apply(null, this.args) + } + + Expector.prototype.addFilter = function(filter) { + const result = Object.create(this) + result.filters = this.filters.addFilter(filter) + return result + } + + Expector.prototype.processResult = function(result, errorForStack) { + const message = this.buildMessage(result) + + if (this.expected.length === 1) { + this.expected = this.expected[0] + } + + this.addExpectationResult(result.pass, { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected, // TODO: this may need to be arrayified/sliced + }) + } + + return Expector +} getJasmineRequireObj().formatErrorMsg = function() { - function generateErrorMsg(domain, usage) { - const usageDefinition = usage ? '\nUsage: ' + usage : ''; + function generateErrorMsg(domain, usage) { + const usageDefinition = usage ? "\nUsage: " + usage : "" - return function errorMsg(msg) { - return domain + ' : ' + msg + usageDefinition; - }; - } + return function errorMsg(msg) { + return domain + " : " + msg + usageDefinition + } + } - return generateErrorMsg; -}; + return generateErrorMsg +} getJasmineRequireObj().GlobalErrors = function(j$) { - function GlobalErrors(global) { - global = global || j$.getGlobal(); + function GlobalErrors(global) { + global = global || j$.getGlobal() - const handlers = []; - let overrideHandler = null, - onRemoveOverrideHandler = null; + const handlers = [] + let overrideHandler = null, + onRemoveOverrideHandler = null - function onerror(message, source, lineno, colno, error) { - if (overrideHandler) { - overrideHandler(error || message); - return; - } + function onerror(message, source, lineno, colno, error) { + if (overrideHandler) { + overrideHandler(error || message) + return + } - const handler = handlers[handlers.length - 1]; + const handler = handlers[handlers.length - 1] - if (handler) { - handler.apply(null, Array.prototype.slice.call(arguments, 0)); - } else { - throw arguments[0]; - } + if (handler) { + handler.apply(null, Array.prototype.slice.call(arguments, 0)) + } else { + throw arguments[0] + } + } + + this.originalHandlers = {} + this.jasmineHandlers = {} + this.installOne_ = function installOne_(errorType, jasmineMessage) { + function taggedOnError(error) { + if (j$.isError_(error)) { + error.jasmineMessage = jasmineMessage + ": " + error + } else { + let substituteMsg + + if (error) { + substituteMsg = jasmineMessage + ": " + error + } else { + substituteMsg = jasmineMessage + " with no error or message" + } + + if (errorType === "unhandledRejection") { + substituteMsg += + "\n" + + "(Tip: to get a useful stack trace, use " + + "Promise.reject(new Error(...)) instead of Promise.reject(" + + (error ? "..." : "") + + ").)" + } + + error = new Error(substituteMsg) + } + + const handler = handlers[handlers.length - 1] + + if (overrideHandler) { + overrideHandler(error) + return + } + + if (handler) { + handler(error) + } else { + throw error + } + } + + this.originalHandlers[errorType] = global.process.listeners(errorType) + this.jasmineHandlers[errorType] = taggedOnError + + global.process.removeAllListeners(errorType) + global.process.on(errorType, taggedOnError) + + this.uninstall = function uninstall() { + const errorTypes = Object.keys(this.originalHandlers) + for (const errorType of errorTypes) { + global.process.removeListener(errorType, this.jasmineHandlers[errorType]) + + for (let i = 0; i < this.originalHandlers[errorType].length; i++) { + global.process.on(errorType, this.originalHandlers[errorType][i]) + } + delete this.originalHandlers[errorType] + delete this.jasmineHandlers[errorType] + } + } + } + + this.install = function install() { + if (global.process && global.process.listeners && j$.isFunction_(global.process.on)) { + this.installOne_("uncaughtException", "Uncaught exception") + this.installOne_("unhandledRejection", "Unhandled promise rejection") + } else { + const originalHandler = global.onerror + global.onerror = onerror + + const browserRejectionHandler = function browserRejectionHandler(event) { + if (j$.isError_(event.reason)) { + event.reason.jasmineMessage = "Unhandled promise rejection: " + event.reason + global.onerror(event.reason) + } else { + global.onerror("Unhandled promise rejection: " + event.reason) + } + } + + global.addEventListener("unhandledrejection", browserRejectionHandler) + + this.uninstall = function uninstall() { + global.onerror = originalHandler + global.removeEventListener("unhandledrejection", browserRejectionHandler) + } + } + } + + this.pushListener = function pushListener(listener) { + handlers.push(listener) + } + + this.popListener = function popListener(listener) { + if (!listener) { + throw new Error("popListener expects a listener") + } + + handlers.pop() + } + + this.setOverrideListener = function(listener, onRemove) { + if (overrideHandler) { + throw new Error("Can't set more than one override listener at a time") + } + + overrideHandler = listener + onRemoveOverrideHandler = onRemove + } + + this.removeOverrideListener = function() { + if (onRemoveOverrideHandler) { + onRemoveOverrideHandler() + } + + overrideHandler = null + onRemoveOverrideHandler = null + } } - this.originalHandlers = {}; - this.jasmineHandlers = {}; - this.installOne_ = function installOne_(errorType, jasmineMessage) { - function taggedOnError(error) { - if (j$.isError_(error)) { - error.jasmineMessage = jasmineMessage + ': ' + error; - } else { - let substituteMsg; - - if (error) { - substituteMsg = jasmineMessage + ': ' + error; - } else { - substituteMsg = jasmineMessage + ' with no error or message'; - } - - if (errorType === 'unhandledRejection') { - substituteMsg += - '\n' + - '(Tip: to get a useful stack trace, use ' + - 'Promise.reject(new Error(...)) instead of Promise.reject(' + - (error ? '...' : '') + - ').)'; - } - - error = new Error(substituteMsg); - } - - const handler = handlers[handlers.length - 1]; - - if (overrideHandler) { - overrideHandler(error); - return; - } - - if (handler) { - handler(error); - } else { - throw error; - } - } - - this.originalHandlers[errorType] = global.process.listeners(errorType); - this.jasmineHandlers[errorType] = taggedOnError; - - global.process.removeAllListeners(errorType); - global.process.on(errorType, taggedOnError); - - this.uninstall = function uninstall() { - const errorTypes = Object.keys(this.originalHandlers); - for (const errorType of errorTypes) { - global.process.removeListener( - errorType, - this.jasmineHandlers[errorType] - ); - - for (let i = 0; i < this.originalHandlers[errorType].length; i++) { - global.process.on(errorType, this.originalHandlers[errorType][i]); - } - delete this.originalHandlers[errorType]; - delete this.jasmineHandlers[errorType]; - } - }; - }; - - this.install = function install() { - if ( - global.process && - global.process.listeners && - j$.isFunction_(global.process.on) - ) { - this.installOne_('uncaughtException', 'Uncaught exception'); - this.installOne_('unhandledRejection', 'Unhandled promise rejection'); - } else { - const originalHandler = global.onerror; - global.onerror = onerror; - - const browserRejectionHandler = function browserRejectionHandler( - event - ) { - if (j$.isError_(event.reason)) { - event.reason.jasmineMessage = - 'Unhandled promise rejection: ' + event.reason; - global.onerror(event.reason); - } else { - global.onerror('Unhandled promise rejection: ' + event.reason); - } - }; - - global.addEventListener('unhandledrejection', browserRejectionHandler); - - this.uninstall = function uninstall() { - global.onerror = originalHandler; - global.removeEventListener( - 'unhandledrejection', - browserRejectionHandler - ); - }; - } - }; - - this.pushListener = function pushListener(listener) { - handlers.push(listener); - }; - - this.popListener = function popListener(listener) { - if (!listener) { - throw new Error('popListener expects a listener'); - } - - handlers.pop(); - }; - - this.setOverrideListener = function(listener, onRemove) { - if (overrideHandler) { - throw new Error("Can't set more than one override listener at a time"); - } - - overrideHandler = listener; - onRemoveOverrideHandler = onRemove; - }; - - this.removeOverrideListener = function() { - if (onRemoveOverrideHandler) { - onRemoveOverrideHandler(); - } - - overrideHandler = null; - onRemoveOverrideHandler = null; - }; - } - - return GlobalErrors; -}; + return GlobalErrors +} getJasmineRequireObj().toBePending = function(j$) { - /** - * Expect a promise to be pending, i.e. the promise is neither resolved nor rejected. - * @function - * @async - * @name async-matchers#toBePending - * @since 3.6 - * @example - * await expectAsync(aPromise).toBePending(); - */ - return function toBePending() { - return { - compare: function(actual) { - if (!j$.isPromiseLike(actual)) { - throw new Error('Expected toBePending to be called on a promise.'); + /** + * Expect a promise to be pending, i.e. the promise is neither resolved nor rejected. + * @function + * @async + * @name async-matchers#toBePending + * @since 3.6 + * @example + * await expectAsync(aPromise).toBePending(); + */ + return function toBePending() { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error("Expected toBePending to be called on a promise.") + } + const want = {} + return Promise.race([actual, Promise.resolve(want)]).then( + function(got) { + return { pass: want === got } + }, + function() { + return { pass: false } + } + ) + }, } - const want = {}; - return Promise.race([actual, Promise.resolve(want)]).then( - function(got) { - return { pass: want === got }; - }, - function() { - return { pass: false }; - } - ); - } - }; - }; -}; + } +} getJasmineRequireObj().toBeRejected = function(j$) { - /** - * Expect a promise to be rejected. - * @function - * @async - * @name async-matchers#toBeRejected - * @since 3.1.0 - * @example - * await expectAsync(aPromise).toBeRejected(); - * @example - * return expectAsync(aPromise).toBeRejected(); - */ - return function toBeRejected() { - return { - compare: function(actual) { - if (!j$.isPromiseLike(actual)) { - throw new Error('Expected toBeRejected to be called on a promise.'); + /** + * Expect a promise to be rejected. + * @function + * @async + * @name async-matchers#toBeRejected + * @since 3.1.0 + * @example + * await expectAsync(aPromise).toBeRejected(); + * @example + * return expectAsync(aPromise).toBeRejected(); + */ + return function toBeRejected() { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error("Expected toBeRejected to be called on a promise.") + } + return actual.then( + function() { + return { pass: false } + }, + function() { + return { pass: true } + } + ) + }, } - return actual.then( - function() { - return { pass: false }; - }, - function() { - return { pass: true }; - } - ); - } - }; - }; -}; + } +} getJasmineRequireObj().toBeRejectedWith = function(j$) { - /** - * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeRejectedWith - * @since 3.3.0 - * @param {Object} expected - Value that the promise is expected to be rejected with - * @example - * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - */ - return function toBeRejectedWith(matchersUtil) { - return { - compare: function(actualPromise, expectedValue) { - if (!j$.isPromiseLike(actualPromise)) { - throw new Error( - 'Expected toBeRejectedWith to be called on a promise.' - ); - } + /** + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeRejectedWith + * @since 3.3.0 + * @param {Object} expected - Value that the promise is expected to be rejected with + * @example + * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + */ + return function toBeRejectedWith(matchersUtil) { + return { + compare: function(actualPromise, expectedValue) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error("Expected toBeRejectedWith to be called on a promise.") + } - function prefix(passed) { - return ( - 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be rejected with ' + - matchersUtil.pp(expectedValue) - ); - } + function prefix(passed) { + return ( + "Expected a promise " + + (passed ? "not " : "") + + "to be rejected with " + + matchersUtil.pp(expectedValue) + ) + } - return actualPromise.then( - function() { - return { - pass: false, - message: prefix(false) + ' but it was resolved.' - }; - }, - function(actualValue) { - if (matchersUtil.equals(actualValue, expectedValue)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: - prefix(false) + - ' but it was rejected with ' + - matchersUtil.pp(actualValue) + - '.' - }; - } - } - ); - } - }; - }; -}; + return actualPromise.then( + function() { + return { + pass: false, + message: prefix(false) + " but it was resolved.", + } + }, + function(actualValue) { + if (matchersUtil.equals(actualValue, expectedValue)) { + return { + pass: true, + message: prefix(true) + ".", + } + } else { + return { + pass: false, + message: + prefix(false) + " but it was rejected with " + matchersUtil.pp(actualValue) + ".", + } + } + } + ) + }, + } + } +} getJasmineRequireObj().toBeRejectedWithError = function(j$) { - /** - * Expect a promise to be rejected with a value matched to the expected - * @function - * @async - * @name async-matchers#toBeRejectedWithError - * @since 3.5.0 - * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. - * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` - * @example - * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, 'Error message'); - * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, /Error message/); - * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError); - * await expectAsync(aPromise).toBeRejectedWithError('Error message'); - * return expectAsync(aPromise).toBeRejectedWithError(/Error message/); - */ - return function toBeRejectedWithError(matchersUtil) { - return { - compare: function(actualPromise, arg1, arg2) { - if (!j$.isPromiseLike(actualPromise)) { - throw new Error( - 'Expected toBeRejectedWithError to be called on a promise.' - ); + /** + * Expect a promise to be rejected with a value matched to the expected + * @function + * @async + * @name async-matchers#toBeRejectedWithError + * @since 3.5.0 + * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. + * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` + * @example + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, 'Error message'); + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, /Error message/); + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError); + * await expectAsync(aPromise).toBeRejectedWithError('Error message'); + * return expectAsync(aPromise).toBeRejectedWithError(/Error message/); + */ + return function toBeRejectedWithError(matchersUtil) { + return { + compare: function(actualPromise, arg1, arg2) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error("Expected toBeRejectedWithError to be called on a promise.") + } + + const expected = getExpectedFromArgs(arg1, arg2, matchersUtil) + + return actualPromise.then( + function() { + return { + pass: false, + message: "Expected a promise to be rejected but it was resolved.", + } + }, + function(actualValue) { + return matchError(actualValue, expected, matchersUtil) + } + ) + }, + } + } + + function matchError(actual, expected, matchersUtil) { + if (!j$.isError_(actual)) { + return fail(expected, "rejected with " + matchersUtil.pp(actual)) } - const expected = getExpectedFromArgs(arg1, arg2, matchersUtil); + if (!(actual instanceof expected.error)) { + return fail(expected, "rejected with type " + j$.fnNameFor(actual.constructor)) + } - return actualPromise.then( - function() { - return { - pass: false, - message: 'Expected a promise to be rejected but it was resolved.' - }; - }, - function(actualValue) { - return matchError(actualValue, expected, matchersUtil); - } - ); - } - }; - }; + const actualMessage = actual.message - function matchError(actual, expected, matchersUtil) { - if (!j$.isError_(actual)) { - return fail(expected, 'rejected with ' + matchersUtil.pp(actual)); + if (actualMessage === expected.message || typeof expected.message === "undefined") { + return pass(expected) + } + + if (expected.message instanceof RegExp && expected.message.test(actualMessage)) { + return pass(expected) + } + + return fail(expected, "rejected with " + matchersUtil.pp(actual)) } - if (!(actual instanceof expected.error)) { - return fail( - expected, - 'rejected with type ' + j$.fnNameFor(actual.constructor) - ); + function pass(expected) { + return { + pass: true, + message: "Expected a promise not to be rejected with " + expected.printValue + ", but it was.", + } } - const actualMessage = actual.message; - - if ( - actualMessage === expected.message || - typeof expected.message === 'undefined' - ) { - return pass(expected); + function fail(expected, message) { + return { + pass: false, + message: "Expected a promise to be rejected with " + expected.printValue + " but it was " + message + ".", + } } - if ( - expected.message instanceof RegExp && - expected.message.test(actualMessage) - ) { - return pass(expected); + function getExpectedFromArgs(arg1, arg2, matchersUtil) { + let error, message + + if (isErrorConstructor(arg1)) { + error = arg1 + message = arg2 + } else { + error = Error + message = arg1 + } + + return { + error: error, + message: message, + printValue: j$.fnNameFor(error) + (typeof message === "undefined" ? "" : ": " + matchersUtil.pp(message)), + } } - return fail(expected, 'rejected with ' + matchersUtil.pp(actual)); - } - - function pass(expected) { - return { - pass: true, - message: - 'Expected a promise not to be rejected with ' + - expected.printValue + - ', but it was.' - }; - } - - function fail(expected, message) { - return { - pass: false, - message: - 'Expected a promise to be rejected with ' + - expected.printValue + - ' but it was ' + - message + - '.' - }; - } - - function getExpectedFromArgs(arg1, arg2, matchersUtil) { - let error, message; - - if (isErrorConstructor(arg1)) { - error = arg1; - message = arg2; - } else { - error = Error; - message = arg1; + function isErrorConstructor(value) { + return typeof value === "function" && (value === Error || j$.isError_(value.prototype)) } - - return { - error: error, - message: message, - printValue: - j$.fnNameFor(error) + - (typeof message === 'undefined' ? '' : ': ' + matchersUtil.pp(message)) - }; - } - - function isErrorConstructor(value) { - return ( - typeof value === 'function' && - (value === Error || j$.isError_(value.prototype)) - ); - } -}; +} getJasmineRequireObj().toBeResolved = function(j$) { - /** - * Expect a promise to be resolved. - * @function - * @async - * @name async-matchers#toBeResolved - * @since 3.1.0 - * @example - * await expectAsync(aPromise).toBeResolved(); - * @example - * return expectAsync(aPromise).toBeResolved(); - */ - return function toBeResolved(matchersUtil) { - return { - compare: function(actual) { - if (!j$.isPromiseLike(actual)) { - throw new Error('Expected toBeResolved to be called on a promise.'); - } + /** + * Expect a promise to be resolved. + * @function + * @async + * @name async-matchers#toBeResolved + * @since 3.1.0 + * @example + * await expectAsync(aPromise).toBeResolved(); + * @example + * return expectAsync(aPromise).toBeResolved(); + */ + return function toBeResolved(matchersUtil) { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error("Expected toBeResolved to be called on a promise.") + } - return actual.then( - function() { - return { pass: true }; - }, - function(e) { - return { - pass: false, - message: - 'Expected a promise to be resolved but it was ' + - 'rejected with ' + - matchersUtil.pp(e) + - '.' - }; - } - ); - } - }; - }; -}; + return actual.then( + function() { + return { pass: true } + }, + function(e) { + return { + pass: false, + message: + "Expected a promise to be resolved but it was " + + "rejected with " + + matchersUtil.pp(e) + + ".", + } + } + ) + }, + } + } +} getJasmineRequireObj().toBeResolvedTo = function(j$) { - /** - * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeResolvedTo - * @since 3.1.0 - * @param {Object} expected - Value that the promise is expected to resolve to - * @example - * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - */ - return function toBeResolvedTo(matchersUtil) { - return { - compare: function(actualPromise, expectedValue) { - if (!j$.isPromiseLike(actualPromise)) { - throw new Error('Expected toBeResolvedTo to be called on a promise.'); - } + /** + * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeResolvedTo + * @since 3.1.0 + * @param {Object} expected - Value that the promise is expected to resolve to + * @example + * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + */ + return function toBeResolvedTo(matchersUtil) { + return { + compare: function(actualPromise, expectedValue) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error("Expected toBeResolvedTo to be called on a promise.") + } - function prefix(passed) { - return ( - 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be resolved to ' + - matchersUtil.pp(expectedValue) - ); - } + function prefix(passed) { + return ( + "Expected a promise " + + (passed ? "not " : "") + + "to be resolved to " + + matchersUtil.pp(expectedValue) + ) + } - return actualPromise.then( - function(actualValue) { - if (matchersUtil.equals(actualValue, expectedValue)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: - prefix(false) + - ' but it was resolved to ' + - matchersUtil.pp(actualValue) + - '.' - }; - } - }, - function(e) { - return { - pass: false, - message: - prefix(false) + - ' but it was rejected with ' + - matchersUtil.pp(e) + - '.' - }; - } - ); - } - }; - }; -}; + return actualPromise.then( + function(actualValue) { + if (matchersUtil.equals(actualValue, expectedValue)) { + return { + pass: true, + message: prefix(true) + ".", + } + } else { + return { + pass: false, + message: + prefix(false) + " but it was resolved to " + matchersUtil.pp(actualValue) + ".", + } + } + }, + function(e) { + return { + pass: false, + message: prefix(false) + " but it was rejected with " + matchersUtil.pp(e) + ".", + } + } + ) + }, + } + } +} getJasmineRequireObj().DiffBuilder = function(j$) { - class DiffBuilder { - constructor(config) { - this.prettyPrinter_ = - (config || {}).prettyPrinter || j$.makePrettyPrinter(); - this.mismatches_ = new j$.MismatchTree(); - this.path_ = new j$.ObjectPath(); - this.actualRoot_ = undefined; - this.expectedRoot_ = undefined; - } - - setRoots(actual, expected) { - this.actualRoot_ = actual; - this.expectedRoot_ = expected; - } - - recordMismatch(formatter) { - this.mismatches_.add(this.path_, formatter); - } - - getMessage() { - const messages = []; - - this.mismatches_.traverse((path, isLeaf, formatter) => { - const { actual, expected } = this.dereferencePath_(path); - - if (formatter) { - messages.push(formatter(actual, expected, path, this.prettyPrinter_)); - return true; + class DiffBuilder { + constructor(config) { + this.prettyPrinter_ = (config || {}).prettyPrinter || j$.makePrettyPrinter() + this.mismatches_ = new j$.MismatchTree() + this.path_ = new j$.ObjectPath() + this.actualRoot_ = undefined + this.expectedRoot_ = undefined } - const actualCustom = this.prettyPrinter_.customFormat_(actual); - const expectedCustom = this.prettyPrinter_.customFormat_(expected); - const useCustom = !( - j$.util.isUndefined(actualCustom) && - j$.util.isUndefined(expectedCustom) - ); - - if (useCustom) { - messages.push(wrapPrettyPrinted(actualCustom, expectedCustom, path)); - return false; // don't recurse further + setRoots(actual, expected) { + this.actualRoot_ = actual + this.expectedRoot_ = expected } - if (isLeaf) { - messages.push(this.defaultFormatter_(actual, expected, path)); + recordMismatch(formatter) { + this.mismatches_.add(this.path_, formatter) } - return true; - }); + getMessage() { + const messages = [] - return messages.join('\n'); - } + this.mismatches_.traverse((path, isLeaf, formatter) => { + const { actual, expected } = this.dereferencePath_(path) - withPath(pathComponent, block) { - const oldPath = this.path_; - this.path_ = this.path_.add(pathComponent); - block(); - this.path_ = oldPath; - } + if (formatter) { + messages.push(formatter(actual, expected, path, this.prettyPrinter_)) + return true + } - dereferencePath_(objectPath) { - let actual = this.actualRoot_; - let expected = this.expectedRoot_; + const actualCustom = this.prettyPrinter_.customFormat_(actual) + const expectedCustom = this.prettyPrinter_.customFormat_(expected) + const useCustom = !(j$.util.isUndefined(actualCustom) && j$.util.isUndefined(expectedCustom)) - const handleAsymmetricExpected = () => { - if ( - j$.isAsymmetricEqualityTester_(expected) && - j$.isFunction_(expected.valuesForDiff_) - ) { - const asymmetricResult = expected.valuesForDiff_( - actual, - this.prettyPrinter_ - ); - expected = asymmetricResult.self; - actual = asymmetricResult.other; + if (useCustom) { + messages.push(wrapPrettyPrinted(actualCustom, expectedCustom, path)) + return false // don't recurse further + } + + if (isLeaf) { + messages.push(this.defaultFormatter_(actual, expected, path)) + } + + return true + }) + + return messages.join("\n") } - }; - handleAsymmetricExpected(); + withPath(pathComponent, block) { + const oldPath = this.path_ + this.path_ = this.path_.add(pathComponent) + block() + this.path_ = oldPath + } - for (const pc of objectPath.components) { - actual = actual[pc]; - expected = expected[pc]; - handleAsymmetricExpected(); - } + dereferencePath_(objectPath) { + let actual = this.actualRoot_ + let expected = this.expectedRoot_ - return { actual: actual, expected: expected }; + const handleAsymmetricExpected = () => { + if (j$.isAsymmetricEqualityTester_(expected) && j$.isFunction_(expected.valuesForDiff_)) { + const asymmetricResult = expected.valuesForDiff_(actual, this.prettyPrinter_) + expected = asymmetricResult.self + actual = asymmetricResult.other + } + } + + handleAsymmetricExpected() + + for (const pc of objectPath.components) { + actual = actual[pc] + expected = expected[pc] + handleAsymmetricExpected() + } + + return { actual: actual, expected: expected } + } + + defaultFormatter_(actual, expected, path) { + return wrapPrettyPrinted(this.prettyPrinter_(actual), this.prettyPrinter_(expected), path) + } } - defaultFormatter_(actual, expected, path) { - return wrapPrettyPrinted( - this.prettyPrinter_(actual), - this.prettyPrinter_(expected), - path - ); + function wrapPrettyPrinted(actual, expected, path) { + return "Expected " + path + (path.depth() ? " = " : "") + actual + " to equal " + expected + "." } - } - function wrapPrettyPrinted(actual, expected, path) { - return ( - 'Expected ' + - path + - (path.depth() ? ' = ' : '') + - actual + - ' to equal ' + - expected + - '.' - ); - } - - return DiffBuilder; -}; + return DiffBuilder +} getJasmineRequireObj().MatchersUtil = function(j$) { - /** - * @class MatchersUtil - * @classdesc Utilities for use in implementing matchers.
    - * _Note:_ Do not construct this directly. Jasmine will construct one and - * pass it to matchers and asymmetric equality testers. - * @hideconstructor - */ - function MatchersUtil(options) { - options = options || {}; - this.customTesters_ = options.customTesters || []; /** - * Formats a value for use in matcher failure messages and similar contexts, - * taking into account the current set of custom value formatters. - * @function - * @name MatchersUtil#pp - * @since 3.6.0 - * @param {*} value The value to pretty-print - * @return {string} The pretty-printed value + * @class MatchersUtil + * @classdesc Utilities for use in implementing matchers.
    + * _Note:_ Do not construct this directly. Jasmine will construct one and + * pass it to matchers and asymmetric equality testers. + * @hideconstructor */ - this.pp = options.pp || function() {}; - } - - /** - * Determines whether `haystack` contains `needle`, using the same comparison - * logic as {@link MatchersUtil#equals}. - * @function - * @name MatchersUtil#contains - * @since 2.0.0 - * @param {*} haystack The collection to search - * @param {*} needle The value to search for - * @returns {boolean} True if `needle` was found in `haystack` - */ - MatchersUtil.prototype.contains = function(haystack, needle) { - if (!haystack) { - return false; + function MatchersUtil(options) { + options = options || {} + this.customTesters_ = options.customTesters || [] + /** + * Formats a value for use in matcher failure messages and similar contexts, + * taking into account the current set of custom value formatters. + * @function + * @name MatchersUtil#pp + * @since 3.6.0 + * @param {*} value The value to pretty-print + * @return {string} The pretty-printed value + */ + this.pp = options.pp || function() {} } - if (j$.isSet(haystack)) { - // Try .has() first. It should be faster in cases where - // needle === something in haystack. Fall back to .equals() comparison - // if that fails. - if (haystack.has(needle)) { - return true; - } - } - - if (j$.isIterable_(haystack) && !j$.isString_(haystack)) { - // Arrays, Sets, etc. - for (const candidate of haystack) { - if (this.equals(candidate, needle)) { - return true; + /** + * Determines whether `haystack` contains `needle`, using the same comparison + * logic as {@link MatchersUtil#equals}. + * @function + * @name MatchersUtil#contains + * @since 2.0.0 + * @param {*} haystack The collection to search + * @param {*} needle The value to search for + * @returns {boolean} True if `needle` was found in `haystack` + */ + MatchersUtil.prototype.contains = function(haystack, needle) { + if (!haystack) { + return false } - } - return false; - } - - if (haystack.indexOf) { - // Mainly strings - return haystack.indexOf(needle) >= 0; - } - - if (j$.isNumber_(haystack.length)) { - // Objects that are shaped like arrays but aren't iterable - for (let i = 0; i < haystack.length; i++) { - if (this.equals(haystack[i], needle)) { - return true; - } - } - } - - return false; - }; - - MatchersUtil.prototype.buildFailureMessage = function() { - const args = Array.prototype.slice.call(arguments, 0), - matcherName = args[0], - isNot = args[1], - actual = args[2], - expected = args.slice(3), - englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { - return ' ' + s.toLowerCase(); - }); - - let message = - 'Expected ' + - this.pp(actual) + - (isNot ? ' not ' : ' ') + - englishyPredicate; - - if (expected.length > 0) { - for (let i = 0; i < expected.length; i++) { - if (i > 0) { - message += ','; - } - message += ' ' + this.pp(expected[i]); - } - } - - return message + '.'; - }; - - MatchersUtil.prototype.asymmetricDiff_ = function( - a, - b, - aStack, - bStack, - diffBuilder - ) { - if (j$.isFunction_(b.valuesForDiff_)) { - const values = b.valuesForDiff_(a, this.pp); - this.eq_(values.other, values.self, aStack, bStack, diffBuilder); - } else { - diffBuilder.recordMismatch(); - } - }; - - MatchersUtil.prototype.asymmetricMatch_ = function( - a, - b, - aStack, - bStack, - diffBuilder - ) { - const asymmetricA = j$.isAsymmetricEqualityTester_(a); - const asymmetricB = j$.isAsymmetricEqualityTester_(b); - - if (asymmetricA === asymmetricB) { - return undefined; - } - - let result; - - if (asymmetricA) { - result = a.asymmetricMatch(b, this); - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - } - - if (asymmetricB) { - result = b.asymmetricMatch(a, this); - if (!result) { - this.asymmetricDiff_(a, b, aStack, bStack, diffBuilder); - } - return result; - } - }; - - /** - * Determines whether two values are deeply equal to each other. - * @function - * @name MatchersUtil#equals - * @since 2.0.0 - * @param {*} a The first value to compare - * @param {*} b The second value to compare - * @returns {boolean} True if the values are equal - */ - MatchersUtil.prototype.equals = function(a, b, diffBuilder) { - diffBuilder = diffBuilder || j$.NullDiffBuilder(); - diffBuilder.setRoots(a, b); - - return this.eq_(a, b, [], [], diffBuilder); - }; - - // Equality function lovingly adapted from isEqual in - // [Underscore](http://underscorejs.org) - MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { - let result = true; - - const asymmetricResult = this.asymmetricMatch_( - a, - b, - aStack, - bStack, - diffBuilder - ); - if (!j$.util.isUndefined(asymmetricResult)) { - return asymmetricResult; - } - - for (const tester of this.customTesters_) { - const customTesterResult = tester(a, b); - if (!j$.util.isUndefined(customTesterResult)) { - if (!customTesterResult) { - diffBuilder.recordMismatch(); - } - return customTesterResult; - } - } - - if (a instanceof Error && b instanceof Error) { - result = a.message == b.message; - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - } - - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) { - result = a !== 0 || 1 / a == 1 / b; - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - } - // A strict comparison is necessary because `null == undefined`. - if (a === null || b === null) { - result = a === b; - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - } - const className = Object.prototype.toString.call(a); - if (className != Object.prototype.toString.call(b)) { - diffBuilder.recordMismatch(); - return false; - } - switch (className) { - // Strings, numbers, dates, and booleans are compared by value. - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - result = a == String(b); - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for - // other numeric values. - result = - a != +a ? b != +b : a === 0 && b === 0 ? 1 / a == 1 / b : a == +b; - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - result = +a == +b; - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - case '[object ArrayBuffer]': - // If we have an instance of ArrayBuffer the Uint8Array ctor - // will be defined as well - return this.eq_( - new Uint8Array(a), - new Uint8Array(b), - aStack, - bStack, - diffBuilder - ); - // RegExps are compared by their source patterns and flags. - case '[object RegExp]': - return ( - a.source == b.source && - a.global == b.global && - a.multiline == b.multiline && - a.ignoreCase == b.ignoreCase - ); - } - if (typeof a != 'object' || typeof b != 'object') { - diffBuilder.recordMismatch(); - return false; - } - - const aIsDomNode = j$.isDomNode(a); - const bIsDomNode = j$.isDomNode(b); - if (aIsDomNode && bIsDomNode) { - // At first try to use DOM3 method isEqualNode - result = a.isEqualNode(b); - if (!result) { - diffBuilder.recordMismatch(); - } - return result; - } - if (aIsDomNode || bIsDomNode) { - diffBuilder.recordMismatch(); - return false; - } - - const aIsPromise = j$.isPromise(a); - const bIsPromise = j$.isPromise(b); - if (aIsPromise && bIsPromise) { - return a === b; - } - - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - let length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] == a) { - return bStack[length] == b; - } - } - // Add the first object to the stack of traversed objects. - aStack.push(a); - bStack.push(b); - let size = 0; - // Recursively compare objects and arrays. - // Compare array lengths to determine if a deep comparison is necessary. - if (className == '[object Array]') { - const aLength = a.length; - const bLength = b.length; - - diffBuilder.withPath('length', function() { - if (aLength !== bLength) { - diffBuilder.recordMismatch(); - result = false; - } - }); - - for (let i = 0; i < aLength || i < bLength; i++) { - diffBuilder.withPath(i, () => { - if (i >= bLength) { - diffBuilder.recordMismatch( - actualArrayIsLongerFormatter.bind(null, this.pp) - ); - result = false; - } else { - result = - this.eq_( - i < aLength ? a[i] : void 0, - i < bLength ? b[i] : void 0, - aStack, - bStack, - diffBuilder - ) && result; - } - }); - } - if (!result) { - return false; - } - } else if (j$.isMap(a) && j$.isMap(b)) { - if (a.size != b.size) { - diffBuilder.recordMismatch(); - return false; - } - - const keysA = []; - const keysB = []; - a.forEach(function(valueA, keyA) { - keysA.push(keyA); - }); - b.forEach(function(valueB, keyB) { - keysB.push(keyB); - }); - - // For both sets of keys, check they map to equal values in both maps. - // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. - const mapKeys = [keysA, keysB]; - const cmpKeys = [keysB, keysA]; - for (let i = 0; result && i < mapKeys.length; i++) { - const mapIter = mapKeys[i]; - const cmpIter = cmpKeys[i]; - - for (let j = 0; result && j < mapIter.length; j++) { - const mapKey = mapIter[j]; - const cmpKey = cmpIter[j]; - const mapValueA = a.get(mapKey); - let mapValueB; - - // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, - // otherwise explicitly look up the mapKey in the other Map since we want keys with unique - // obj identity (that are otherwise equal) to not match. - if ( - j$.isAsymmetricEqualityTester_(mapKey) || - (j$.isAsymmetricEqualityTester_(cmpKey) && - this.eq_(mapKey, cmpKey, aStack, bStack, j$.NullDiffBuilder())) - ) { - mapValueB = b.get(cmpKey); - } else { - mapValueB = b.get(mapKey); - } - result = this.eq_( - mapValueA, - mapValueB, - aStack, - bStack, - j$.NullDiffBuilder() - ); - } - } - - if (!result) { - diffBuilder.recordMismatch(); - return false; - } - } else if (j$.isSet(a) && j$.isSet(b)) { - if (a.size != b.size) { - diffBuilder.recordMismatch(); - return false; - } - - const valuesA = []; - a.forEach(function(valueA) { - valuesA.push(valueA); - }); - const valuesB = []; - b.forEach(function(valueB) { - valuesB.push(valueB); - }); - - // For both sets, check they are all contained in the other set - const setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; - const stackPairs = [[aStack, bStack], [bStack, aStack]]; - for (let i = 0; result && i < setPairs.length; i++) { - const baseValues = setPairs[i][0]; - const otherValues = setPairs[i][1]; - const baseStack = stackPairs[i][0]; - const otherStack = stackPairs[i][1]; - // For each value in the base set... - for (const baseValue of baseValues) { - let found = false; - // ... test that it is present in the other set - for (let j = 0; !found && j < otherValues.length; j++) { - const otherValue = otherValues[j]; - const prevStackSize = baseStack.length; - // compare by value equality - found = this.eq_( - baseValue, - otherValue, - baseStack, - otherStack, - j$.NullDiffBuilder() - ); - if (!found && prevStackSize !== baseStack.length) { - baseStack.splice(prevStackSize); - otherStack.splice(prevStackSize); + if (j$.isSet(haystack)) { + // Try .has() first. It should be faster in cases where + // needle === something in haystack. Fall back to .equals() comparison + // if that fails. + if (haystack.has(needle)) { + return true } - } - result = result && found; } - } - if (!result) { - diffBuilder.recordMismatch(); - return false; - } - } else if (j$.isURL(a) && j$.isURL(b)) { - // URLs have no enumrable properties, so the default object comparison - // would consider any two URLs to be equal. - return a.toString() === b.toString(); - } else { - // Objects with different constructors are not equivalent, but `Object`s - // or `Array`s from different frames are. - const aCtor = a.constructor, - bCtor = b.constructor; - if ( - aCtor !== bCtor && - isFunction(aCtor) && - isFunction(bCtor) && - a instanceof aCtor && - b instanceof bCtor && - !(aCtor instanceof aCtor && bCtor instanceof bCtor) - ) { - diffBuilder.recordMismatch( - constructorsAreDifferentFormatter.bind(null, this.pp) - ); - return false; - } - } + if (j$.isIterable_(haystack) && !j$.isString_(haystack)) { + // Arrays, Sets, etc. + for (const candidate of haystack) { + if (this.equals(candidate, needle)) { + return true + } + } - // Deep compare objects. - const aKeys = MatchersUtil.keys(a, className == '[object Array]'); - size = aKeys.length; - - // Ensure that both objects contain the same number of properties before comparing deep equality. - if (MatchersUtil.keys(b, className == '[object Array]').length !== size) { - diffBuilder.recordMismatch( - objectKeysAreDifferentFormatter.bind(null, this.pp) - ); - return false; - } - - for (const key of aKeys) { - // Deep compare each member - if (!j$.util.has(b, key)) { - diffBuilder.recordMismatch( - objectKeysAreDifferentFormatter.bind(null, this.pp) - ); - result = false; - continue; - } - - diffBuilder.withPath(key, () => { - if (!this.eq_(a[key], b[key], aStack, bStack, diffBuilder)) { - result = false; + return false } - }); - } - if (!result) { - return false; - } - - // Remove the first object from the stack of traversed objects. - aStack.pop(); - bStack.pop(); - - return result; - }; - - MatchersUtil.keys = function(obj, isArray) { - const allKeys = (function(o) { - const keys = []; - for (const key in o) { - if (j$.util.has(o, key)) { - keys.push(key); + if (haystack.indexOf) { + // Mainly strings + return haystack.indexOf(needle) >= 0 } - } - const symbols = Object.getOwnPropertySymbols(o); - for (const sym of symbols) { - if (o.propertyIsEnumerable(sym)) { - keys.push(sym); + if (j$.isNumber_(haystack.length)) { + // Objects that are shaped like arrays but aren't iterable + for (let i = 0; i < haystack.length; i++) { + if (this.equals(haystack[i], needle)) { + return true + } + } } - } - return keys; - })(obj); - - if (!isArray) { - return allKeys; + return false } - if (allKeys.length === 0) { - return allKeys; + MatchersUtil.prototype.buildFailureMessage = function() { + const args = Array.prototype.slice.call(arguments, 0), + matcherName = args[0], + isNot = args[1], + actual = args[2], + expected = args.slice(3), + englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { + return " " + s.toLowerCase() + }) + + let message = "Expected " + this.pp(actual) + (isNot ? " not " : " ") + englishyPredicate + + if (expected.length > 0) { + for (let i = 0; i < expected.length; i++) { + if (i > 0) { + message += "," + } + message += " " + this.pp(expected[i]) + } + } + + return message + "." } - const extraKeys = []; - for (const k of allKeys) { - if (typeof k === 'symbol' || !/^[0-9]+$/.test(k)) { - extraKeys.push(k); - } + MatchersUtil.prototype.asymmetricDiff_ = function(a, b, aStack, bStack, diffBuilder) { + if (j$.isFunction_(b.valuesForDiff_)) { + const values = b.valuesForDiff_(a, this.pp) + this.eq_(values.other, values.self, aStack, bStack, diffBuilder) + } else { + diffBuilder.recordMismatch() + } } - return extraKeys; - }; + MatchersUtil.prototype.asymmetricMatch_ = function(a, b, aStack, bStack, diffBuilder) { + const asymmetricA = j$.isAsymmetricEqualityTester_(a) + const asymmetricB = j$.isAsymmetricEqualityTester_(b) - function isFunction(obj) { - return typeof obj === 'function'; - } + if (asymmetricA === asymmetricB) { + return undefined + } - // Returns an array of [k, v] pairs for eacch property that's in objA - // and not in objB. - function extraKeysAndValues(objA, objB) { - return MatchersUtil.keys(objA) - .filter(key => !j$.util.has(objB, key)) - .map(key => [key, objA[key]]); - } + let result - function objectKeysAreDifferentFormatter(pp, actual, expected, path) { - const missingProperties = extraKeysAndValues(expected, actual), - extraProperties = extraKeysAndValues(actual, expected), - missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties), - extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties), - messages = []; + if (asymmetricA) { + result = a.asymmetricMatch(b, this) + if (!result) { + diffBuilder.recordMismatch() + } + return result + } - if (!path.depth()) { - path = 'object'; + if (asymmetricB) { + result = b.asymmetricMatch(a, this) + if (!result) { + this.asymmetricDiff_(a, b, aStack, bStack, diffBuilder) + } + return result + } } - if (missingPropertiesMessage.length) { - messages.push( - 'Expected ' + path + ' to have properties' + missingPropertiesMessage - ); + /** + * Determines whether two values are deeply equal to each other. + * @function + * @name MatchersUtil#equals + * @since 2.0.0 + * @param {*} a The first value to compare + * @param {*} b The second value to compare + * @returns {boolean} True if the values are equal + */ + MatchersUtil.prototype.equals = function(a, b, diffBuilder) { + diffBuilder = diffBuilder || j$.NullDiffBuilder() + diffBuilder.setRoots(a, b) + + return this.eq_(a, b, [], [], diffBuilder) } - if (extraPropertiesMessage.length) { - messages.push( - 'Expected ' + path + ' not to have properties' + extraPropertiesMessage - ); + // Equality function lovingly adapted from isEqual in + // [Underscore](http://underscorejs.org) + MatchersUtil.prototype.eq_ = function(a, b, aStack, bStack, diffBuilder) { + let result = true + + const asymmetricResult = this.asymmetricMatch_(a, b, aStack, bStack, diffBuilder) + if (!j$.util.isUndefined(asymmetricResult)) { + return asymmetricResult + } + + for (const tester of this.customTesters_) { + const customTesterResult = tester(a, b) + if (!j$.util.isUndefined(customTesterResult)) { + if (!customTesterResult) { + diffBuilder.recordMismatch() + } + return customTesterResult + } + } + + if (a instanceof Error && b instanceof Error) { + result = a.message == b.message + if (!result) { + diffBuilder.recordMismatch() + } + return result + } + + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) { + result = a !== 0 || 1 / a == 1 / b + if (!result) { + diffBuilder.recordMismatch() + } + return result + } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { + result = a === b + if (!result) { + diffBuilder.recordMismatch() + } + return result + } + const className = Object.prototype.toString.call(a) + if (className != Object.prototype.toString.call(b)) { + diffBuilder.recordMismatch() + return false + } + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case "[object String]": + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + result = a == String(b) + if (!result) { + diffBuilder.recordMismatch() + } + return result + case "[object Number]": + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + result = a != +a ? b != +b : a === 0 && b === 0 ? 1 / a == 1 / b : a == +b + if (!result) { + diffBuilder.recordMismatch() + } + return result + case "[object Date]": + case "[object Boolean]": + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + result = +a == +b + if (!result) { + diffBuilder.recordMismatch() + } + return result + case "[object ArrayBuffer]": + // If we have an instance of ArrayBuffer the Uint8Array ctor + // will be defined as well + return this.eq_(new Uint8Array(a), new Uint8Array(b), aStack, bStack, diffBuilder) + // RegExps are compared by their source patterns and flags. + case "[object RegExp]": + return ( + a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase + ) + } + if (typeof a != "object" || typeof b != "object") { + diffBuilder.recordMismatch() + return false + } + + const aIsDomNode = j$.isDomNode(a) + const bIsDomNode = j$.isDomNode(b) + if (aIsDomNode && bIsDomNode) { + // At first try to use DOM3 method isEqualNode + result = a.isEqualNode(b) + if (!result) { + diffBuilder.recordMismatch() + } + return result + } + if (aIsDomNode || bIsDomNode) { + diffBuilder.recordMismatch() + return false + } + + const aIsPromise = j$.isPromise(a) + const bIsPromise = j$.isPromise(b) + if (aIsPromise && bIsPromise) { + return a === b + } + + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + let length = aStack.length + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) { + return bStack[length] == b + } + } + // Add the first object to the stack of traversed objects. + aStack.push(a) + bStack.push(b) + let size = 0 + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (className == "[object Array]") { + const aLength = a.length + const bLength = b.length + + diffBuilder.withPath("length", function() { + if (aLength !== bLength) { + diffBuilder.recordMismatch() + result = false + } + }) + + for (let i = 0; i < aLength || i < bLength; i++) { + diffBuilder.withPath(i, () => { + if (i >= bLength) { + diffBuilder.recordMismatch(actualArrayIsLongerFormatter.bind(null, this.pp)) + result = false + } else { + result = + this.eq_( + i < aLength ? a[i] : void 0, + i < bLength ? b[i] : void 0, + aStack, + bStack, + diffBuilder + ) && result + } + }) + } + if (!result) { + return false + } + } else if (j$.isMap(a) && j$.isMap(b)) { + if (a.size != b.size) { + diffBuilder.recordMismatch() + return false + } + + const keysA = [] + const keysB = [] + a.forEach(function(valueA, keyA) { + keysA.push(keyA) + }) + b.forEach(function(valueB, keyB) { + keysB.push(keyB) + }) + + // For both sets of keys, check they map to equal values in both maps. + // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. + const mapKeys = [keysA, keysB] + const cmpKeys = [keysB, keysA] + for (let i = 0; result && i < mapKeys.length; i++) { + const mapIter = mapKeys[i] + const cmpIter = cmpKeys[i] + + for (let j = 0; result && j < mapIter.length; j++) { + const mapKey = mapIter[j] + const cmpKey = cmpIter[j] + const mapValueA = a.get(mapKey) + let mapValueB + + // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, + // otherwise explicitly look up the mapKey in the other Map since we want keys with unique + // obj identity (that are otherwise equal) to not match. + if ( + j$.isAsymmetricEqualityTester_(mapKey) || + (j$.isAsymmetricEqualityTester_(cmpKey) && + this.eq_(mapKey, cmpKey, aStack, bStack, j$.NullDiffBuilder())) + ) { + mapValueB = b.get(cmpKey) + } else { + mapValueB = b.get(mapKey) + } + result = this.eq_(mapValueA, mapValueB, aStack, bStack, j$.NullDiffBuilder()) + } + } + + if (!result) { + diffBuilder.recordMismatch() + return false + } + } else if (j$.isSet(a) && j$.isSet(b)) { + if (a.size != b.size) { + diffBuilder.recordMismatch() + return false + } + + const valuesA = [] + a.forEach(function(valueA) { + valuesA.push(valueA) + }) + const valuesB = [] + b.forEach(function(valueB) { + valuesB.push(valueB) + }) + + // For both sets, check they are all contained in the other set + const setPairs = [ + [valuesA, valuesB], + [valuesB, valuesA], + ] + const stackPairs = [ + [aStack, bStack], + [bStack, aStack], + ] + for (let i = 0; result && i < setPairs.length; i++) { + const baseValues = setPairs[i][0] + const otherValues = setPairs[i][1] + const baseStack = stackPairs[i][0] + const otherStack = stackPairs[i][1] + // For each value in the base set... + for (const baseValue of baseValues) { + let found = false + // ... test that it is present in the other set + for (let j = 0; !found && j < otherValues.length; j++) { + const otherValue = otherValues[j] + const prevStackSize = baseStack.length + // compare by value equality + found = this.eq_(baseValue, otherValue, baseStack, otherStack, j$.NullDiffBuilder()) + if (!found && prevStackSize !== baseStack.length) { + baseStack.splice(prevStackSize) + otherStack.splice(prevStackSize) + } + } + result = result && found + } + } + + if (!result) { + diffBuilder.recordMismatch() + return false + } + } else if (j$.isURL(a) && j$.isURL(b)) { + // URLs have no enumrable properties, so the default object comparison + // would consider any two URLs to be equal. + return a.toString() === b.toString() + } else { + // Objects with different constructors are not equivalent, but `Object`s + // or `Array`s from different frames are. + const aCtor = a.constructor, + bCtor = b.constructor + if ( + aCtor !== bCtor && + isFunction(aCtor) && + isFunction(bCtor) && + a instanceof aCtor && + b instanceof bCtor && + !(aCtor instanceof aCtor && bCtor instanceof bCtor) + ) { + diffBuilder.recordMismatch(constructorsAreDifferentFormatter.bind(null, this.pp)) + return false + } + } + + // Deep compare objects. + const aKeys = MatchersUtil.keys(a, className == "[object Array]") + size = aKeys.length + + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (MatchersUtil.keys(b, className == "[object Array]").length !== size) { + diffBuilder.recordMismatch(objectKeysAreDifferentFormatter.bind(null, this.pp)) + return false + } + + for (const key of aKeys) { + // Deep compare each member + if (!j$.util.has(b, key)) { + diffBuilder.recordMismatch(objectKeysAreDifferentFormatter.bind(null, this.pp)) + result = false + continue + } + + diffBuilder.withPath(key, () => { + if (!this.eq_(a[key], b[key], aStack, bStack, diffBuilder)) { + result = false + } + }) + } + + if (!result) { + return false + } + + // Remove the first object from the stack of traversed objects. + aStack.pop() + bStack.pop() + + return result } - return messages.join('\n'); - } + MatchersUtil.keys = function(obj, isArray) { + const allKeys = (function(o) { + const keys = [] + for (const key in o) { + if (j$.util.has(o, key)) { + keys.push(key) + } + } - function constructorsAreDifferentFormatter(pp, actual, expected, path) { - if (!path.depth()) { - path = 'object'; + const symbols = Object.getOwnPropertySymbols(o) + for (const sym of symbols) { + if (o.propertyIsEnumerable(sym)) { + keys.push(sym) + } + } + + return keys + })(obj) + + if (!isArray) { + return allKeys + } + + if (allKeys.length === 0) { + return allKeys + } + + const extraKeys = [] + for (const k of allKeys) { + if (typeof k === "symbol" || !/^[0-9]+$/.test(k)) { + extraKeys.push(k) + } + } + + return extraKeys } - return ( - 'Expected ' + - path + - ' to be a kind of ' + - j$.fnNameFor(expected.constructor) + - ', but was ' + - pp(actual) + - '.' - ); - } - - function actualArrayIsLongerFormatter(pp, actual, expected, path) { - return ( - 'Unexpected ' + - path + - (path.depth() ? ' = ' : '') + - pp(actual) + - ' in array.' - ); - } - - function formatKeyValuePairs(pp, keyValuePairs) { - let formatted = ''; - - for (const [key, value] of keyValuePairs) { - formatted += '\n ' + key.toString() + ': ' + pp(value); + function isFunction(obj) { + return typeof obj === "function" } - return formatted; - } + // Returns an array of [k, v] pairs for eacch property that's in objA + // and not in objB. + function extraKeysAndValues(objA, objB) { + return MatchersUtil.keys(objA) + .filter((key) => !j$.util.has(objB, key)) + .map((key) => [key, objA[key]]) + } - return MatchersUtil; -}; + function objectKeysAreDifferentFormatter(pp, actual, expected, path) { + const missingProperties = extraKeysAndValues(expected, actual), + extraProperties = extraKeysAndValues(actual, expected), + missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties), + extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties), + messages = [] + + if (!path.depth()) { + path = "object" + } + + if (missingPropertiesMessage.length) { + messages.push("Expected " + path + " to have properties" + missingPropertiesMessage) + } + + if (extraPropertiesMessage.length) { + messages.push("Expected " + path + " not to have properties" + extraPropertiesMessage) + } + + return messages.join("\n") + } + + function constructorsAreDifferentFormatter(pp, actual, expected, path) { + if (!path.depth()) { + path = "object" + } + + return ( + "Expected " + + path + + " to be a kind of " + + j$.fnNameFor(expected.constructor) + + ", but was " + + pp(actual) + + "." + ) + } + + function actualArrayIsLongerFormatter(pp, actual, expected, path) { + return "Unexpected " + path + (path.depth() ? " = " : "") + pp(actual) + " in array." + } + + function formatKeyValuePairs(pp, keyValuePairs) { + let formatted = "" + + for (const [key, value] of keyValuePairs) { + formatted += "\n " + key.toString() + ": " + pp(value) + } + + return formatted + } + + return MatchersUtil +} /** * @interface AsymmetricEqualityTester @@ -5288,5181 +4964,4872 @@ getJasmineRequireObj().MatchersUtil = function(j$) { */ getJasmineRequireObj().MismatchTree = function(j$) { - /* + /* To be able to apply custom object formatters at all possible levels of an object graph, DiffBuilder needs to be able to know not just where the mismatch occurred but also all ancestors of the mismatched value in both the expected and actual object graphs. MismatchTree maintains that context and provides it via the traverse method. */ - class MismatchTree { - constructor(path) { - this.path = path || new j$.ObjectPath([]); - this.formatter = undefined; - this.children = []; - this.isMismatch = false; - } - - add(path, formatter) { - if (path.depth() === 0) { - this.formatter = formatter; - this.isMismatch = true; - } else { - const key = path.components[0]; - path = path.shift(); - let child = this.child(key); - - if (!child) { - child = new MismatchTree(this.path.add(key)); - this.children.push(child); + class MismatchTree { + constructor(path) { + this.path = path || new j$.ObjectPath([]) + this.formatter = undefined + this.children = [] + this.isMismatch = false } - child.add(path, formatter); - } - } + add(path, formatter) { + if (path.depth() === 0) { + this.formatter = formatter + this.isMismatch = true + } else { + const key = path.components[0] + path = path.shift() + let child = this.child(key) - traverse(visit) { - const hasChildren = this.children.length > 0; + if (!child) { + child = new MismatchTree(this.path.add(key)) + this.children.push(child) + } - if (this.isMismatch || hasChildren) { - if (visit(this.path, !hasChildren, this.formatter)) { - for (const child of this.children) { - child.traverse(visit); - } + child.add(path, formatter) + } + } + + traverse(visit) { + const hasChildren = this.children.length > 0 + + if (this.isMismatch || hasChildren) { + if (visit(this.path, !hasChildren, this.formatter)) { + for (const child of this.children) { + child.traverse(visit) + } + } + } + } + + child(key) { + return this.children.find((child) => { + const pathEls = child.path.components + return pathEls[pathEls.length - 1] === key + }) } - } } - child(key) { - return this.children.find(child => { - const pathEls = child.path.components; - return pathEls[pathEls.length - 1] === key; - }); - } - } - - return MismatchTree; -}; + return MismatchTree +} getJasmineRequireObj().nothing = function() { - /** - * {@link expect} nothing explicitly. - * @function - * @name matchers#nothing - * @since 2.8.0 - * @example - * expect().nothing(); - */ - function nothing() { - return { - compare: function() { + /** + * {@link expect} nothing explicitly. + * @function + * @name matchers#nothing + * @since 2.8.0 + * @example + * expect().nothing(); + */ + function nothing() { return { - pass: true - }; - } - }; - } + compare: function() { + return { + pass: true, + } + }, + } + } - return nothing; -}; + return nothing +} getJasmineRequireObj().NullDiffBuilder = function(j$) { - return function() { - return { - withPath: function(_, block) { - block(); - }, - setRoots: function() {}, - recordMismatch: function() {} - }; - }; -}; + return function() { + return { + withPath: function(_, block) { + block() + }, + setRoots: function() {}, + recordMismatch: function() {}, + } + } +} getJasmineRequireObj().ObjectPath = function(j$) { - class ObjectPath { - constructor(components) { - this.components = components || []; + class ObjectPath { + constructor(components) { + this.components = components || [] + } + + toString() { + if (this.components.length) { + return "$" + this.components.map(formatPropertyAccess).join("") + } else { + return "" + } + } + + add(component) { + return new ObjectPath(this.components.concat([component])) + } + + shift() { + return new ObjectPath(this.components.slice(1)) + } + + depth() { + return this.components.length + } } - toString() { - if (this.components.length) { - return '$' + this.components.map(formatPropertyAccess).join(''); - } else { - return ''; - } + function formatPropertyAccess(prop) { + if (typeof prop === "number" || typeof prop === "symbol") { + return "[" + prop.toString() + "]" + } + + if (isValidIdentifier(prop)) { + return "." + prop + } + + return `['${prop}']` } - add(component) { - return new ObjectPath(this.components.concat([component])); + function isValidIdentifier(string) { + return /^[A-Za-z\$_][A-Za-z0-9\$_]*$/.test(string) } - shift() { - return new ObjectPath(this.components.slice(1)); - } - - depth() { - return this.components.length; - } - } - - function formatPropertyAccess(prop) { - if (typeof prop === 'number' || typeof prop === 'symbol') { - return '[' + prop.toString() + ']'; - } - - if (isValidIdentifier(prop)) { - return '.' + prop; - } - - return `['${prop}']`; - } - - function isValidIdentifier(string) { - return /^[A-Za-z\$_][A-Za-z0-9\$_]*$/.test(string); - } - - return ObjectPath; -}; + return ObjectPath +} getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { - const availableMatchers = [ - 'toBePending', - 'toBeResolved', - 'toBeRejected', - 'toBeResolvedTo', - 'toBeRejectedWith', - 'toBeRejectedWithError' - ], - matchers = {}; + const availableMatchers = [ + "toBePending", + "toBeResolved", + "toBeRejected", + "toBeResolvedTo", + "toBeRejectedWith", + "toBeRejectedWithError", + ], + matchers = {} - for (const name of availableMatchers) { - matchers[name] = jRequire[name](j$); - } + for (const name of availableMatchers) { + matchers[name] = jRequire[name](j$) + } - return matchers; -}; + return matchers +} getJasmineRequireObj().toBe = function(j$) { - /** - * {@link expect} the actual value to be `===` to the expected value. - * @function - * @name matchers#toBe - * @since 1.3.0 - * @param {Object} expected - The expected value to compare against. - * @example - * expect(thing).toBe(realThing); - */ - function toBe(matchersUtil) { - const tip = - ' Tip: To check for deep equality, use .toEqual() instead of .toBe().'; + /** + * {@link expect} the actual value to be `===` to the expected value. + * @function + * @name matchers#toBe + * @since 1.3.0 + * @param {Object} expected - The expected value to compare against. + * @example + * expect(thing).toBe(realThing); + */ + function toBe(matchersUtil) { + const tip = " Tip: To check for deep equality, use .toEqual() instead of .toBe()." - return { - compare: function(actual, expected) { - const result = { - pass: actual === expected - }; + return { + compare: function(actual, expected) { + const result = { + pass: actual === expected, + } - if (typeof expected === 'object') { - result.message = - matchersUtil.buildFailureMessage( - 'toBe', - result.pass, - actual, - expected - ) + tip; + if (typeof expected === "object") { + result.message = matchersUtil.buildFailureMessage("toBe", result.pass, actual, expected) + tip + } + + return result + }, } + } - return result; - } - }; - } - - return toBe; -}; + return toBe +} getJasmineRequireObj().toBeCloseTo = function() { - /** - * {@link expect} the actual value to be within a specified precision of the expected value. - * @function - * @name matchers#toBeCloseTo - * @since 1.3.0 - * @param {Object} expected - The expected value to compare against. - * @param {Number} [precision=2] - The number of decimal points to check. - * @example - * expect(number).toBeCloseTo(42.2, 3); - */ - function toBeCloseTo() { - return { - compare: function(actual, expected, precision) { - if (precision !== 0) { - precision = precision || 2; - } - - if (expected === null || actual === null) { - throw new Error( - 'Cannot use toBeCloseTo with null. Arguments evaluated to: ' + - 'expect(' + - actual + - ').toBeCloseTo(' + - expected + - ').' - ); - } - - // Infinity is close to Infinity and -Infinity is close to -Infinity, - // regardless of the precision. - if (expected === Infinity || expected === -Infinity) { - return { - pass: actual === expected - }; - } - - const pow = Math.pow(10, precision + 1); - const delta = Math.abs(expected - actual); - const maxDelta = Math.pow(10, -precision) / 2; - + /** + * {@link expect} the actual value to be within a specified precision of the expected value. + * @function + * @name matchers#toBeCloseTo + * @since 1.3.0 + * @param {Object} expected - The expected value to compare against. + * @param {Number} [precision=2] - The number of decimal points to check. + * @example + * expect(number).toBeCloseTo(42.2, 3); + */ + function toBeCloseTo() { return { - pass: Math.round(delta * pow) <= maxDelta * pow - }; - } - }; - } + compare: function(actual, expected, precision) { + if (precision !== 0) { + precision = precision || 2 + } - return toBeCloseTo; -}; + if (expected === null || actual === null) { + throw new Error( + "Cannot use toBeCloseTo with null. Arguments evaluated to: " + + "expect(" + + actual + + ").toBeCloseTo(" + + expected + + ")." + ) + } + + // Infinity is close to Infinity and -Infinity is close to -Infinity, + // regardless of the precision. + if (expected === Infinity || expected === -Infinity) { + return { + pass: actual === expected, + } + } + + const pow = Math.pow(10, precision + 1) + const delta = Math.abs(expected - actual) + const maxDelta = Math.pow(10, -precision) / 2 + + return { + pass: Math.round(delta * pow) <= maxDelta * pow, + } + }, + } + } + + return toBeCloseTo +} getJasmineRequireObj().toBeDefined = function() { - /** - * {@link expect} the actual value to be defined. (Not `undefined`) - * @function - * @name matchers#toBeDefined - * @since 1.3.0 - * @example - * expect(result).toBeDefined(); - */ - function toBeDefined() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be defined. (Not `undefined`) + * @function + * @name matchers#toBeDefined + * @since 1.3.0 + * @example + * expect(result).toBeDefined(); + */ + function toBeDefined() { return { - pass: void 0 !== actual - }; - } - }; - } + compare: function(actual) { + return { + pass: void 0 !== actual, + } + }, + } + } - return toBeDefined; -}; + return toBeDefined +} getJasmineRequireObj().toBeFalse = function() { - /** - * {@link expect} the actual value to be `false`. - * @function - * @name matchers#toBeFalse - * @since 3.5.0 - * @example - * expect(result).toBeFalse(); - */ - function toBeFalse() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be `false`. + * @function + * @name matchers#toBeFalse + * @since 3.5.0 + * @example + * expect(result).toBeFalse(); + */ + function toBeFalse() { return { - pass: actual === false - }; - } - }; - } + compare: function(actual) { + return { + pass: actual === false, + } + }, + } + } - return toBeFalse; -}; + return toBeFalse +} getJasmineRequireObj().toBeFalsy = function() { - /** - * {@link expect} the actual value to be falsy - * @function - * @name matchers#toBeFalsy - * @since 2.0.0 - * @example - * expect(result).toBeFalsy(); - */ - function toBeFalsy() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be falsy + * @function + * @name matchers#toBeFalsy + * @since 2.0.0 + * @example + * expect(result).toBeFalsy(); + */ + function toBeFalsy() { return { - pass: !actual - }; - } - }; - } + compare: function(actual) { + return { + pass: !actual, + } + }, + } + } - return toBeFalsy; -}; + return toBeFalsy +} getJasmineRequireObj().toBeGreaterThan = function() { - /** - * {@link expect} the actual value to be greater than the expected value. - * @function - * @name matchers#toBeGreaterThan - * @since 2.0.0 - * @param {Number} expected - The value to compare against. - * @example - * expect(result).toBeGreaterThan(3); - */ - function toBeGreaterThan() { - return { - compare: function(actual, expected) { + /** + * {@link expect} the actual value to be greater than the expected value. + * @function + * @name matchers#toBeGreaterThan + * @since 2.0.0 + * @param {Number} expected - The value to compare against. + * @example + * expect(result).toBeGreaterThan(3); + */ + function toBeGreaterThan() { return { - pass: actual > expected - }; - } - }; - } + compare: function(actual, expected) { + return { + pass: actual > expected, + } + }, + } + } - return toBeGreaterThan; -}; + return toBeGreaterThan +} getJasmineRequireObj().toBeGreaterThanOrEqual = function() { - /** - * {@link expect} the actual value to be greater than or equal to the expected value. - * @function - * @name matchers#toBeGreaterThanOrEqual - * @since 2.0.0 - * @param {Number} expected - The expected value to compare against. - * @example - * expect(result).toBeGreaterThanOrEqual(25); - */ - function toBeGreaterThanOrEqual() { - return { - compare: function(actual, expected) { + /** + * {@link expect} the actual value to be greater than or equal to the expected value. + * @function + * @name matchers#toBeGreaterThanOrEqual + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeGreaterThanOrEqual(25); + */ + function toBeGreaterThanOrEqual() { return { - pass: actual >= expected - }; - } - }; - } + compare: function(actual, expected) { + return { + pass: actual >= expected, + } + }, + } + } - return toBeGreaterThanOrEqual; -}; + return toBeGreaterThanOrEqual +} getJasmineRequireObj().toBeInstanceOf = function(j$) { - const usageError = j$.formatErrorMsg( - '', - 'expect(value).toBeInstanceOf()' - ); + const usageError = j$.formatErrorMsg("", "expect(value).toBeInstanceOf()") - /** - * {@link expect} the actual to be an instance of the expected class - * @function - * @name matchers#toBeInstanceOf - * @since 3.5.0 - * @param {Object} expected - The class or constructor function to check for - * @example - * expect('foo').toBeInstanceOf(String); - * expect(3).toBeInstanceOf(Number); - * expect(new Error()).toBeInstanceOf(Error); - */ - function toBeInstanceOf(matchersUtil) { - return { - compare: function(actual, expected) { - const actualType = - actual && actual.constructor - ? j$.fnNameFor(actual.constructor) - : matchersUtil.pp(actual); - const expectedType = expected - ? j$.fnNameFor(expected) - : matchersUtil.pp(expected); - let expectedMatcher; - let pass; + /** + * {@link expect} the actual to be an instance of the expected class + * @function + * @name matchers#toBeInstanceOf + * @since 3.5.0 + * @param {Object} expected - The class or constructor function to check for + * @example + * expect('foo').toBeInstanceOf(String); + * expect(3).toBeInstanceOf(Number); + * expect(new Error()).toBeInstanceOf(Error); + */ + function toBeInstanceOf(matchersUtil) { + return { + compare: function(actual, expected) { + const actualType = + actual && actual.constructor ? j$.fnNameFor(actual.constructor) : matchersUtil.pp(actual) + const expectedType = expected ? j$.fnNameFor(expected) : matchersUtil.pp(expected) + let expectedMatcher + let pass - try { - expectedMatcher = new j$.Any(expected); - pass = expectedMatcher.asymmetricMatch(actual); - } catch (error) { - throw new Error( - usageError('Expected value is not a constructor function') - ); + try { + expectedMatcher = new j$.Any(expected) + pass = expectedMatcher.asymmetricMatch(actual) + } catch (error) { + throw new Error(usageError("Expected value is not a constructor function")) + } + + if (pass) { + return { + pass: true, + message: "Expected instance of " + actualType + " not to be an instance of " + expectedType, + } + } else { + return { + pass: false, + message: "Expected instance of " + actualType + " to be an instance of " + expectedType, + } + } + }, } + } - if (pass) { - return { - pass: true, - message: - 'Expected instance of ' + - actualType + - ' not to be an instance of ' + - expectedType - }; - } else { - return { - pass: false, - message: - 'Expected instance of ' + - actualType + - ' to be an instance of ' + - expectedType - }; - } - } - }; - } - - return toBeInstanceOf; -}; + return toBeInstanceOf +} getJasmineRequireObj().toBeLessThan = function() { - /** - * {@link expect} the actual value to be less than the expected value. - * @function - * @name matchers#toBeLessThan - * @since 2.0.0 - * @param {Number} expected - The expected value to compare against. - * @example - * expect(result).toBeLessThan(0); - */ - function toBeLessThan() { - return { - compare: function(actual, expected) { + /** + * {@link expect} the actual value to be less than the expected value. + * @function + * @name matchers#toBeLessThan + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeLessThan(0); + */ + function toBeLessThan() { return { - pass: actual < expected - }; - } - }; - } + compare: function(actual, expected) { + return { + pass: actual < expected, + } + }, + } + } - return toBeLessThan; -}; + return toBeLessThan +} getJasmineRequireObj().toBeLessThanOrEqual = function() { - /** - * {@link expect} the actual value to be less than or equal to the expected value. - * @function - * @name matchers#toBeLessThanOrEqual - * @since 2.0.0 - * @param {Number} expected - The expected value to compare against. - * @example - * expect(result).toBeLessThanOrEqual(123); - */ - function toBeLessThanOrEqual() { - return { - compare: function(actual, expected) { + /** + * {@link expect} the actual value to be less than or equal to the expected value. + * @function + * @name matchers#toBeLessThanOrEqual + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeLessThanOrEqual(123); + */ + function toBeLessThanOrEqual() { return { - pass: actual <= expected - }; - } - }; - } + compare: function(actual, expected) { + return { + pass: actual <= expected, + } + }, + } + } - return toBeLessThanOrEqual; -}; + return toBeLessThanOrEqual +} getJasmineRequireObj().toBeNaN = function(j$) { - /** - * {@link expect} the actual value to be `NaN` (Not a Number). - * @function - * @name matchers#toBeNaN - * @since 1.3.0 - * @example - * expect(thing).toBeNaN(); - */ - function toBeNaN(matchersUtil) { - return { - compare: function(actual) { - const result = { - pass: actual !== actual - }; + /** + * {@link expect} the actual value to be `NaN` (Not a Number). + * @function + * @name matchers#toBeNaN + * @since 1.3.0 + * @example + * expect(thing).toBeNaN(); + */ + function toBeNaN(matchersUtil) { + return { + compare: function(actual) { + const result = { + pass: actual !== actual, + } - if (result.pass) { - result.message = 'Expected actual not to be NaN.'; - } else { - result.message = function() { - return 'Expected ' + matchersUtil.pp(actual) + ' to be NaN.'; - }; + if (result.pass) { + result.message = "Expected actual not to be NaN." + } else { + result.message = function() { + return "Expected " + matchersUtil.pp(actual) + " to be NaN." + } + } + + return result + }, } + } - return result; - } - }; - } - - return toBeNaN; -}; + return toBeNaN +} getJasmineRequireObj().toBeNegativeInfinity = function(j$) { - /** - * {@link expect} the actual value to be `-Infinity` (-infinity). - * @function - * @name matchers#toBeNegativeInfinity - * @since 2.6.0 - * @example - * expect(thing).toBeNegativeInfinity(); - */ - function toBeNegativeInfinity(matchersUtil) { - return { - compare: function(actual) { - const result = { - pass: actual === Number.NEGATIVE_INFINITY - }; + /** + * {@link expect} the actual value to be `-Infinity` (-infinity). + * @function + * @name matchers#toBeNegativeInfinity + * @since 2.6.0 + * @example + * expect(thing).toBeNegativeInfinity(); + */ + function toBeNegativeInfinity(matchersUtil) { + return { + compare: function(actual) { + const result = { + pass: actual === Number.NEGATIVE_INFINITY, + } - if (result.pass) { - result.message = 'Expected actual not to be -Infinity.'; - } else { - result.message = function() { - return 'Expected ' + matchersUtil.pp(actual) + ' to be -Infinity.'; - }; + if (result.pass) { + result.message = "Expected actual not to be -Infinity." + } else { + result.message = function() { + return "Expected " + matchersUtil.pp(actual) + " to be -Infinity." + } + } + + return result + }, } + } - return result; - } - }; - } - - return toBeNegativeInfinity; -}; + return toBeNegativeInfinity +} getJasmineRequireObj().toBeNull = function() { - /** - * {@link expect} the actual value to be `null`. - * @function - * @name matchers#toBeNull - * @since 1.3.0 - * @example - * expect(result).toBeNull(); - */ - function toBeNull() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be `null`. + * @function + * @name matchers#toBeNull + * @since 1.3.0 + * @example + * expect(result).toBeNull(); + */ + function toBeNull() { return { - pass: actual === null - }; - } - }; - } + compare: function(actual) { + return { + pass: actual === null, + } + }, + } + } - return toBeNull; -}; + return toBeNull +} getJasmineRequireObj().toBePositiveInfinity = function(j$) { - /** - * {@link expect} the actual value to be `Infinity` (infinity). - * @function - * @name matchers#toBePositiveInfinity - * @since 2.6.0 - * @example - * expect(thing).toBePositiveInfinity(); - */ - function toBePositiveInfinity(matchersUtil) { - return { - compare: function(actual) { - const result = { - pass: actual === Number.POSITIVE_INFINITY - }; + /** + * {@link expect} the actual value to be `Infinity` (infinity). + * @function + * @name matchers#toBePositiveInfinity + * @since 2.6.0 + * @example + * expect(thing).toBePositiveInfinity(); + */ + function toBePositiveInfinity(matchersUtil) { + return { + compare: function(actual) { + const result = { + pass: actual === Number.POSITIVE_INFINITY, + } - if (result.pass) { - result.message = 'Expected actual not to be Infinity.'; - } else { - result.message = function() { - return 'Expected ' + matchersUtil.pp(actual) + ' to be Infinity.'; - }; + if (result.pass) { + result.message = "Expected actual not to be Infinity." + } else { + result.message = function() { + return "Expected " + matchersUtil.pp(actual) + " to be Infinity." + } + } + + return result + }, } + } - return result; - } - }; - } - - return toBePositiveInfinity; -}; + return toBePositiveInfinity +} getJasmineRequireObj().toBeTrue = function() { - /** - * {@link expect} the actual value to be `true`. - * @function - * @name matchers#toBeTrue - * @since 3.5.0 - * @example - * expect(result).toBeTrue(); - */ - function toBeTrue() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be `true`. + * @function + * @name matchers#toBeTrue + * @since 3.5.0 + * @example + * expect(result).toBeTrue(); + */ + function toBeTrue() { return { - pass: actual === true - }; - } - }; - } + compare: function(actual) { + return { + pass: actual === true, + } + }, + } + } - return toBeTrue; -}; + return toBeTrue +} getJasmineRequireObj().toBeTruthy = function() { - /** - * {@link expect} the actual value to be truthy. - * @function - * @name matchers#toBeTruthy - * @since 2.0.0 - * @example - * expect(thing).toBeTruthy(); - */ - function toBeTruthy() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be truthy. + * @function + * @name matchers#toBeTruthy + * @since 2.0.0 + * @example + * expect(thing).toBeTruthy(); + */ + function toBeTruthy() { return { - pass: !!actual - }; - } - }; - } + compare: function(actual) { + return { + pass: !!actual, + } + }, + } + } - return toBeTruthy; -}; + return toBeTruthy +} getJasmineRequireObj().toBeUndefined = function() { - /** - * {@link expect} the actual value to be `undefined`. - * @function - * @name matchers#toBeUndefined - * @since 1.3.0 - * @example - * expect(result).toBeUndefined(): - */ - function toBeUndefined() { - return { - compare: function(actual) { + /** + * {@link expect} the actual value to be `undefined`. + * @function + * @name matchers#toBeUndefined + * @since 1.3.0 + * @example + * expect(result).toBeUndefined(): + */ + function toBeUndefined() { return { - pass: void 0 === actual - }; - } - }; - } + compare: function(actual) { + return { + pass: void 0 === actual, + } + }, + } + } - return toBeUndefined; -}; + return toBeUndefined +} getJasmineRequireObj().toContain = function() { - /** - * {@link expect} the actual value to contain a specific value. - * @function - * @name matchers#toContain - * @since 2.0.0 - * @param {Object} expected - The value to look for. - * @example - * expect(array).toContain(anElement); - * expect(string).toContain(substring); - */ - function toContain(matchersUtil) { - return { - compare: function(actual, expected) { + /** + * {@link expect} the actual value to contain a specific value. + * @function + * @name matchers#toContain + * @since 2.0.0 + * @param {Object} expected - The value to look for. + * @example + * expect(array).toContain(anElement); + * expect(string).toContain(substring); + */ + function toContain(matchersUtil) { return { - pass: matchersUtil.contains(actual, expected) - }; - } - }; - } + compare: function(actual, expected) { + return { + pass: matchersUtil.contains(actual, expected), + } + }, + } + } - return toContain; -}; + return toContain +} getJasmineRequireObj().toEqual = function(j$) { - /** - * {@link expect} the actual value to be equal to the expected, using deep equality comparison. - * @function - * @name matchers#toEqual - * @since 1.3.0 - * @param {Object} expected - Expected value - * @example - * expect(bigObject).toEqual({"foo": ['bar', 'baz']}); - */ - function toEqual(matchersUtil) { - return { - compare: function(actual, expected) { - const result = { - pass: false - }, - diffBuilder = new j$.DiffBuilder({ prettyPrinter: matchersUtil.pp }); + /** + * {@link expect} the actual value to be equal to the expected, using deep equality comparison. + * @function + * @name matchers#toEqual + * @since 1.3.0 + * @param {Object} expected - Expected value + * @example + * expect(bigObject).toEqual({"foo": ['bar', 'baz']}); + */ + function toEqual(matchersUtil) { + return { + compare: function(actual, expected) { + const result = { + pass: false, + }, + diffBuilder = new j$.DiffBuilder({ prettyPrinter: matchersUtil.pp }) - result.pass = matchersUtil.equals(actual, expected, diffBuilder); + result.pass = matchersUtil.equals(actual, expected, diffBuilder) - // TODO: only set error message if test fails - result.message = diffBuilder.getMessage(); + // TODO: only set error message if test fails + result.message = diffBuilder.getMessage() - return result; - } - }; - } + return result + }, + } + } - return toEqual; -}; + return toEqual +} getJasmineRequireObj().toHaveBeenCalled = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveBeenCalled()' - ); + const getErrorMsg = j$.formatErrorMsg("", "expect().toHaveBeenCalled()") - /** - * {@link expect} the actual (a {@link Spy}) to have been called. - * @function - * @name matchers#toHaveBeenCalled - * @since 1.3.0 - * @example - * expect(mySpy).toHaveBeenCalled(); - * expect(mySpy).not.toHaveBeenCalled(); - */ - function toHaveBeenCalled(matchersUtil) { - return { - compare: function(actual) { - const result = {}; + /** + * {@link expect} the actual (a {@link Spy}) to have been called. + * @function + * @name matchers#toHaveBeenCalled + * @since 1.3.0 + * @example + * expect(mySpy).toHaveBeenCalled(); + * expect(mySpy).not.toHaveBeenCalled(); + */ + function toHaveBeenCalled(matchersUtil) { + return { + compare: function(actual) { + const result = {} - if (!j$.isSpy(actual)) { - throw new Error( - getErrorMsg( - 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' - ) - ); + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg("Expected a spy, but got " + matchersUtil.pp(actual) + ".")) + } + + if (arguments.length > 1) { + throw new Error(getErrorMsg("Does not take arguments, use toHaveBeenCalledWith")) + } + + result.pass = actual.calls.any() + + result.message = result.pass + ? "Expected spy " + actual.and.identity + " not to have been called." + : "Expected spy " + actual.and.identity + " to have been called." + + return result + }, } + } - if (arguments.length > 1) { - throw new Error( - getErrorMsg('Does not take arguments, use toHaveBeenCalledWith') - ); - } - - result.pass = actual.calls.any(); - - result.message = result.pass - ? 'Expected spy ' + actual.and.identity + ' not to have been called.' - : 'Expected spy ' + actual.and.identity + ' to have been called.'; - - return result; - } - }; - } - - return toHaveBeenCalled; -}; + return toHaveBeenCalled +} getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveBeenCalledBefore()' - ); + const getErrorMsg = j$.formatErrorMsg( + "", + "expect().toHaveBeenCalledBefore()" + ) - /** - * {@link expect} the actual value (a {@link Spy}) to have been called before another {@link Spy}. - * @function - * @name matchers#toHaveBeenCalledBefore - * @since 2.6.0 - * @param {Spy} expected - {@link Spy} that should have been called after the `actual` {@link Spy}. - * @example - * expect(mySpy).toHaveBeenCalledBefore(otherSpy); - */ - function toHaveBeenCalledBefore(matchersUtil) { - return { - compare: function(firstSpy, latterSpy) { - if (!j$.isSpy(firstSpy)) { - throw new Error( - getErrorMsg( - 'Expected a spy, but got ' + matchersUtil.pp(firstSpy) + '.' - ) - ); - } - if (!j$.isSpy(latterSpy)) { - throw new Error( - getErrorMsg( - 'Expected a spy, but got ' + matchersUtil.pp(latterSpy) + '.' - ) - ); + /** + * {@link expect} the actual value (a {@link Spy}) to have been called before another {@link Spy}. + * @function + * @name matchers#toHaveBeenCalledBefore + * @since 2.6.0 + * @param {Spy} expected - {@link Spy} that should have been called after the `actual` {@link Spy}. + * @example + * expect(mySpy).toHaveBeenCalledBefore(otherSpy); + */ + function toHaveBeenCalledBefore(matchersUtil) { + return { + compare: function(firstSpy, latterSpy) { + if (!j$.isSpy(firstSpy)) { + throw new Error(getErrorMsg("Expected a spy, but got " + matchersUtil.pp(firstSpy) + ".")) + } + if (!j$.isSpy(latterSpy)) { + throw new Error(getErrorMsg("Expected a spy, but got " + matchersUtil.pp(latterSpy) + ".")) + } + + const result = { pass: false } + + if (!firstSpy.calls.count()) { + result.message = "Expected spy " + firstSpy.and.identity + " to have been called." + return result + } + if (!latterSpy.calls.count()) { + result.message = "Expected spy " + latterSpy.and.identity + " to have been called." + return result + } + + const latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder + const first2ndSpyCall = latterSpy.calls.first().invocationOrder + + result.pass = latest1stSpyCall < first2ndSpyCall + + if (result.pass) { + result.message = + "Expected spy " + + firstSpy.and.identity + + " to not have been called before spy " + + latterSpy.and.identity + + ", but it was" + } else { + const first1stSpyCall = firstSpy.calls.first().invocationOrder + const latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder + + if (first1stSpyCall < first2ndSpyCall) { + result.message = + "Expected latest call to spy " + + firstSpy.and.identity + + " to have been called before first call to spy " + + latterSpy.and.identity + + " (no interleaved calls)" + } else if (latest2ndSpyCall > latest1stSpyCall) { + result.message = + "Expected first call to spy " + + latterSpy.and.identity + + " to have been called after latest call to spy " + + firstSpy.and.identity + + " (no interleaved calls)" + } else { + result.message = + "Expected spy " + + firstSpy.and.identity + + " to have been called before spy " + + latterSpy.and.identity + } + } + + return result + }, } + } - const result = { pass: false }; - - if (!firstSpy.calls.count()) { - result.message = - 'Expected spy ' + firstSpy.and.identity + ' to have been called.'; - return result; - } - if (!latterSpy.calls.count()) { - result.message = - 'Expected spy ' + latterSpy.and.identity + ' to have been called.'; - return result; - } - - const latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; - const first2ndSpyCall = latterSpy.calls.first().invocationOrder; - - result.pass = latest1stSpyCall < first2ndSpyCall; - - if (result.pass) { - result.message = - 'Expected spy ' + - firstSpy.and.identity + - ' to not have been called before spy ' + - latterSpy.and.identity + - ', but it was'; - } else { - const first1stSpyCall = firstSpy.calls.first().invocationOrder; - const latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; - - if (first1stSpyCall < first2ndSpyCall) { - result.message = - 'Expected latest call to spy ' + - firstSpy.and.identity + - ' to have been called before first call to spy ' + - latterSpy.and.identity + - ' (no interleaved calls)'; - } else if (latest2ndSpyCall > latest1stSpyCall) { - result.message = - 'Expected first call to spy ' + - latterSpy.and.identity + - ' to have been called after latest call to spy ' + - firstSpy.and.identity + - ' (no interleaved calls)'; - } else { - result.message = - 'Expected spy ' + - firstSpy.and.identity + - ' to have been called before spy ' + - latterSpy.and.identity; - } - } - - return result; - } - }; - } - - return toHaveBeenCalledBefore; -}; + return toHaveBeenCalledBefore +} getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveBeenCalledOnceWith(...arguments)' - ); - - /** - * {@link expect} the actual (a {@link Spy}) to have been called exactly once, and exactly with the particular arguments. - * @function - * @name matchers#toHaveBeenCalledOnceWith - * @since 3.6.0 - * @param {...Object} - The arguments to look for - * @example - * expect(mySpy).toHaveBeenCalledOnceWith('foo', 'bar', 2); - */ - function toHaveBeenCalledOnceWith(util) { - return { - compare: function() { - const args = Array.prototype.slice.call(arguments, 0), - actual = args[0], - expectedArgs = args.slice(1); - - if (!j$.isSpy(actual)) { - throw new Error( - getErrorMsg('Expected a spy, but got ' + util.pp(actual) + '.') - ); - } - - const prettyPrintedCalls = actual.calls - .allArgs() - .map(function(argsForCall) { - return ' ' + util.pp(argsForCall); - }); - - if ( - actual.calls.count() === 1 && - util.contains(actual.calls.allArgs(), expectedArgs) - ) { - return { - pass: true, - message: - 'Expected spy ' + - actual.and.identity + - ' to have been called 0 times, multiple times, or once, but with arguments different from:\n' + - ' ' + - util.pp(expectedArgs) + - '\n' + - 'But the actual call was:\n' + - prettyPrintedCalls.join(',\n') + - '.\n\n' - }; - } - - function getDiffs() { - return actual.calls.allArgs().map(function(argsForCall, callIx) { - const diffBuilder = new j$.DiffBuilder(); - util.equals(argsForCall, expectedArgs, diffBuilder); - return diffBuilder.getMessage(); - }); - } - - function butString() { - switch (actual.calls.count()) { - case 0: - return 'But it was never called.\n\n'; - case 1: - return ( - 'But the actual call was:\n' + - prettyPrintedCalls.join(',\n') + - '.\n' + - getDiffs().join('\n') + - '\n\n' - ); - default: - return ( - 'But the actual calls were:\n' + - prettyPrintedCalls.join(',\n') + - '.\n\n' - ); - } - } + const getErrorMsg = j$.formatErrorMsg( + "", + "expect().toHaveBeenCalledOnceWith(...arguments)" + ) + /** + * {@link expect} the actual (a {@link Spy}) to have been called exactly once, and exactly with the particular arguments. + * @function + * @name matchers#toHaveBeenCalledOnceWith + * @since 3.6.0 + * @param {...Object} - The arguments to look for + * @example + * expect(mySpy).toHaveBeenCalledOnceWith('foo', 'bar', 2); + */ + function toHaveBeenCalledOnceWith(util) { return { - pass: false, - message: - 'Expected spy ' + - actual.and.identity + - ' to have been called only once, and with given args:\n' + - ' ' + - util.pp(expectedArgs) + - '\n' + - butString() - }; - } - }; - } + compare: function() { + const args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1) - return toHaveBeenCalledOnceWith; -}; + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg("Expected a spy, but got " + util.pp(actual) + ".")) + } + + const prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) { + return " " + util.pp(argsForCall) + }) + + if (actual.calls.count() === 1 && util.contains(actual.calls.allArgs(), expectedArgs)) { + return { + pass: true, + message: + "Expected spy " + + actual.and.identity + + " to have been called 0 times, multiple times, or once, but with arguments different from:\n" + + " " + + util.pp(expectedArgs) + + "\n" + + "But the actual call was:\n" + + prettyPrintedCalls.join(",\n") + + ".\n\n", + } + } + + function getDiffs() { + return actual.calls.allArgs().map(function(argsForCall, callIx) { + const diffBuilder = new j$.DiffBuilder() + util.equals(argsForCall, expectedArgs, diffBuilder) + return diffBuilder.getMessage() + }) + } + + function butString() { + switch (actual.calls.count()) { + case 0: + return "But it was never called.\n\n" + case 1: + return ( + "But the actual call was:\n" + + prettyPrintedCalls.join(",\n") + + ".\n" + + getDiffs().join("\n") + + "\n\n" + ) + default: + return "But the actual calls were:\n" + prettyPrintedCalls.join(",\n") + ".\n\n" + } + } + + return { + pass: false, + message: + "Expected spy " + + actual.and.identity + + " to have been called only once, and with given args:\n" + + " " + + util.pp(expectedArgs) + + "\n" + + butString(), + } + }, + } + } + + return toHaveBeenCalledOnceWith +} getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveBeenCalledTimes()' - ); + const getErrorMsg = j$.formatErrorMsg("", "expect().toHaveBeenCalledTimes()") - /** - * {@link expect} the actual (a {@link Spy}) to have been called the specified number of times. - * @function - * @name matchers#toHaveBeenCalledTimes - * @since 2.4.0 - * @param {Number} expected - The number of invocations to look for. - * @example - * expect(mySpy).toHaveBeenCalledTimes(3); - */ - function toHaveBeenCalledTimes(matchersUtil) { - return { - compare: function(actual, expected) { - if (!j$.isSpy(actual)) { - throw new Error( - getErrorMsg( - 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' - ) - ); + /** + * {@link expect} the actual (a {@link Spy}) to have been called the specified number of times. + * @function + * @name matchers#toHaveBeenCalledTimes + * @since 2.4.0 + * @param {Number} expected - The number of invocations to look for. + * @example + * expect(mySpy).toHaveBeenCalledTimes(3); + */ + function toHaveBeenCalledTimes(matchersUtil) { + return { + compare: function(actual, expected) { + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg("Expected a spy, but got " + matchersUtil.pp(actual) + ".")) + } + + const args = Array.prototype.slice.call(arguments, 0), + result = { pass: false } + + if (!j$.isNumber_(expected)) { + throw new Error( + getErrorMsg("The expected times failed is a required argument and must be a number.") + ) + } + + actual = args[0] + const calls = actual.calls.count() + const timesMessage = expected === 1 ? "once" : expected + " times" + result.pass = calls === expected + result.message = result.pass + ? "Expected spy " + + actual.and.identity + + " not to have been called " + + timesMessage + + ". It was called " + + calls + + " times." + : "Expected spy " + + actual.and.identity + + " to have been called " + + timesMessage + + ". It was called " + + calls + + " times." + return result + }, } + } - const args = Array.prototype.slice.call(arguments, 0), - result = { pass: false }; - - if (!j$.isNumber_(expected)) { - throw new Error( - getErrorMsg( - 'The expected times failed is a required argument and must be a number.' - ) - ); - } - - actual = args[0]; - const calls = actual.calls.count(); - const timesMessage = expected === 1 ? 'once' : expected + ' times'; - result.pass = calls === expected; - result.message = result.pass - ? 'Expected spy ' + - actual.and.identity + - ' not to have been called ' + - timesMessage + - '. It was called ' + - calls + - ' times.' - : 'Expected spy ' + - actual.and.identity + - ' to have been called ' + - timesMessage + - '. It was called ' + - calls + - ' times.'; - return result; - } - }; - } - - return toHaveBeenCalledTimes; -}; + return toHaveBeenCalledTimes +} getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveBeenCalledWith(...arguments)' - ); + const getErrorMsg = j$.formatErrorMsg( + "", + "expect().toHaveBeenCalledWith(...arguments)" + ) - /** - * {@link expect} the actual (a {@link Spy}) to have been called with particular arguments at least once. - * @function - * @name matchers#toHaveBeenCalledWith - * @since 1.3.0 - * @param {...Object} - The arguments to look for - * @example - * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); - */ - function toHaveBeenCalledWith(matchersUtil) { - return { - compare: function() { - const args = Array.prototype.slice.call(arguments, 0), - actual = args[0], - expectedArgs = args.slice(1), - result = { pass: false }; + /** + * {@link expect} the actual (a {@link Spy}) to have been called with particular arguments at least once. + * @function + * @name matchers#toHaveBeenCalledWith + * @since 1.3.0 + * @param {...Object} - The arguments to look for + * @example + * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); + */ + function toHaveBeenCalledWith(matchersUtil) { + return { + compare: function() { + const args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1), + result = { pass: false } - if (!j$.isSpy(actual)) { - throw new Error( - getErrorMsg( - 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' - ) - ); + if (!j$.isSpy(actual)) { + throw new Error(getErrorMsg("Expected a spy, but got " + matchersUtil.pp(actual) + ".")) + } + + if (!actual.calls.any()) { + result.message = function() { + return ( + "Expected spy " + + actual.and.identity + + " to have been called with:\n" + + " " + + matchersUtil.pp(expectedArgs) + + "\nbut it was never called." + ) + } + return result + } + + if (matchersUtil.contains(actual.calls.allArgs(), expectedArgs)) { + result.pass = true + result.message = function() { + return ( + "Expected spy " + + actual.and.identity + + " not to have been called with:\n" + + " " + + matchersUtil.pp(expectedArgs) + + "\nbut it was." + ) + } + } else { + result.message = function() { + const prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) { + return " " + matchersUtil.pp(argsForCall) + }) + + const diffs = actual.calls.allArgs().map(function(argsForCall, callIx) { + const diffBuilder = new j$.DiffBuilder() + matchersUtil.equals(argsForCall, expectedArgs, diffBuilder) + return "Call " + callIx + ":\n" + diffBuilder.getMessage().replace(/^/gm, " ") + }) + + return ( + "Expected spy " + + actual.and.identity + + " to have been called with:\n" + + " " + + matchersUtil.pp(expectedArgs) + + "\n" + + "" + + "but actual calls were:\n" + + prettyPrintedCalls.join(",\n") + + ".\n\n" + + diffs.join("\n") + ) + } + } + + return result + }, } + } - if (!actual.calls.any()) { - result.message = function() { - return ( - 'Expected spy ' + - actual.and.identity + - ' to have been called with:\n' + - ' ' + - matchersUtil.pp(expectedArgs) + - '\nbut it was never called.' - ); - }; - return result; - } - - if (matchersUtil.contains(actual.calls.allArgs(), expectedArgs)) { - result.pass = true; - result.message = function() { - return ( - 'Expected spy ' + - actual.and.identity + - ' not to have been called with:\n' + - ' ' + - matchersUtil.pp(expectedArgs) + - '\nbut it was.' - ); - }; - } else { - result.message = function() { - const prettyPrintedCalls = actual.calls - .allArgs() - .map(function(argsForCall) { - return ' ' + matchersUtil.pp(argsForCall); - }); - - const diffs = actual.calls - .allArgs() - .map(function(argsForCall, callIx) { - const diffBuilder = new j$.DiffBuilder(); - matchersUtil.equals(argsForCall, expectedArgs, diffBuilder); - return ( - 'Call ' + - callIx + - ':\n' + - diffBuilder.getMessage().replace(/^/gm, ' ') - ); - }); - - return ( - 'Expected spy ' + - actual.and.identity + - ' to have been called with:\n' + - ' ' + - matchersUtil.pp(expectedArgs) + - '\n' + - '' + - 'but actual calls were:\n' + - prettyPrintedCalls.join(',\n') + - '.\n\n' + - diffs.join('\n') - ); - }; - } - - return result; - } - }; - } - - return toHaveBeenCalledWith; -}; + return toHaveBeenCalledWith +} getJasmineRequireObj().toHaveClass = function(j$) { - /** - * {@link expect} the actual value to be a DOM element that has the expected class - * @function - * @name matchers#toHaveClass - * @since 3.0.0 - * @param {Object} expected - The class name to test for - * @example - * const el = document.createElement('div'); - * el.className = 'foo bar baz'; - * expect(el).toHaveClass('bar'); - */ - function toHaveClass(matchersUtil) { - return { - compare: function(actual, expected) { - if (!isElement(actual)) { - throw new Error(matchersUtil.pp(actual) + ' is not a DOM element'); - } - + /** + * {@link expect} the actual value to be a DOM element that has the expected class + * @function + * @name matchers#toHaveClass + * @since 3.0.0 + * @param {Object} expected - The class name to test for + * @example + * const el = document.createElement('div'); + * el.className = 'foo bar baz'; + * expect(el).toHaveClass('bar'); + */ + function toHaveClass(matchersUtil) { return { - pass: actual.classList.contains(expected) - }; - } - }; - } + compare: function(actual, expected) { + if (!isElement(actual)) { + throw new Error(matchersUtil.pp(actual) + " is not a DOM element") + } - function isElement(maybeEl) { - return ( - maybeEl && maybeEl.classList && j$.isFunction_(maybeEl.classList.contains) - ); - } + return { + pass: actual.classList.contains(expected), + } + }, + } + } - return toHaveClass; -}; + function isElement(maybeEl) { + return maybeEl && maybeEl.classList && j$.isFunction_(maybeEl.classList.contains) + } + + return toHaveClass +} getJasmineRequireObj().toHaveSize = function(j$) { - /** - * {@link expect} the actual size to be equal to the expected, using array-like length or object keys size. - * @function - * @name matchers#toHaveSize - * @since 3.6.0 - * @param {Object} expected - Expected size - * @example - * array = [1,2]; - * expect(array).toHaveSize(2); - */ - function toHaveSize() { - return { - compare: function(actual, expected) { - const result = { - pass: false - }; + /** + * {@link expect} the actual size to be equal to the expected, using array-like length or object keys size. + * @function + * @name matchers#toHaveSize + * @since 3.6.0 + * @param {Object} expected - Expected size + * @example + * array = [1,2]; + * expect(array).toHaveSize(2); + */ + function toHaveSize() { + return { + compare: function(actual, expected) { + const result = { + pass: false, + } - if ( - j$.isA_('WeakSet', actual) || - j$.isWeakMap(actual) || - j$.isDataView(actual) - ) { - throw new Error('Cannot get size of ' + actual + '.'); + if (j$.isA_("WeakSet", actual) || j$.isWeakMap(actual) || j$.isDataView(actual)) { + throw new Error("Cannot get size of " + actual + ".") + } + + if (j$.isSet(actual) || j$.isMap(actual)) { + result.pass = actual.size === expected + } else if (isLength(actual.length)) { + result.pass = actual.length === expected + } else { + result.pass = Object.keys(actual).length === expected + } + + return result + }, } + } - if (j$.isSet(actual) || j$.isMap(actual)) { - result.pass = actual.size === expected; - } else if (isLength(actual.length)) { - result.pass = actual.length === expected; - } else { - result.pass = Object.keys(actual).length === expected; - } + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991 + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER + } - return result; - } - }; - } - - const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - function isLength(value) { - return ( - typeof value == 'number' && - value > -1 && - value % 1 === 0 && - value <= MAX_SAFE_INTEGER - ); - } - - return toHaveSize; -}; + return toHaveSize +} getJasmineRequireObj().toHaveSpyInteractions = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toHaveSpyInteractions()' - ); + const getErrorMsg = j$.formatErrorMsg("", "expect().toHaveSpyInteractions()") - /** - * {@link expect} the actual (a {@link SpyObj}) spies to have been called. - * @function - * @name matchers#toHaveSpyInteractions - * @since 4.1.0 - * @example - * expect(mySpyObj).toHaveSpyInteractions(); - * expect(mySpyObj).not.toHaveSpyInteractions(); - */ - function toHaveSpyInteractions(matchersUtil) { - return { - compare: function(actual) { - const result = {}; + /** + * {@link expect} the actual (a {@link SpyObj}) spies to have been called. + * @function + * @name matchers#toHaveSpyInteractions + * @since 4.1.0 + * @example + * expect(mySpyObj).toHaveSpyInteractions(); + * expect(mySpyObj).not.toHaveSpyInteractions(); + */ + function toHaveSpyInteractions(matchersUtil) { + return { + compare: function(actual) { + const result = {} - if (!j$.isObject_(actual)) { - throw new Error( - getErrorMsg('Expected a spy object, but got ' + typeof actual + '.') - ); + if (!j$.isObject_(actual)) { + throw new Error(getErrorMsg("Expected a spy object, but got " + typeof actual + ".")) + } + + if (arguments.length > 1) { + throw new Error(getErrorMsg("Does not take arguments")) + } + + result.pass = false + let hasSpy = false + const calledSpies = [] + for (const spy of Object.values(actual)) { + if (!j$.isSpy(spy)) continue + hasSpy = true + + if (spy.calls.any()) { + result.pass = true + calledSpies.push([spy.and.identity, spy.calls.count()]) + } + } + + if (!hasSpy) { + throw new Error(getErrorMsg("Expected a spy object with spies, but object has no spies.")) + } + + let resultMessage + if (result.pass) { + resultMessage = + "Expected spy object spies not to have been called, " + "but the following spies were called: " + resultMessage += calledSpies + .map(([spyName, spyCount]) => { + return `${spyName} called ${spyCount} time(s)` + }) + .join(", ") + } else { + resultMessage = "Expected spy object spies to have been called, " + "but no spies were called." + } + result.message = resultMessage + + return result + }, } + } - if (arguments.length > 1) { - throw new Error(getErrorMsg('Does not take arguments')); - } - - result.pass = false; - let hasSpy = false; - const calledSpies = []; - for (const spy of Object.values(actual)) { - if (!j$.isSpy(spy)) continue; - hasSpy = true; - - if (spy.calls.any()) { - result.pass = true; - calledSpies.push([spy.and.identity, spy.calls.count()]); - } - } - - if (!hasSpy) { - throw new Error( - getErrorMsg( - 'Expected a spy object with spies, but object has no spies.' - ) - ); - } - - let resultMessage; - if (result.pass) { - resultMessage = - 'Expected spy object spies not to have been called, ' + - 'but the following spies were called: '; - resultMessage += calledSpies - .map(([spyName, spyCount]) => { - return `${spyName} called ${spyCount} time(s)`; - }) - .join(', '); - } else { - resultMessage = - 'Expected spy object spies to have been called, ' + - 'but no spies were called.'; - } - result.message = resultMessage; - - return result; - } - }; - } - - return toHaveSpyInteractions; -}; + return toHaveSpyInteractions +} getJasmineRequireObj().toMatch = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect().toMatch( || )' - ); - - /** - * {@link expect} the actual value to match a regular expression - * @function - * @name matchers#toMatch - * @since 1.3.0 - * @param {RegExp|String} expected - Value to look for in the string. - * @example - * expect("my string").toMatch(/string$/); - * expect("other string").toMatch("her"); - */ - function toMatch() { - return { - compare: function(actual, expected) { - if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { - throw new Error(getErrorMsg('Expected is not a String or a RegExp')); - } - - const regexp = new RegExp(expected); + const getErrorMsg = j$.formatErrorMsg("", "expect().toMatch( || )") + /** + * {@link expect} the actual value to match a regular expression + * @function + * @name matchers#toMatch + * @since 1.3.0 + * @param {RegExp|String} expected - Value to look for in the string. + * @example + * expect("my string").toMatch(/string$/); + * expect("other string").toMatch("her"); + */ + function toMatch() { return { - pass: regexp.test(actual) - }; - } - }; - } + compare: function(actual, expected) { + if (!j$.isString_(expected) && !j$.isA_("RegExp", expected)) { + throw new Error(getErrorMsg("Expected is not a String or a RegExp")) + } - return toMatch; -}; + const regexp = new RegExp(expected) + + return { + pass: regexp.test(actual), + } + }, + } + } + + return toMatch +} getJasmineRequireObj().toThrow = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect(function() {}).toThrow()' - ); + const getErrorMsg = j$.formatErrorMsg("", "expect(function() {}).toThrow()") - /** - * {@link expect} a function to `throw` something. - * @function - * @name matchers#toThrow - * @since 2.0.0 - * @param {Object} [expected] - Value that should be thrown. If not provided, simply the fact that something was thrown will be checked. - * @example - * expect(function() { return 'things'; }).toThrow('foo'); - * expect(function() { return 'stuff'; }).toThrow(); - */ - function toThrow(matchersUtil) { - return { - compare: function(actual, expected) { - const result = { pass: false }; - let threw = false; - let thrown; + /** + * {@link expect} a function to `throw` something. + * @function + * @name matchers#toThrow + * @since 2.0.0 + * @param {Object} [expected] - Value that should be thrown. If not provided, simply the fact that something was thrown will be checked. + * @example + * expect(function() { return 'things'; }).toThrow('foo'); + * expect(function() { return 'stuff'; }).toThrow(); + */ + function toThrow(matchersUtil) { + return { + compare: function(actual, expected) { + const result = { pass: false } + let threw = false + let thrown - if (typeof actual != 'function') { - throw new Error(getErrorMsg('Actual is not a Function')); + if (typeof actual != "function") { + throw new Error(getErrorMsg("Actual is not a Function")) + } + + try { + actual() + } catch (e) { + threw = true + thrown = e + } + + if (!threw) { + result.message = "Expected function to throw an exception." + return result + } + + if (arguments.length == 1) { + result.pass = true + result.message = function() { + return "Expected function not to throw, but it threw " + matchersUtil.pp(thrown) + "." + } + + return result + } + + if (matchersUtil.equals(thrown, expected)) { + result.pass = true + result.message = function() { + return "Expected function not to throw " + matchersUtil.pp(expected) + "." + } + } else { + result.message = function() { + return ( + "Expected function to throw " + + matchersUtil.pp(expected) + + ", but it threw " + + matchersUtil.pp(thrown) + + "." + ) + } + } + + return result + }, } + } - try { - actual(); - } catch (e) { - threw = true; - thrown = e; - } - - if (!threw) { - result.message = 'Expected function to throw an exception.'; - return result; - } - - if (arguments.length == 1) { - result.pass = true; - result.message = function() { - return ( - 'Expected function not to throw, but it threw ' + - matchersUtil.pp(thrown) + - '.' - ); - }; - - return result; - } - - if (matchersUtil.equals(thrown, expected)) { - result.pass = true; - result.message = function() { - return ( - 'Expected function not to throw ' + - matchersUtil.pp(expected) + - '.' - ); - }; - } else { - result.message = function() { - return ( - 'Expected function to throw ' + - matchersUtil.pp(expected) + - ', but it threw ' + - matchersUtil.pp(thrown) + - '.' - ); - }; - } - - return result; - } - }; - } - - return toThrow; -}; + return toThrow +} getJasmineRequireObj().toThrowError = function(j$) { - const getErrorMsg = j$.formatErrorMsg( - '', - 'expect(function() {}).toThrowError(, )' - ); + const getErrorMsg = j$.formatErrorMsg( + "", + "expect(function() {}).toThrowError(, )" + ) - /** - * {@link expect} a function to `throw` an `Error`. - * @function - * @name matchers#toThrowError - * @since 2.0.0 - * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. - * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` - * @example - * expect(function() { return 'things'; }).toThrowError(MyCustomError, 'message'); - * expect(function() { return 'things'; }).toThrowError(MyCustomError, /bar/); - * expect(function() { return 'stuff'; }).toThrowError(MyCustomError); - * expect(function() { return 'other'; }).toThrowError(/foo/); - * expect(function() { return 'other'; }).toThrowError(); - */ - function toThrowError(matchersUtil) { - return { - compare: function(actual) { - const errorMatcher = getMatcher.apply(null, arguments); + /** + * {@link expect} a function to `throw` an `Error`. + * @function + * @name matchers#toThrowError + * @since 2.0.0 + * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. + * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` + * @example + * expect(function() { return 'things'; }).toThrowError(MyCustomError, 'message'); + * expect(function() { return 'things'; }).toThrowError(MyCustomError, /bar/); + * expect(function() { return 'stuff'; }).toThrowError(MyCustomError); + * expect(function() { return 'other'; }).toThrowError(/foo/); + * expect(function() { return 'other'; }).toThrowError(); + */ + function toThrowError(matchersUtil) { + return { + compare: function(actual) { + const errorMatcher = getMatcher.apply(null, arguments) - if (typeof actual != 'function') { - throw new Error(getErrorMsg('Actual is not a Function')); + if (typeof actual != "function") { + throw new Error(getErrorMsg("Actual is not a Function")) + } + + let thrown + + try { + actual() + return fail("Expected function to throw an Error.") + } catch (e) { + thrown = e + } + + if (!j$.isError_(thrown)) { + return fail(function() { + return "Expected function to throw an Error, but it threw " + matchersUtil.pp(thrown) + "." + }) + } + + return errorMatcher.match(thrown) + }, } - let thrown; + function getMatcher() { + let expected, errorType - try { - actual(); - return fail('Expected function to throw an Error.'); - } catch (e) { - thrown = e; + if (arguments[2]) { + errorType = arguments[1] + expected = arguments[2] + if (!isAnErrorType(errorType)) { + throw new Error(getErrorMsg("Expected error type is not an Error.")) + } + + return exactMatcher(expected, errorType) + } else if (arguments[1]) { + expected = arguments[1] + + if (isAnErrorType(arguments[1])) { + return exactMatcher(null, arguments[1]) + } else { + return exactMatcher(arguments[1], null) + } + } else { + return anyMatcher() + } } - if (!j$.isError_(thrown)) { - return fail(function() { - return ( - 'Expected function to throw an Error, but it threw ' + - matchersUtil.pp(thrown) + - '.' - ); - }); + function anyMatcher() { + return { + match: function(error) { + return pass("Expected function not to throw an Error, but it threw " + j$.fnNameFor(error) + ".") + }, + } } - return errorMatcher.match(thrown); - } - }; + function exactMatcher(expected, errorType) { + if (expected && !isStringOrRegExp(expected)) { + if (errorType) { + throw new Error(getErrorMsg("Expected error message is not a string or RegExp.")) + } else { + throw new Error(getErrorMsg("Expected is not an Error, string, or RegExp.")) + } + } - function getMatcher() { - let expected, errorType; + function messageMatch(message) { + if (typeof expected == "string") { + return expected == message + } else { + return expected.test(message) + } + } - if (arguments[2]) { - errorType = arguments[1]; - expected = arguments[2]; - if (!isAnErrorType(errorType)) { - throw new Error(getErrorMsg('Expected error type is not an Error.')); + const errorTypeDescription = errorType ? j$.fnNameFor(errorType) : "an exception" + + function thrownDescription(thrown) { + const thrownName = errorType ? j$.fnNameFor(thrown.constructor) : "an exception" + let thrownMessage = "" + + if (expected) { + thrownMessage = " with message " + matchersUtil.pp(thrown.message) + } + + return thrownName + thrownMessage + } + + function messageDescription() { + if (expected === null) { + return "" + } else if (expected instanceof RegExp) { + return " with a message matching " + matchersUtil.pp(expected) + } else { + return " with message " + matchersUtil.pp(expected) + } + } + + function matches(error) { + return ( + (errorType === null || error instanceof errorType) && + (expected === null || messageMatch(error.message)) + ) + } + + return { + match: function(thrown) { + if (matches(thrown)) { + return pass(function() { + return "Expected function not to throw " + errorTypeDescription + messageDescription() + "." + }) + } else { + return fail(function() { + return ( + "Expected function to throw " + + errorTypeDescription + + messageDescription() + + ", but it threw " + + thrownDescription(thrown) + + "." + ) + }) + } + }, + } } - return exactMatcher(expected, errorType); - } else if (arguments[1]) { - expected = arguments[1]; - - if (isAnErrorType(arguments[1])) { - return exactMatcher(null, arguments[1]); - } else { - return exactMatcher(arguments[1], null); + function isStringOrRegExp(potential) { + return potential instanceof RegExp || typeof potential == "string" + } + + function isAnErrorType(type) { + if (typeof type !== "function") { + return false + } + + const Surrogate = function() {} + Surrogate.prototype = type.prototype + return j$.isError_(new Surrogate()) } - } else { - return anyMatcher(); - } } - function anyMatcher() { - return { - match: function(error) { - return pass( - 'Expected function not to throw an Error, but it threw ' + - j$.fnNameFor(error) + - '.' - ); + function pass(message) { + return { + pass: true, + message: message, } - }; } - function exactMatcher(expected, errorType) { - if (expected && !isStringOrRegExp(expected)) { - if (errorType) { - throw new Error( - getErrorMsg('Expected error message is not a string or RegExp.') - ); - } else { - throw new Error( - getErrorMsg('Expected is not an Error, string, or RegExp.') - ); + function fail(message) { + return { + pass: false, + message: message, } - } - - function messageMatch(message) { - if (typeof expected == 'string') { - return expected == message; - } else { - return expected.test(message); - } - } - - const errorTypeDescription = errorType - ? j$.fnNameFor(errorType) - : 'an exception'; - - function thrownDescription(thrown) { - const thrownName = errorType - ? j$.fnNameFor(thrown.constructor) - : 'an exception'; - let thrownMessage = ''; - - if (expected) { - thrownMessage = ' with message ' + matchersUtil.pp(thrown.message); - } - - return thrownName + thrownMessage; - } - - function messageDescription() { - if (expected === null) { - return ''; - } else if (expected instanceof RegExp) { - return ' with a message matching ' + matchersUtil.pp(expected); - } else { - return ' with message ' + matchersUtil.pp(expected); - } - } - - function matches(error) { - return ( - (errorType === null || error instanceof errorType) && - (expected === null || messageMatch(error.message)) - ); - } - - return { - match: function(thrown) { - if (matches(thrown)) { - return pass(function() { - return ( - 'Expected function not to throw ' + - errorTypeDescription + - messageDescription() + - '.' - ); - }); - } else { - return fail(function() { - return ( - 'Expected function to throw ' + - errorTypeDescription + - messageDescription() + - ', but it threw ' + - thrownDescription(thrown) + - '.' - ); - }); - } - } - }; } - function isStringOrRegExp(potential) { - return potential instanceof RegExp || typeof potential == 'string'; - } - - function isAnErrorType(type) { - if (typeof type !== 'function') { - return false; - } - - const Surrogate = function() {}; - Surrogate.prototype = type.prototype; - return j$.isError_(new Surrogate()); - } - } - - function pass(message) { - return { - pass: true, - message: message - }; - } - - function fail(message) { - return { - pass: false, - message: message - }; - } - - return toThrowError; -}; + return toThrowError +} getJasmineRequireObj().toThrowMatching = function(j$) { - const usageError = j$.formatErrorMsg( - '', - 'expect(function() {}).toThrowMatching()' - ); + const usageError = j$.formatErrorMsg( + "", + "expect(function() {}).toThrowMatching()" + ) - /** - * {@link expect} a function to `throw` something matching a predicate. - * @function - * @name matchers#toThrowMatching - * @since 3.0.0 - * @param {Function} predicate - A function that takes the thrown exception as its parameter and returns true if it matches. - * @example - * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); - */ - function toThrowMatching(matchersUtil) { - return { - compare: function(actual, predicate) { - if (typeof actual !== 'function') { - throw new Error(usageError('Actual is not a Function')); + /** + * {@link expect} a function to `throw` something matching a predicate. + * @function + * @name matchers#toThrowMatching + * @since 3.0.0 + * @param {Function} predicate - A function that takes the thrown exception as its parameter and returns true if it matches. + * @example + * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); + */ + function toThrowMatching(matchersUtil) { + return { + compare: function(actual, predicate) { + if (typeof actual !== "function") { + throw new Error(usageError("Actual is not a Function")) + } + + if (typeof predicate !== "function") { + throw new Error(usageError("Predicate is not a Function")) + } + + let thrown + + try { + actual() + return fail("Expected function to throw an exception.") + } catch (e) { + thrown = e + } + + if (predicate(thrown)) { + return pass("Expected function not to throw an exception matching a predicate.") + } else { + return fail(function() { + return ( + "Expected function to throw an exception matching a predicate, " + + "but it threw " + + thrownDescription(thrown) + + "." + ) + }) + } + }, } - if (typeof predicate !== 'function') { - throw new Error(usageError('Predicate is not a Function')); + function thrownDescription(thrown) { + if (thrown && thrown.constructor) { + return j$.fnNameFor(thrown.constructor) + " with message " + matchersUtil.pp(thrown.message) + } else { + return matchersUtil.pp(thrown) + } } - - let thrown; - - try { - actual(); - return fail('Expected function to throw an exception.'); - } catch (e) { - thrown = e; - } - - if (predicate(thrown)) { - return pass( - 'Expected function not to throw an exception matching a predicate.' - ); - } else { - return fail(function() { - return ( - 'Expected function to throw an exception matching a predicate, ' + - 'but it threw ' + - thrownDescription(thrown) + - '.' - ); - }); - } - } - }; - - function thrownDescription(thrown) { - if (thrown && thrown.constructor) { - return ( - j$.fnNameFor(thrown.constructor) + - ' with message ' + - matchersUtil.pp(thrown.message) - ); - } else { - return matchersUtil.pp(thrown); - } } - } - function pass(message) { - return { - pass: true, - message: message - }; - } + function pass(message) { + return { + pass: true, + message: message, + } + } - function fail(message) { - return { - pass: false, - message: message - }; - } + function fail(message) { + return { + pass: false, + message: message, + } + } - return toThrowMatching; -}; + return toThrowMatching +} getJasmineRequireObj().MockDate = function(j$) { - function MockDate(global) { - let currentTime = 0; + function MockDate(global) { + let currentTime = 0 - if (!global || !global.Date) { - this.install = function() {}; - this.tick = function() {}; - this.uninstall = function() {}; - return this; - } - - const GlobalDate = global.Date; - - this.install = function(mockDate) { - if (mockDate instanceof GlobalDate) { - currentTime = mockDate.getTime(); - } else { - if (!j$.util.isUndefined(mockDate)) { - throw new Error( - 'The argument to jasmine.clock().mockDate(), if specified, ' + - 'should be a Date instance.' - ); + if (!global || !global.Date) { + this.install = function() {} + this.tick = function() {} + this.uninstall = function() {} + return this } - currentTime = new GlobalDate().getTime(); - } + const GlobalDate = global.Date - global.Date = FakeDate; - }; + this.install = function(mockDate) { + if (mockDate instanceof GlobalDate) { + currentTime = mockDate.getTime() + } else { + if (!j$.util.isUndefined(mockDate)) { + throw new Error( + "The argument to jasmine.clock().mockDate(), if specified, " + "should be a Date instance." + ) + } - this.tick = function(millis) { - millis = millis || 0; - currentTime = currentTime + millis; - }; + currentTime = new GlobalDate().getTime() + } - this.uninstall = function() { - currentTime = 0; - global.Date = GlobalDate; - }; + global.Date = FakeDate + } - createDateProperties(); + this.tick = function(millis) { + millis = millis || 0 + currentTime = currentTime + millis + } - return this; + this.uninstall = function() { + currentTime = 0 + global.Date = GlobalDate + } - function FakeDate() { - switch (arguments.length) { - case 0: - return new GlobalDate(currentTime); - case 1: - return new GlobalDate(arguments[0]); - case 2: - return new GlobalDate(arguments[0], arguments[1]); - case 3: - return new GlobalDate(arguments[0], arguments[1], arguments[2]); - case 4: - return new GlobalDate( - arguments[0], - arguments[1], - arguments[2], - arguments[3] - ); - case 5: - return new GlobalDate( - arguments[0], - arguments[1], - arguments[2], - arguments[3], - arguments[4] - ); - case 6: - return new GlobalDate( - arguments[0], - arguments[1], - arguments[2], - arguments[3], - arguments[4], - arguments[5] - ); - default: - return new GlobalDate( - arguments[0], - arguments[1], - arguments[2], - arguments[3], - arguments[4], - arguments[5], - arguments[6] - ); - } + createDateProperties() + + return this + + function FakeDate() { + switch (arguments.length) { + case 0: + return new GlobalDate(currentTime) + case 1: + return new GlobalDate(arguments[0]) + case 2: + return new GlobalDate(arguments[0], arguments[1]) + case 3: + return new GlobalDate(arguments[0], arguments[1], arguments[2]) + case 4: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]) + case 5: + return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]) + case 6: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5] + ) + default: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5], + arguments[6] + ) + } + } + + function createDateProperties() { + FakeDate.prototype = GlobalDate.prototype + + FakeDate.now = function() { + return currentTime + } + + FakeDate.toSource = GlobalDate.toSource + FakeDate.toString = GlobalDate.toString + FakeDate.parse = GlobalDate.parse + FakeDate.UTC = GlobalDate.UTC + } } - function createDateProperties() { - FakeDate.prototype = GlobalDate.prototype; - - FakeDate.now = function() { - return currentTime; - }; - - FakeDate.toSource = GlobalDate.toSource; - FakeDate.toString = GlobalDate.toString; - FakeDate.parse = GlobalDate.parse; - FakeDate.UTC = GlobalDate.UTC; - } - } - - return MockDate; -}; + return MockDate +} getJasmineRequireObj().NeverSkipPolicy = function(j$) { - function NeverSkipPolicy(queueableFns) {} + function NeverSkipPolicy(queueableFns) {} - NeverSkipPolicy.prototype.skipTo = function(lastRanFnIx) { - return lastRanFnIx + 1; - }; + NeverSkipPolicy.prototype.skipTo = function(lastRanFnIx) { + return lastRanFnIx + 1 + } - NeverSkipPolicy.prototype.fnErrored = function(fnIx) {}; + NeverSkipPolicy.prototype.fnErrored = function(fnIx) {} - return NeverSkipPolicy; -}; + return NeverSkipPolicy +} getJasmineRequireObj().makePrettyPrinter = function(j$) { - class SinglePrettyPrintRun { - constructor(customObjectFormatters, pp) { - this.customObjectFormatters_ = customObjectFormatters; - this.ppNestLevel_ = 0; - this.seen = []; - this.length = 0; - this.stringParts = []; - this.pp_ = pp; - } - - format(value) { - this.ppNestLevel_++; - try { - const customFormatResult = this.applyCustomFormatters_(value); - - if (customFormatResult) { - this.emitScalar(customFormatResult); - } else if (j$.util.isUndefined(value)) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === 0 && 1 / value === -Infinity) { - this.emitScalar('-0'); - } else if (value === j$.getGlobal()) { - this.emitScalar(''); - } else if (value.jasmineToString) { - this.emitScalar(value.jasmineToString(this.pp_)); - } else if (j$.isString_(value)) { - this.emitString(value); - } else if (j$.isSpy(value)) { - this.emitScalar('spy on ' + value.and.identity); - } else if (j$.isSpy(value.toString)) { - this.emitScalar('spy on ' + value.toString.and.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (j$.isDomNode(value)) { - if (value.tagName) { - this.emitDomElement(value); - } else { - this.emitScalar('HTMLNode'); - } - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (j$.isSet(value)) { - this.emitSet(value); - } else if (j$.isMap(value)) { - this.emitMap(value); - } else if (j$.isTypedArray_(value)) { - this.emitTypedArray(value); - } else if ( - value.toString && - typeof value === 'object' && - !j$.isArray_(value) && - hasCustomToString(value) - ) { - try { - this.emitScalar(value.toString()); - } catch (e) { - this.emitScalar('has-invalid-toString-method'); - } - } else if (this.seen.includes(value)) { - this.emitScalar( - '' - ); - } else if (j$.isArray_(value) || j$.isA_('Object', value)) { - this.seen.push(value); - if (j$.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - this.seen.pop(); - } else { - this.emitScalar(value.toString()); - } - } catch (e) { - if (this.ppNestLevel_ > 1 || !(e instanceof MaxCharsReachedError)) { - throw e; - } - } finally { - this.ppNestLevel_--; - } - } - - applyCustomFormatters_(value) { - return customFormat(value, this.customObjectFormatters_); - } - - iterateObject(obj, fn) { - const objKeys = j$.MatchersUtil.keys(obj, j$.isArray_(obj)); - const length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); - - for (let i = 0; i < length; i++) { - fn(objKeys[i]); - } - - return objKeys.length > length; - } - - emitScalar(value) { - this.append(value); - } - - emitString(value) { - this.append("'" + value + "'"); - } - - emitArray(array) { - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - this.append('Array'); - return; - } - - const length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); - this.append('[ '); - - for (let i = 0; i < length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - if (array.length > length) { - this.append(', ...'); - } - - let first = array.length === 0; - const wasTruncated = this.iterateObject(array, property => { - if (first) { - first = false; - } else { - this.append(', '); + class SinglePrettyPrintRun { + constructor(customObjectFormatters, pp) { + this.customObjectFormatters_ = customObjectFormatters + this.ppNestLevel_ = 0 + this.seen = [] + this.length = 0 + this.stringParts = [] + this.pp_ = pp } - this.formatProperty(array, property); - }); + format(value) { + this.ppNestLevel_++ + try { + const customFormatResult = this.applyCustomFormatters_(value) - if (wasTruncated) { - this.append(', ...'); - } - - this.append(' ]'); - } - - emitSet(set) { - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - this.append('Set'); - return; - } - this.append('Set( '); - const size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); - let i = 0; - set.forEach(function(value, key) { - if (i >= size) { - return; - } - if (i > 0) { - this.append(', '); - } - this.format(value); - - i++; - }, this); - if (set.size > size) { - this.append(', ...'); - } - this.append(' )'); - } - - emitMap(map) { - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - this.append('Map'); - return; - } - this.append('Map( '); - const size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); - let i = 0; - map.forEach(function(value, key) { - if (i >= size) { - return; - } - if (i > 0) { - this.append(', '); - } - this.format([key, value]); - - i++; - }, this); - if (map.size > size) { - this.append(', ...'); - } - this.append(' )'); - } - - emitObject(obj) { - const ctor = obj.constructor; - const constructorName = - typeof ctor === 'function' && obj instanceof ctor - ? j$.fnNameFor(obj.constructor) - : 'null'; - - this.append(constructorName); - - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - return; - } - - this.append('({ '); - let first = true; - - const wasTruncated = this.iterateObject(obj, property => { - if (first) { - first = false; - } else { - this.append(', '); + if (customFormatResult) { + this.emitScalar(customFormatResult) + } else if (j$.util.isUndefined(value)) { + this.emitScalar("undefined") + } else if (value === null) { + this.emitScalar("null") + } else if (value === 0 && 1 / value === -Infinity) { + this.emitScalar("-0") + } else if (value === j$.getGlobal()) { + this.emitScalar("") + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString(this.pp_)) + } else if (j$.isString_(value)) { + this.emitString(value) + } else if (j$.isSpy(value)) { + this.emitScalar("spy on " + value.and.identity) + } else if (j$.isSpy(value.toString)) { + this.emitScalar("spy on " + value.toString.and.identity) + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()) + } else if (typeof value === "function") { + this.emitScalar("Function") + } else if (j$.isDomNode(value)) { + if (value.tagName) { + this.emitDomElement(value) + } else { + this.emitScalar("HTMLNode") + } + } else if (value instanceof Date) { + this.emitScalar("Date(" + value + ")") + } else if (j$.isSet(value)) { + this.emitSet(value) + } else if (j$.isMap(value)) { + this.emitMap(value) + } else if (j$.isTypedArray_(value)) { + this.emitTypedArray(value) + } else if ( + value.toString && + typeof value === "object" && + !j$.isArray_(value) && + hasCustomToString(value) + ) { + try { + this.emitScalar(value.toString()) + } catch (e) { + this.emitScalar("has-invalid-toString-method") + } + } else if (this.seen.includes(value)) { + this.emitScalar("") + } else if (j$.isArray_(value) || j$.isA_("Object", value)) { + this.seen.push(value) + if (j$.isArray_(value)) { + this.emitArray(value) + } else { + this.emitObject(value) + } + this.seen.pop() + } else { + this.emitScalar(value.toString()) + } + } catch (e) { + if (this.ppNestLevel_ > 1 || !(e instanceof MaxCharsReachedError)) { + throw e + } + } finally { + this.ppNestLevel_-- + } } - this.formatProperty(obj, property); - }); - - if (wasTruncated) { - this.append(', ...'); - } - - this.append(' })'); - } - - emitTypedArray(arr) { - const constructorName = j$.fnNameFor(arr.constructor); - const limitedArray = Array.prototype.slice.call( - arr, - 0, - j$.MAX_PRETTY_PRINT_ARRAY_LENGTH - ); - let itemsString = Array.prototype.join.call(limitedArray, ', '); - - if (limitedArray.length !== arr.length) { - itemsString += ', ...'; - } - - this.append(constructorName + ' [ ' + itemsString + ' ]'); - } - - emitDomElement(el) { - const tagName = el.tagName.toLowerCase(); - let out = '<' + tagName; - - for (const attr of el.attributes) { - out += ' ' + attr.name; - - if (attr.value !== '') { - out += '="' + attr.value + '"'; + applyCustomFormatters_(value) { + return customFormat(value, this.customObjectFormatters_) } - } - out += '>'; + iterateObject(obj, fn) { + const objKeys = j$.MatchersUtil.keys(obj, j$.isArray_(obj)) + const length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH) - if (el.childElementCount !== 0 || el.textContent !== '') { - out += '...'; - } + for (let i = 0; i < length; i++) { + fn(objKeys[i]) + } - this.append(out); + return objKeys.length > length + } + + emitScalar(value) { + this.append(value) + } + + emitString(value) { + this.append("'" + value + "'") + } + + emitArray(array) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append("Array") + return + } + + const length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH) + this.append("[ ") + + for (let i = 0; i < length; i++) { + if (i > 0) { + this.append(", ") + } + this.format(array[i]) + } + if (array.length > length) { + this.append(", ...") + } + + let first = array.length === 0 + const wasTruncated = this.iterateObject(array, (property) => { + if (first) { + first = false + } else { + this.append(", ") + } + + this.formatProperty(array, property) + }) + + if (wasTruncated) { + this.append(", ...") + } + + this.append(" ]") + } + + emitSet(set) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append("Set") + return + } + this.append("Set( ") + const size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH) + let i = 0 + set.forEach(function(value, key) { + if (i >= size) { + return + } + if (i > 0) { + this.append(", ") + } + this.format(value) + + i++ + }, this) + if (set.size > size) { + this.append(", ...") + } + this.append(" )") + } + + emitMap(map) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append("Map") + return + } + this.append("Map( ") + const size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH) + let i = 0 + map.forEach(function(value, key) { + if (i >= size) { + return + } + if (i > 0) { + this.append(", ") + } + this.format([key, value]) + + i++ + }, this) + if (map.size > size) { + this.append(", ...") + } + this.append(" )") + } + + emitObject(obj) { + const ctor = obj.constructor + const constructorName = + typeof ctor === "function" && obj instanceof ctor ? j$.fnNameFor(obj.constructor) : "null" + + this.append(constructorName) + + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + return + } + + this.append("({ ") + let first = true + + const wasTruncated = this.iterateObject(obj, (property) => { + if (first) { + first = false + } else { + this.append(", ") + } + + this.formatProperty(obj, property) + }) + + if (wasTruncated) { + this.append(", ...") + } + + this.append(" })") + } + + emitTypedArray(arr) { + const constructorName = j$.fnNameFor(arr.constructor) + const limitedArray = Array.prototype.slice.call(arr, 0, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH) + let itemsString = Array.prototype.join.call(limitedArray, ", ") + + if (limitedArray.length !== arr.length) { + itemsString += ", ..." + } + + this.append(constructorName + " [ " + itemsString + " ]") + } + + emitDomElement(el) { + const tagName = el.tagName.toLowerCase() + let out = "<" + tagName + + for (const attr of el.attributes) { + out += " " + attr.name + + if (attr.value !== "") { + out += '="' + attr.value + '"' + } + } + + out += ">" + + if (el.childElementCount !== 0 || el.textContent !== "") { + out += "..." + } + + this.append(out) + } + + formatProperty(obj, property) { + if (typeof property === "symbol") { + this.append(property.toString()) + } else { + this.append(property) + } + + this.append(": ") + this.format(obj[property]) + } + + append(value) { + // This check protects us from the rare case where an object has overriden + // `toString()` with an invalid implementation (returning a non-string). + if (typeof value !== "string") { + value = Object.prototype.toString.call(value) + } + + const result = truncate(value, j$.MAX_PRETTY_PRINT_CHARS - this.length) + this.length += result.value.length + this.stringParts.push(result.value) + + if (result.truncated) { + throw new MaxCharsReachedError() + } + } } - formatProperty(obj, property) { - if (typeof property === 'symbol') { - this.append(property.toString()); - } else { - this.append(property); - } - - this.append(': '); - this.format(obj[property]); + function hasCustomToString(value) { + // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. + // iframe, web worker) + try { + return ( + j$.isFunction_(value.toString) && + value.toString !== Object.prototype.toString && + value.toString() !== Object.prototype.toString.call(value) + ) + } catch (e) { + // The custom toString() threw. + return true + } } - append(value) { - // This check protects us from the rare case where an object has overriden - // `toString()` with an invalid implementation (returning a non-string). - if (typeof value !== 'string') { - value = Object.prototype.toString.call(value); - } + function truncate(s, maxlen) { + if (s.length <= maxlen) { + return { value: s, truncated: false } + } - const result = truncate(value, j$.MAX_PRETTY_PRINT_CHARS - this.length); - this.length += result.value.length; - this.stringParts.push(result.value); - - if (result.truncated) { - throw new MaxCharsReachedError(); - } - } - } - - function hasCustomToString(value) { - // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. - // iframe, web worker) - try { - return ( - j$.isFunction_(value.toString) && - value.toString !== Object.prototype.toString && - value.toString() !== Object.prototype.toString.call(value) - ); - } catch (e) { - // The custom toString() threw. - return true; - } - } - - function truncate(s, maxlen) { - if (s.length <= maxlen) { - return { value: s, truncated: false }; + s = s.substring(0, maxlen - 4) + " ..." + return { value: s, truncated: true } } - s = s.substring(0, maxlen - 4) + ' ...'; - return { value: s, truncated: true }; - } - - function MaxCharsReachedError() { - this.message = - 'Exceeded ' + - j$.MAX_PRETTY_PRINT_CHARS + - ' characters while pretty-printing a value'; - } - - MaxCharsReachedError.prototype = new Error(); - - function customFormat(value, customObjectFormatters) { - for (const formatter of customObjectFormatters) { - const result = formatter(value); - - if (result !== undefined) { - return result; - } + function MaxCharsReachedError() { + this.message = "Exceeded " + j$.MAX_PRETTY_PRINT_CHARS + " characters while pretty-printing a value" } - } - return function(customObjectFormatters) { - customObjectFormatters = customObjectFormatters || []; + MaxCharsReachedError.prototype = new Error() - const pp = function(value) { - const prettyPrinter = new SinglePrettyPrintRun( - customObjectFormatters, - pp - ); - prettyPrinter.format(value); - return prettyPrinter.stringParts.join(''); - }; + function customFormat(value, customObjectFormatters) { + for (const formatter of customObjectFormatters) { + const result = formatter(value) - pp.customFormat_ = function(value) { - return customFormat(value, customObjectFormatters); - }; + if (result !== undefined) { + return result + } + } + } - return pp; - }; -}; + return function(customObjectFormatters) { + customObjectFormatters = customObjectFormatters || [] + + const pp = function(value) { + const prettyPrinter = new SinglePrettyPrintRun(customObjectFormatters, pp) + prettyPrinter.format(value) + return prettyPrinter.stringParts.join("") + } + + pp.customFormat_ = function(value) { + return customFormat(value, customObjectFormatters) + } + + return pp + } +} getJasmineRequireObj().QueueRunner = function(j$) { - let nextid = 1; + let nextid = 1 - function StopExecutionError() {} - StopExecutionError.prototype = new Error(); - j$.StopExecutionError = StopExecutionError; + function StopExecutionError() {} + StopExecutionError.prototype = new Error() + j$.StopExecutionError = StopExecutionError - function once(fn, onTwice) { - let called = false; - return function(arg) { - if (called) { - if (onTwice) { - onTwice(); + function once(fn, onTwice) { + let called = false + return function(arg) { + if (called) { + if (onTwice) { + onTwice() + } + } else { + called = true + // Direct call using single parameter, because cleanup/next does not need more + fn(arg) + } + return null } - } else { - called = true; - // Direct call using single parameter, because cleanup/next does not need more - fn(arg); - } - return null; - }; - } - - function fallbackOnMultipleDone() { - console.error( - new Error( - "An asynchronous function called its 'done' " + - 'callback more than once, in a QueueRunner without a onMultipleDone ' + - 'handler.' - ) - ); - } - - function emptyFn() {} - - function QueueRunner(attrs) { - this.id_ = nextid++; - this.queueableFns = attrs.queueableFns || []; - this.onComplete = attrs.onComplete || emptyFn; - this.clearStack = - attrs.clearStack || - function(fn) { - fn(); - }; - this.onException = attrs.onException || emptyFn; - this.onMultipleDone = attrs.onMultipleDone || fallbackOnMultipleDone; - this.userContext = attrs.userContext || new j$.UserContext(); - this.timeout = attrs.timeout || { - setTimeout: setTimeout, - clearTimeout: clearTimeout - }; - this.fail = attrs.fail || emptyFn; - this.globalErrors = attrs.globalErrors || { - pushListener: emptyFn, - popListener: emptyFn - }; - - const SkipPolicy = attrs.SkipPolicy || j$.NeverSkipPolicy; - this.skipPolicy_ = new SkipPolicy(this.queueableFns); - this.errored_ = false; - - if (typeof this.onComplete !== 'function') { - throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); } - this.deprecated = attrs.deprecated; - } - QueueRunner.prototype.execute = function() { - this.handleFinalError = (message, source, lineno, colno, error) => { - // Older browsers would send the error as the first parameter. HTML5 - // specifies the the five parameters above. The error instance should - // be preffered, otherwise the call stack would get lost. - this.onException(error || message); - }; - this.globalErrors.pushListener(this.handleFinalError); - this.run(0); - }; - - QueueRunner.prototype.clearTimeout = function(timeoutId) { - Function.prototype.apply.apply(this.timeout.clearTimeout, [ - j$.getGlobal(), - [timeoutId] - ]); - }; - - QueueRunner.prototype.setTimeout = function(fn, timeout) { - return Function.prototype.apply.apply(this.timeout.setTimeout, [ - j$.getGlobal(), - [fn, timeout] - ]); - }; - - QueueRunner.prototype.attempt = function attempt(iterativeIndex) { - let timeoutId; - let timedOut; - let completedSynchronously = true; - - const onException = e => { - this.onException(e); - this.recordError_(iterativeIndex); - }; - - function handleError(error) { - // TODO probably shouldn't next() right away here. - // That makes debugging async failures much more confusing. - onException(error); + function fallbackOnMultipleDone() { + console.error( + new Error( + "An asynchronous function called its 'done' " + + "callback more than once, in a QueueRunner without a onMultipleDone " + + "handler." + ) + ) } - const cleanup = once(() => { - if (timeoutId !== void 0) { - this.clearTimeout(timeoutId); - } - this.globalErrors.popListener(handleError); - }); - const next = once( - err => { - cleanup(); - if (typeof err !== 'undefined') { - if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { - this.fail(err); - } - this.recordError_(iterativeIndex); + function emptyFn() {} + + function QueueRunner(attrs) { + this.id_ = nextid++ + this.queueableFns = attrs.queueableFns || [] + this.onComplete = attrs.onComplete || emptyFn + this.clearStack = + attrs.clearStack || + function(fn) { + fn() + } + this.onException = attrs.onException || emptyFn + this.onMultipleDone = attrs.onMultipleDone || fallbackOnMultipleDone + this.userContext = attrs.userContext || new j$.UserContext() + this.timeout = attrs.timeout || { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + } + this.fail = attrs.fail || emptyFn + this.globalErrors = attrs.globalErrors || { + pushListener: emptyFn, + popListener: emptyFn, } - const runNext = () => { - this.run(this.nextFnIx_(iterativeIndex)); - }; + const SkipPolicy = attrs.SkipPolicy || j$.NeverSkipPolicy + this.skipPolicy_ = new SkipPolicy(this.queueableFns) + this.errored_ = false - if (completedSynchronously) { - this.setTimeout(runNext); - } else { - runNext(); + if (typeof this.onComplete !== "function") { + throw new Error("invalid onComplete " + JSON.stringify(this.onComplete)) } - }, - () => { + this.deprecated = attrs.deprecated + } + + QueueRunner.prototype.execute = function() { + this.handleFinalError = (message, source, lineno, colno, error) => { + // Older browsers would send the error as the first parameter. HTML5 + // specifies the the five parameters above. The error instance should + // be preffered, otherwise the call stack would get lost. + this.onException(error || message) + } + this.globalErrors.pushListener(this.handleFinalError) + this.run(0) + } + + QueueRunner.prototype.clearTimeout = function(timeoutId) { + Function.prototype.apply.apply(this.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]) + } + + QueueRunner.prototype.setTimeout = function(fn, timeout) { + return Function.prototype.apply.apply(this.timeout.setTimeout, [j$.getGlobal(), [fn, timeout]]) + } + + QueueRunner.prototype.attempt = function attempt(iterativeIndex) { + let timeoutId + let timedOut + let completedSynchronously = true + + const onException = (e) => { + this.onException(e) + this.recordError_(iterativeIndex) + } + + function handleError(error) { + // TODO probably shouldn't next() right away here. + // That makes debugging async failures much more confusing. + onException(error) + } + const cleanup = once(() => { + if (timeoutId !== void 0) { + this.clearTimeout(timeoutId) + } + this.globalErrors.popListener(handleError) + }) + const next = once( + (err) => { + cleanup() + + if (typeof err !== "undefined") { + if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { + this.fail(err) + } + this.recordError_(iterativeIndex) + } + + const runNext = () => { + this.run(this.nextFnIx_(iterativeIndex)) + } + + if (completedSynchronously) { + this.setTimeout(runNext) + } else { + runNext() + } + }, + () => { + try { + if (!timedOut) { + this.onMultipleDone() + } + } catch (error) { + // Any error we catch here is probably due to a bug in Jasmine, + // and it's not likely to end up anywhere useful if we let it + // propagate. Log it so it can at least show up when debugging. + console.error(error) + } + } + ) + timedOut = false + const queueableFn = this.queueableFns[iterativeIndex] + + next.fail = function nextFail() { + this.fail.apply(null, arguments) + this.recordError_(iterativeIndex) + next() + }.bind(this) + + this.globalErrors.pushListener(handleError) + + if (queueableFn.timeout !== undefined) { + const timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL + timeoutId = this.setTimeout(function() { + timedOut = true + const error = new Error( + "Timeout - Async function did not complete within " + + timeoutInterval + + "ms " + + (queueableFn.timeout ? "(custom timeout)" : "(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)") + ) + // TODO Need to decide what to do about a successful completion after a + // timeout. That should probably not be a deprecation, and maybe not + // an error in 4.0. (But a diagnostic of some sort might be helpful.) + onException(error) + next() + }, timeoutInterval) + } + try { - if (!timedOut) { - this.onMultipleDone(); - } - } catch (error) { - // Any error we catch here is probably due to a bug in Jasmine, - // and it's not likely to end up anywhere useful if we let it - // propagate. Log it so it can at least show up when debugging. - console.error(error); + let maybeThenable + + if (queueableFn.fn.length === 0) { + maybeThenable = queueableFn.fn.call(this.userContext) + + if (maybeThenable && j$.isFunction_(maybeThenable.then)) { + maybeThenable.then(wrapInPromiseResolutionHandler(next), onPromiseRejection) + completedSynchronously = false + return { completedSynchronously: false } + } + } else { + maybeThenable = queueableFn.fn.call(this.userContext, next) + this.diagnoseConflictingAsync_(queueableFn.fn, maybeThenable) + completedSynchronously = false + return { completedSynchronously: false } + } + } catch (e) { + onException(e) + this.recordError_(iterativeIndex) } - } - ); - timedOut = false; - const queueableFn = this.queueableFns[iterativeIndex]; - next.fail = function nextFail() { - this.fail.apply(null, arguments); - this.recordError_(iterativeIndex); - next(); - }.bind(this); + cleanup() + return { completedSynchronously: true } - this.globalErrors.pushListener(handleError); - - if (queueableFn.timeout !== undefined) { - const timeoutInterval = - queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; - timeoutId = this.setTimeout(function() { - timedOut = true; - const error = new Error( - 'Timeout - Async function did not complete within ' + - timeoutInterval + - 'ms ' + - (queueableFn.timeout - ? '(custom timeout)' - : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') - ); - // TODO Need to decide what to do about a successful completion after a - // timeout. That should probably not be a deprecation, and maybe not - // an error in 4.0. (But a diagnostic of some sort might be helpful.) - onException(error); - next(); - }, timeoutInterval); - } - - try { - let maybeThenable; - - if (queueableFn.fn.length === 0) { - maybeThenable = queueableFn.fn.call(this.userContext); - - if (maybeThenable && j$.isFunction_(maybeThenable.then)) { - maybeThenable.then( - wrapInPromiseResolutionHandler(next), - onPromiseRejection - ); - completedSynchronously = false; - return { completedSynchronously: false }; + function onPromiseRejection(e) { + onException(e) + next() } - } else { - maybeThenable = queueableFn.fn.call(this.userContext, next); - this.diagnoseConflictingAsync_(queueableFn.fn, maybeThenable); - completedSynchronously = false; - return { completedSynchronously: false }; - } - } catch (e) { - onException(e); - this.recordError_(iterativeIndex); } - cleanup(); - return { completedSynchronously: true }; + QueueRunner.prototype.run = function(recursiveIndex) { + const length = this.queueableFns.length - function onPromiseRejection(e) { - onException(e); - next(); - } - }; + for ( + let iterativeIndex = recursiveIndex; + iterativeIndex < length; + iterativeIndex = this.nextFnIx_(iterativeIndex) + ) { + const result = this.attempt(iterativeIndex) - QueueRunner.prototype.run = function(recursiveIndex) { - const length = this.queueableFns.length; + if (!result.completedSynchronously) { + return + } + } - for ( - let iterativeIndex = recursiveIndex; - iterativeIndex < length; - iterativeIndex = this.nextFnIx_(iterativeIndex) - ) { - const result = this.attempt(iterativeIndex); + this.clearStack(() => { + this.globalErrors.popListener(this.handleFinalError) - if (!result.completedSynchronously) { - return; - } + if (this.errored_) { + this.onComplete(new StopExecutionError()) + } else { + this.onComplete() + } + }) } - this.clearStack(() => { - this.globalErrors.popListener(this.handleFinalError); + QueueRunner.prototype.nextFnIx_ = function(currentFnIx) { + const result = this.skipPolicy_.skipTo(currentFnIx) - if (this.errored_) { - this.onComplete(new StopExecutionError()); - } else { - this.onComplete(); - } - }); - }; + if (result === currentFnIx) { + throw new Error("Can't skip to the same queueable fn that just finished") + } - QueueRunner.prototype.nextFnIx_ = function(currentFnIx) { - const result = this.skipPolicy_.skipTo(currentFnIx); - - if (result === currentFnIx) { - throw new Error("Can't skip to the same queueable fn that just finished"); + return result } - return result; - }; - - QueueRunner.prototype.recordError_ = function(currentFnIx) { - this.errored_ = true; - this.skipPolicy_.fnErrored(currentFnIx); - }; - - QueueRunner.prototype.diagnoseConflictingAsync_ = function(fn, retval) { - if (retval && j$.isFunction_(retval.then)) { - // Issue a warning that matches the user's code. - // Omit the stack trace because there's almost certainly no user code - // on the stack at this point. - if (j$.isAsyncFunction_(fn)) { - this.onException( - 'An asynchronous before/it/after ' + - 'function was defined with the async keyword but also took a ' + - 'done callback. Either remove the done callback (recommended) or ' + - 'remove the async keyword.' - ); - } else { - this.onException( - 'An asynchronous before/it/after ' + - 'function took a done callback but also returned a promise. ' + - 'Either remove the done callback (recommended) or change the ' + - 'function to not return a promise.' - ); - } + QueueRunner.prototype.recordError_ = function(currentFnIx) { + this.errored_ = true + this.skipPolicy_.fnErrored(currentFnIx) } - }; - function wrapInPromiseResolutionHandler(fn) { - return function(maybeArg) { - if (j$.isError_(maybeArg)) { - fn(maybeArg); - } else { - fn(); - } - }; - } + QueueRunner.prototype.diagnoseConflictingAsync_ = function(fn, retval) { + if (retval && j$.isFunction_(retval.then)) { + // Issue a warning that matches the user's code. + // Omit the stack trace because there's almost certainly no user code + // on the stack at this point. + if (j$.isAsyncFunction_(fn)) { + this.onException( + "An asynchronous before/it/after " + + "function was defined with the async keyword but also took a " + + "done callback. Either remove the done callback (recommended) or " + + "remove the async keyword." + ) + } else { + this.onException( + "An asynchronous before/it/after " + + "function took a done callback but also returned a promise. " + + "Either remove the done callback (recommended) or change the " + + "function to not return a promise." + ) + } + } + } - return QueueRunner; -}; + function wrapInPromiseResolutionHandler(fn) { + return function(maybeArg) { + if (j$.isError_(maybeArg)) { + fn(maybeArg) + } else { + fn() + } + } + } + + return QueueRunner +} getJasmineRequireObj().ReportDispatcher = function(j$) { - function ReportDispatcher(methods, queueRunnerFactory, onLateError) { - const dispatchedMethods = methods || []; + function ReportDispatcher(methods, queueRunnerFactory, onLateError) { + const dispatchedMethods = methods || [] - for (const method of dispatchedMethods) { - this[method] = (function(m) { - return function() { - return dispatch(m, arguments); - }; - })(method); + for (const method of dispatchedMethods) { + this[method] = (function(m) { + return function() { + return dispatch(m, arguments) + } + })(method) + } + + let reporters = [] + let fallbackReporter = null + + this.addReporter = function(reporter) { + reporters.push(reporter) + } + + this.provideFallbackReporter = function(reporter) { + fallbackReporter = reporter + } + + this.clearReporters = function() { + reporters = [] + } + + return this + + function dispatch(method, args) { + if (reporters.length === 0 && fallbackReporter !== null) { + reporters.push(fallbackReporter) + } + const fns = [] + for (const reporter of reporters) { + addFn(fns, reporter, method, args) + } + + return new Promise(function(resolve) { + queueRunnerFactory({ + queueableFns: fns, + onComplete: resolve, + isReporter: true, + onMultipleDone: function() { + onLateError( + new Error( + "An asynchronous reporter callback called its 'done' callback " + "more than once." + ) + ) + }, + }) + }) + } + + function addFn(fns, reporter, method, args) { + const fn = reporter[method] + if (!fn) { + return + } + + const thisArgs = j$.util.cloneArgs(args) + if (fn.length <= 1) { + fns.push({ + fn: function() { + return fn.apply(reporter, thisArgs) + }, + }) + } else { + fns.push({ + fn: function(done) { + return fn.apply(reporter, thisArgs.concat([done])) + }, + }) + } + } } - let reporters = []; - let fallbackReporter = null; - - this.addReporter = function(reporter) { - reporters.push(reporter); - }; - - this.provideFallbackReporter = function(reporter) { - fallbackReporter = reporter; - }; - - this.clearReporters = function() { - reporters = []; - }; - - return this; - - function dispatch(method, args) { - if (reporters.length === 0 && fallbackReporter !== null) { - reporters.push(fallbackReporter); - } - const fns = []; - for (const reporter of reporters) { - addFn(fns, reporter, method, args); - } - - return new Promise(function(resolve) { - queueRunnerFactory({ - queueableFns: fns, - onComplete: resolve, - isReporter: true, - onMultipleDone: function() { - onLateError( - new Error( - "An asynchronous reporter callback called its 'done' callback " + - 'more than once.' - ) - ); - } - }); - }); - } - - function addFn(fns, reporter, method, args) { - const fn = reporter[method]; - if (!fn) { - return; - } - - const thisArgs = j$.util.cloneArgs(args); - if (fn.length <= 1) { - fns.push({ - fn: function() { - return fn.apply(reporter, thisArgs); - } - }); - } else { - fns.push({ - fn: function(done) { - return fn.apply(reporter, thisArgs.concat([done])); - } - }); - } - } - } - - return ReportDispatcher; -}; + return ReportDispatcher +} getJasmineRequireObj().interface = function(jasmine, env) { - const jasmineInterface = { + const jasmineInterface = { + /** + * Callback passed to parts of the Jasmine base interface. + * + * By default Jasmine assumes this function completes synchronously. + * If you have code that you need to test asynchronously, you can declare that you receive a `done` callback, return a Promise, or use the `async` keyword if it is supported in your environment. + * @callback implementationCallback + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + */ + + /** + * Create a group of specs (often called a suite). + * + * Calls to `describe` can be nested within other calls to compose your suite as a tree. + * @name describe + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + describe: function(description, specDefinitions) { + return env.describe(description, specDefinitions) + }, + + /** + * A temporarily disabled [`describe`]{@link describe} + * + * Specs within an `xdescribe` will be marked pending and not executed + * @name xdescribe + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + xdescribe: function(description, specDefinitions) { + return env.xdescribe(description, specDefinitions) + }, + + /** + * A focused [`describe`]{@link describe} + * + * If suites or specs are focused, only those that are focused will be executed + * @see fit + * @name fdescribe + * @since 2.1.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + fdescribe: function(description, specDefinitions) { + return env.fdescribe(description, specDefinitions) + }, + + /** + * Define a single spec. A spec should contain one or more {@link expect|expectations} that test the state of the code. + * + * A spec whose expectations all succeed will be passing and a spec with any failures will fail. + * The name `it` is a pronoun for the test target, not an abbreviation of anything. It makes the + * spec more readable by connecting the function name `it` and the argument `description` as a + * complete sentence. + * @name it + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking + * @param {implementationCallback} [testFunction] Function that contains the code of your test. If not provided the test will be `pending`. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. + * @see async + */ + it: function() { + return env.it.apply(env, arguments) + }, + + /** + * A temporarily disabled [`it`]{@link it} + * + * The spec will report as `pending` and will not be executed. + * @name xit + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking. + * @param {implementationCallback} [testFunction] Function that contains the code of your test. Will not be executed. + */ + xit: function() { + return env.xit.apply(env, arguments) + }, + + /** + * A focused [`it`]{@link it} + * + * If suites or specs are focused, only those that are focused will be executed. + * @name fit + * @since 2.1.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking. + * @param {implementationCallback} testFunction Function that contains the code of your test. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. + * @see async + */ + fit: function() { + return env.fit.apply(env, arguments) + }, + + /** + * Run some shared setup before each of the specs in the {@link describe} in which it is called. + * @name beforeEach + * @since 1.3.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to setup your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeEach. + * @see async + */ + beforeEach: function() { + return env.beforeEach.apply(env, arguments) + }, + + /** + * Run some shared teardown after each of the specs in the {@link describe} in which it is called. + * @name afterEach + * @since 1.3.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to teardown your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterEach. + * @see async + */ + afterEach: function() { + return env.afterEach.apply(env, arguments) + }, + + /** + * Run some shared setup once before all of the specs in the {@link describe} are run. + * + * _Note:_ Be careful, sharing the setup from a beforeAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @name beforeAll + * @since 2.1.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to setup your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeAll. + * @see async + */ + beforeAll: function() { + return env.beforeAll.apply(env, arguments) + }, + + /** + * Run some shared teardown once after all of the specs in the {@link describe} are run. + * + * _Note:_ Be careful, sharing the teardown from a afterAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @name afterAll + * @since 2.1.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to teardown your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterAll. + * @see async + */ + afterAll: function() { + return env.afterAll.apply(env, arguments) + }, + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} + * @name setSpecProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + setSpecProperty: function(key, value) { + return env.setSpecProperty(key, value) + }, + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} + * @name setSuiteProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + setSuiteProperty: function(key, value) { + return env.setSuiteProperty(key, value) + }, + + /** + * Create an expectation for a spec. + * @name expect + * @since 1.3.0 + * @function + * @global + * @param {Object} actual - Actual computed value to test expectations against. + * @return {matchers} + */ + expect: function(actual) { + return env.expect(actual) + }, + + /** + * Create an asynchronous expectation for a spec. Note that the matchers + * that are provided by an asynchronous expectation all return promises + * which must be either returned from the spec or waited for using `await` + * in order for Jasmine to associate them with the correct spec. + * @name expectAsync + * @since 3.3.0 + * @function + * @global + * @param {Object} actual - Actual computed value to test expectations against. + * @return {async-matchers} + * @example + * await expectAsync(somePromise).toBeResolved(); + * @example + * return expectAsync(somePromise).toBeResolved(); + */ + expectAsync: function(actual) { + return env.expectAsync(actual) + }, + + /** + * Mark a spec as pending, expectation results will be ignored. + * @name pending + * @since 2.0.0 + * @function + * @global + * @param {String} [message] - Reason the spec is pending. + */ + pending: function() { + return env.pending.apply(env, arguments) + }, + + /** + * Explicitly mark a spec as failed. + * @name fail + * @since 2.1.0 + * @function + * @global + * @param {String|Error} [error] - Reason for the failure. + */ + fail: function() { + return env.fail.apply(env, arguments) + }, + + /** + * Install a spy onto an existing object. + * @name spyOn + * @since 1.3.0 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy}. + * @param {String} methodName - The name of the method to replace with a {@link Spy}. + * @returns {Spy} + */ + spyOn: function(obj, methodName) { + return env.spyOn(obj, methodName) + }, + + /** + * Install a spy on a property installed with `Object.defineProperty` onto an existing object. + * @name spyOnProperty + * @since 2.6.0 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy} + * @param {String} propertyName - The name of the property to replace with a {@link Spy}. + * @param {String} [accessType=get] - The access type (get|set) of the property to {@link Spy} on. + * @returns {Spy} + */ + spyOnProperty: function(obj, methodName, accessType) { + return env.spyOnProperty(obj, methodName, accessType) + }, + + /** + * Installs spies on all writable and configurable properties of an object. + * @name spyOnAllFunctions + * @since 3.2.1 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy}s + * @param {boolean} includeNonEnumerable - Whether or not to add spies to non-enumerable properties + * @returns {Object} the spied object + */ + spyOnAllFunctions: function(obj, includeNonEnumerable) { + return env.spyOnAllFunctions(obj, includeNonEnumerable) + }, + + jsApiReporter: new jasmine.JsApiReporter({ + timer: new jasmine.Timer(), + }), + + /** + * @namespace jasmine + */ + jasmine: jasmine, + } + /** - * Callback passed to parts of the Jasmine base interface. + * Add a custom equality tester for the current scope of specs. * - * By default Jasmine assumes this function completes synchronously. - * If you have code that you need to test asynchronously, you can declare that you receive a `done` callback, return a Promise, or use the `async` keyword if it is supported in your environment. - * @callback implementationCallback - * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. - * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. - */ - - /** - * Create a group of specs (often called a suite). - * - * Calls to `describe` can be nested within other calls to compose your suite as a tree. - * @name describe - * @since 1.3.0 - * @function - * @global - * @param {String} description Textual description of the group - * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs - */ - describe: function(description, specDefinitions) { - return env.describe(description, specDefinitions); - }, - - /** - * A temporarily disabled [`describe`]{@link describe} - * - * Specs within an `xdescribe` will be marked pending and not executed - * @name xdescribe - * @since 1.3.0 - * @function - * @global - * @param {String} description Textual description of the group - * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs - */ - xdescribe: function(description, specDefinitions) { - return env.xdescribe(description, specDefinitions); - }, - - /** - * A focused [`describe`]{@link describe} - * - * If suites or specs are focused, only those that are focused will be executed - * @see fit - * @name fdescribe - * @since 2.1.0 - * @function - * @global - * @param {String} description Textual description of the group - * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs - */ - fdescribe: function(description, specDefinitions) { - return env.fdescribe(description, specDefinitions); - }, - - /** - * Define a single spec. A spec should contain one or more {@link expect|expectations} that test the state of the code. - * - * A spec whose expectations all succeed will be passing and a spec with any failures will fail. - * The name `it` is a pronoun for the test target, not an abbreviation of anything. It makes the - * spec more readable by connecting the function name `it` and the argument `description` as a - * complete sentence. - * @name it - * @since 1.3.0 - * @function - * @global - * @param {String} description Textual description of what this spec is checking - * @param {implementationCallback} [testFunction] Function that contains the code of your test. If not provided the test will be `pending`. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. - * @see async - */ - it: function() { - return env.it.apply(env, arguments); - }, - - /** - * A temporarily disabled [`it`]{@link it} - * - * The spec will report as `pending` and will not be executed. - * @name xit - * @since 1.3.0 - * @function - * @global - * @param {String} description Textual description of what this spec is checking. - * @param {implementationCallback} [testFunction] Function that contains the code of your test. Will not be executed. - */ - xit: function() { - return env.xit.apply(env, arguments); - }, - - /** - * A focused [`it`]{@link it} - * - * If suites or specs are focused, only those that are focused will be executed. - * @name fit - * @since 2.1.0 - * @function - * @global - * @param {String} description Textual description of what this spec is checking. - * @param {implementationCallback} testFunction Function that contains the code of your test. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. - * @see async - */ - fit: function() { - return env.fit.apply(env, arguments); - }, - - /** - * Run some shared setup before each of the specs in the {@link describe} in which it is called. - * @name beforeEach - * @since 1.3.0 - * @function - * @global - * @param {implementationCallback} [function] Function that contains the code to setup your specs. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeEach. - * @see async - */ - beforeEach: function() { - return env.beforeEach.apply(env, arguments); - }, - - /** - * Run some shared teardown after each of the specs in the {@link describe} in which it is called. - * @name afterEach - * @since 1.3.0 - * @function - * @global - * @param {implementationCallback} [function] Function that contains the code to teardown your specs. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterEach. - * @see async - */ - afterEach: function() { - return env.afterEach.apply(env, arguments); - }, - - /** - * Run some shared setup once before all of the specs in the {@link describe} are run. - * - * _Note:_ Be careful, sharing the setup from a beforeAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. - * @name beforeAll - * @since 2.1.0 - * @function - * @global - * @param {implementationCallback} [function] Function that contains the code to setup your specs. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeAll. - * @see async - */ - beforeAll: function() { - return env.beforeAll.apply(env, arguments); - }, - - /** - * Run some shared teardown once after all of the specs in the {@link describe} are run. - * - * _Note:_ Be careful, sharing the teardown from a afterAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. - * @name afterAll - * @since 2.1.0 - * @function - * @global - * @param {implementationCallback} [function] Function that contains the code to teardown your specs. - * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterAll. - * @see async - */ - afterAll: function() { - return env.afterAll.apply(env, arguments); - }, - - /** - * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} - * @name setSpecProperty - * @since 3.6.0 - * @function - * @param {String} key The name of the property - * @param {*} value The value of the property - */ - setSpecProperty: function(key, value) { - return env.setSpecProperty(key, value); - }, - - /** - * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} - * @name setSuiteProperty - * @since 3.6.0 - * @function - * @param {String} key The name of the property - * @param {*} value The value of the property - */ - setSuiteProperty: function(key, value) { - return env.setSuiteProperty(key, value); - }, - - /** - * Create an expectation for a spec. - * @name expect - * @since 1.3.0 - * @function - * @global - * @param {Object} actual - Actual computed value to test expectations against. - * @return {matchers} - */ - expect: function(actual) { - return env.expect(actual); - }, - - /** - * Create an asynchronous expectation for a spec. Note that the matchers - * that are provided by an asynchronous expectation all return promises - * which must be either returned from the spec or waited for using `await` - * in order for Jasmine to associate them with the correct spec. - * @name expectAsync - * @since 3.3.0 - * @function - * @global - * @param {Object} actual - Actual computed value to test expectations against. - * @return {async-matchers} - * @example - * await expectAsync(somePromise).toBeResolved(); - * @example - * return expectAsync(somePromise).toBeResolved(); - */ - expectAsync: function(actual) { - return env.expectAsync(actual); - }, - - /** - * Mark a spec as pending, expectation results will be ignored. - * @name pending + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addCustomEqualityTester * @since 2.0.0 * @function - * @global - * @param {String} [message] - Reason the spec is pending. + * @param {Function} tester - A function which takes two arguments to compare and returns a `true` or `false` comparison result if it knows how to compare them, and `undefined` otherwise. + * @see custom_equality */ - pending: function() { - return env.pending.apply(env, arguments); - }, + jasmine.addCustomEqualityTester = function(tester) { + env.addCustomEqualityTester(tester) + } /** - * Explicitly mark a spec as failed. - * @name fail - * @since 2.1.0 + * Add custom matchers for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addMatchers + * @since 2.0.0 * @function - * @global - * @param {String|Error} [error] - Reason for the failure. + * @param {Object} matchers - Keys from this object will be the new matcher names. + * @see custom_matcher */ - fail: function() { - return env.fail.apply(env, arguments); - }, + jasmine.addMatchers = function(matchers) { + return env.addMatchers(matchers) + } /** - * Install a spy onto an existing object. - * @name spyOn + * Add custom async matchers for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addAsyncMatchers + * @since 3.5.0 + * @function + * @param {Object} matchers - Keys from this object will be the new async matcher names. + * @see custom_matcher + */ + jasmine.addAsyncMatchers = function(matchers) { + return env.addAsyncMatchers(matchers) + } + + /** + * Add a custom object formatter for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addCustomObjectFormatter + * @since 3.6.0 + * @function + * @param {Function} formatter - A function which takes a value to format and returns a string if it knows how to format it, and `undefined` otherwise. + * @see custom_object_formatters + */ + jasmine.addCustomObjectFormatter = function(formatter) { + return env.addCustomObjectFormatter(formatter) + } + + /** + * Get the currently booted mock {Clock} for this Jasmine environment. + * @name jasmine.clock + * @since 2.0.0 + * @function + * @returns {Clock} + */ + jasmine.clock = function() { + return env.clock + } + + /** + * Create a bare {@link Spy} object. This won't be installed anywhere and will not have any implementation behind it. + * @name jasmine.createSpy * @since 1.3.0 * @function - * @global - * @param {Object} obj - The object upon which to install the {@link Spy}. - * @param {String} methodName - The name of the method to replace with a {@link Spy}. - * @returns {Spy} + * @param {String} [name] - Name to give the spy. This will be displayed in failure messages. + * @param {Function} [originalFn] - Function to act as the real implementation. + * @return {Spy} */ - spyOn: function(obj, methodName) { - return env.spyOn(obj, methodName); - }, + jasmine.createSpy = function(name, originalFn) { + return env.createSpy(name, originalFn) + } /** - * Install a spy on a property installed with `Object.defineProperty` onto an existing object. - * @name spyOnProperty - * @since 2.6.0 + * Create an object with multiple {@link Spy}s as its members. + * @name jasmine.createSpyObj + * @since 1.3.0 * @function - * @global - * @param {Object} obj - The object upon which to install the {@link Spy} - * @param {String} propertyName - The name of the property to replace with a {@link Spy}. - * @param {String} [accessType=get] - The access type (get|set) of the property to {@link Spy} on. - * @returns {Spy} + * @param {String} [baseName] - Base name for the spies in the object. + * @param {String[]|Object} methodNames - Array of method names to create spies for, or Object whose keys will be method names and values the {@link Spy#and#returnValue|returnValue}. + * @param {String[]|Object} [propertyNames] - Array of property names to create spies for, or Object whose keys will be propertynames and values the {@link Spy#and#returnValue|returnValue}. + * @return {Object} */ - spyOnProperty: function(obj, methodName, accessType) { - return env.spyOnProperty(obj, methodName, accessType); - }, + jasmine.createSpyObj = function(baseName, methodNames, propertyNames) { + return env.createSpyObj(baseName, methodNames, propertyNames) + } /** - * Installs spies on all writable and configurable properties of an object. - * @name spyOnAllFunctions - * @since 3.2.1 + * Add a custom spy strategy for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addSpyStrategy + * @since 3.5.0 * @function - * @global - * @param {Object} obj - The object upon which to install the {@link Spy}s - * @param {boolean} includeNonEnumerable - Whether or not to add spies to non-enumerable properties - * @returns {Object} the spied object + * @param {String} name - The name of the strategy (i.e. what you call from `and`) + * @param {Function} factory - Factory function that returns the plan to be executed. */ - spyOnAllFunctions: function(obj, includeNonEnumerable) { - return env.spyOnAllFunctions(obj, includeNonEnumerable); - }, - - jsApiReporter: new jasmine.JsApiReporter({ - timer: new jasmine.Timer() - }), + jasmine.addSpyStrategy = function(name, factory) { + return env.addSpyStrategy(name, factory) + } /** - * @namespace jasmine + * Set the default spy strategy for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.setDefaultSpyStrategy + * @function + * @param {Function} defaultStrategyFn - a function that assigns a strategy + * @example + * beforeEach(function() { + * jasmine.setDefaultSpyStrategy(and => and.returnValue(true)); + * }); */ - jasmine: jasmine - }; + jasmine.setDefaultSpyStrategy = function(defaultStrategyFn) { + return env.setDefaultSpyStrategy(defaultStrategyFn) + } - /** - * Add a custom equality tester for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.addCustomEqualityTester - * @since 2.0.0 - * @function - * @param {Function} tester - A function which takes two arguments to compare and returns a `true` or `false` comparison result if it knows how to compare them, and `undefined` otherwise. - * @see custom_equality - */ - jasmine.addCustomEqualityTester = function(tester) { - env.addCustomEqualityTester(tester); - }; - - /** - * Add custom matchers for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.addMatchers - * @since 2.0.0 - * @function - * @param {Object} matchers - Keys from this object will be the new matcher names. - * @see custom_matcher - */ - jasmine.addMatchers = function(matchers) { - return env.addMatchers(matchers); - }; - - /** - * Add custom async matchers for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.addAsyncMatchers - * @since 3.5.0 - * @function - * @param {Object} matchers - Keys from this object will be the new async matcher names. - * @see custom_matcher - */ - jasmine.addAsyncMatchers = function(matchers) { - return env.addAsyncMatchers(matchers); - }; - - /** - * Add a custom object formatter for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.addCustomObjectFormatter - * @since 3.6.0 - * @function - * @param {Function} formatter - A function which takes a value to format and returns a string if it knows how to format it, and `undefined` otherwise. - * @see custom_object_formatters - */ - jasmine.addCustomObjectFormatter = function(formatter) { - return env.addCustomObjectFormatter(formatter); - }; - - /** - * Get the currently booted mock {Clock} for this Jasmine environment. - * @name jasmine.clock - * @since 2.0.0 - * @function - * @returns {Clock} - */ - jasmine.clock = function() { - return env.clock; - }; - - /** - * Create a bare {@link Spy} object. This won't be installed anywhere and will not have any implementation behind it. - * @name jasmine.createSpy - * @since 1.3.0 - * @function - * @param {String} [name] - Name to give the spy. This will be displayed in failure messages. - * @param {Function} [originalFn] - Function to act as the real implementation. - * @return {Spy} - */ - jasmine.createSpy = function(name, originalFn) { - return env.createSpy(name, originalFn); - }; - - /** - * Create an object with multiple {@link Spy}s as its members. - * @name jasmine.createSpyObj - * @since 1.3.0 - * @function - * @param {String} [baseName] - Base name for the spies in the object. - * @param {String[]|Object} methodNames - Array of method names to create spies for, or Object whose keys will be method names and values the {@link Spy#and#returnValue|returnValue}. - * @param {String[]|Object} [propertyNames] - Array of property names to create spies for, or Object whose keys will be propertynames and values the {@link Spy#and#returnValue|returnValue}. - * @return {Object} - */ - jasmine.createSpyObj = function(baseName, methodNames, propertyNames) { - return env.createSpyObj(baseName, methodNames, propertyNames); - }; - - /** - * Add a custom spy strategy for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.addSpyStrategy - * @since 3.5.0 - * @function - * @param {String} name - The name of the strategy (i.e. what you call from `and`) - * @param {Function} factory - Factory function that returns the plan to be executed. - */ - jasmine.addSpyStrategy = function(name, factory) { - return env.addSpyStrategy(name, factory); - }; - - /** - * Set the default spy strategy for the current scope of specs. - * - * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. - * @name jasmine.setDefaultSpyStrategy - * @function - * @param {Function} defaultStrategyFn - a function that assigns a strategy - * @example - * beforeEach(function() { - * jasmine.setDefaultSpyStrategy(and => and.returnValue(true)); - * }); - */ - jasmine.setDefaultSpyStrategy = function(defaultStrategyFn) { - return env.setDefaultSpyStrategy(defaultStrategyFn); - }; - - return jasmineInterface; -}; + return jasmineInterface +} getJasmineRequireObj().RunableResources = function(j$) { - class RunableResources { - constructor(options) { - this.byRunableId_ = {}; - this.getCurrentRunableId_ = options.getCurrentRunableId; - this.globalErrors_ = options.globalErrors; + class RunableResources { + constructor(options) { + this.byRunableId_ = {} + this.getCurrentRunableId_ = options.getCurrentRunableId + this.globalErrors_ = options.globalErrors - this.spyFactory = new j$.SpyFactory( - () => { - if (this.getCurrentRunableId_()) { - return this.customSpyStrategies(); - } else { - return {}; - } - }, - () => this.defaultSpyStrategy(), - () => this.makeMatchersUtil() - ); + this.spyFactory = new j$.SpyFactory( + () => { + if (this.getCurrentRunableId_()) { + return this.customSpyStrategies() + } else { + return {} + } + }, + () => this.defaultSpyStrategy(), + () => this.makeMatchersUtil() + ) - this.spyRegistry = new j$.SpyRegistry({ - currentSpies: () => this.spies(), - createSpy: (name, originalFn) => - this.spyFactory.createSpy(name, originalFn) - }); - } - - initForRunable(runableId, parentId) { - const newRes = (this.byRunableId_[runableId] = { - customEqualityTesters: [], - customMatchers: {}, - customAsyncMatchers: {}, - customSpyStrategies: {}, - customObjectFormatters: [], - defaultSpyStrategy: undefined, - spies: [] - }); - - const parentRes = this.byRunableId_[parentId]; - - if (parentRes) { - newRes.defaultSpyStrategy = parentRes.defaultSpyStrategy; - const toClone = [ - 'customEqualityTesters', - 'customMatchers', - 'customAsyncMatchers', - 'customObjectFormatters', - 'customSpyStrategies' - ]; - - for (const k of toClone) { - newRes[k] = j$.util.clone(parentRes[k]); + this.spyRegistry = new j$.SpyRegistry({ + currentSpies: () => this.spies(), + createSpy: (name, originalFn) => this.spyFactory.createSpy(name, originalFn), + }) + } + + initForRunable(runableId, parentId) { + const newRes = (this.byRunableId_[runableId] = { + customEqualityTesters: [], + customMatchers: {}, + customAsyncMatchers: {}, + customSpyStrategies: {}, + customObjectFormatters: [], + defaultSpyStrategy: undefined, + spies: [], + }) + + const parentRes = this.byRunableId_[parentId] + + if (parentRes) { + newRes.defaultSpyStrategy = parentRes.defaultSpyStrategy + const toClone = [ + "customEqualityTesters", + "customMatchers", + "customAsyncMatchers", + "customObjectFormatters", + "customSpyStrategies", + ] + + for (const k of toClone) { + newRes[k] = j$.util.clone(parentRes[k]) + } + } + } + + clearForRunable(runableId) { + this.globalErrors_.removeOverrideListener() + this.spyRegistry.clearSpies() + delete this.byRunableId_[runableId] + } + + spies() { + return this.forCurrentRunable_("Spies must be created in a before function or a spec").spies + } + + defaultSpyStrategy() { + if (!this.getCurrentRunableId_()) { + return undefined + } + + return this.byRunableId_[this.getCurrentRunableId_()].defaultSpyStrategy + } + + setDefaultSpyStrategy(fn) { + this.forCurrentRunable_( + "Default spy strategy must be set in a before function or a spec" + ).defaultSpyStrategy = fn + } + + customSpyStrategies() { + return this.forCurrentRunable_("Custom spy strategies must be added in a before function or a spec") + .customSpyStrategies + } + + customEqualityTesters() { + return this.forCurrentRunable_("Custom Equalities must be added in a before function or a spec") + .customEqualityTesters + } + + customMatchers() { + return this.forCurrentRunable_("Matchers must be added in a before function or a spec").customMatchers + } + + addCustomMatchers(matchersToAdd) { + const matchers = this.customMatchers() + + for (const name in matchersToAdd) { + matchers[name] = matchersToAdd[name] + } + } + + customAsyncMatchers() { + return this.forCurrentRunable_("Async Matchers must be added in a before function or a spec") + .customAsyncMatchers + } + + addCustomAsyncMatchers(matchersToAdd) { + const matchers = this.customAsyncMatchers() + + for (const name in matchersToAdd) { + matchers[name] = matchersToAdd[name] + } + } + + customObjectFormatters() { + return this.forCurrentRunable_("Custom object formatters must be added in a before function or a spec") + .customObjectFormatters + } + + makePrettyPrinter() { + return j$.makePrettyPrinter(this.customObjectFormatters()) + } + + makeMatchersUtil() { + if (this.getCurrentRunableId_()) { + return new j$.MatchersUtil({ + customTesters: this.customEqualityTesters(), + pp: this.makePrettyPrinter(), + }) + } else { + return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }) + } + } + + forCurrentRunable_(errorMsg) { + const resources = this.byRunableId_[this.getCurrentRunableId_()] + + if (!resources && errorMsg) { + throw new Error(errorMsg) + } + + return resources } - } } - clearForRunable(runableId) { - this.globalErrors_.removeOverrideListener(); - this.spyRegistry.clearSpies(); - delete this.byRunableId_[runableId]; - } - - spies() { - return this.forCurrentRunable_( - 'Spies must be created in a before function or a spec' - ).spies; - } - - defaultSpyStrategy() { - if (!this.getCurrentRunableId_()) { - return undefined; - } - - return this.byRunableId_[this.getCurrentRunableId_()].defaultSpyStrategy; - } - - setDefaultSpyStrategy(fn) { - this.forCurrentRunable_( - 'Default spy strategy must be set in a before function or a spec' - ).defaultSpyStrategy = fn; - } - - customSpyStrategies() { - return this.forCurrentRunable_( - 'Custom spy strategies must be added in a before function or a spec' - ).customSpyStrategies; - } - - customEqualityTesters() { - return this.forCurrentRunable_( - 'Custom Equalities must be added in a before function or a spec' - ).customEqualityTesters; - } - - customMatchers() { - return this.forCurrentRunable_( - 'Matchers must be added in a before function or a spec' - ).customMatchers; - } - - addCustomMatchers(matchersToAdd) { - const matchers = this.customMatchers(); - - for (const name in matchersToAdd) { - matchers[name] = matchersToAdd[name]; - } - } - - customAsyncMatchers() { - return this.forCurrentRunable_( - 'Async Matchers must be added in a before function or a spec' - ).customAsyncMatchers; - } - - addCustomAsyncMatchers(matchersToAdd) { - const matchers = this.customAsyncMatchers(); - - for (const name in matchersToAdd) { - matchers[name] = matchersToAdd[name]; - } - } - - customObjectFormatters() { - return this.forCurrentRunable_( - 'Custom object formatters must be added in a before function or a spec' - ).customObjectFormatters; - } - - makePrettyPrinter() { - return j$.makePrettyPrinter(this.customObjectFormatters()); - } - - makeMatchersUtil() { - if (this.getCurrentRunableId_()) { - return new j$.MatchersUtil({ - customTesters: this.customEqualityTesters(), - pp: this.makePrettyPrinter() - }); - } else { - return new j$.MatchersUtil({ pp: j$.basicPrettyPrinter_ }); - } - } - - forCurrentRunable_(errorMsg) { - const resources = this.byRunableId_[this.getCurrentRunableId_()]; - - if (!resources && errorMsg) { - throw new Error(errorMsg); - } - - return resources; - } - } - - return RunableResources; -}; + return RunableResources +} getJasmineRequireObj().Runner = function(j$) { - class Runner { - constructor(options) { - this.topSuite_ = options.topSuite; - this.totalSpecsDefined_ = options.totalSpecsDefined; - this.focusedRunables_ = options.focusedRunables; - this.runableResources_ = options.runableResources; - this.queueRunnerFactory_ = options.queueRunnerFactory; - this.reporter_ = options.reporter; - this.getConfig_ = options.getConfig; - this.reportSpecDone_ = options.reportSpecDone; - this.hasFailures = false; - this.executedBefore_ = false; + class Runner { + constructor(options) { + this.topSuite_ = options.topSuite + this.totalSpecsDefined_ = options.totalSpecsDefined + this.focusedRunables_ = options.focusedRunables + this.runableResources_ = options.runableResources + this.queueRunnerFactory_ = options.queueRunnerFactory + this.reporter_ = options.reporter + this.getConfig_ = options.getConfig + this.reportSpecDone_ = options.reportSpecDone + this.hasFailures = false + this.executedBefore_ = false - this.currentlyExecutingSuites_ = []; - this.currentSpec = null; - } - - currentRunable() { - return this.currentSpec || this.currentSuite(); - } - - currentSuite() { - return this.currentlyExecutingSuites_[ - this.currentlyExecutingSuites_.length - 1 - ]; - } - - // Although execute returns a promise, it isn't async for backwards - // compatibility: The "Invalid order" exception needs to be propagated - // synchronously from Env#execute. - // TODO: make this and Env#execute async in the next major release - execute(runablesToRun) { - if (this.executedBefore_) { - this.topSuite_.reset(); - } - this.executedBefore_ = true; - - this.hasFailures = false; - const focusedRunables = this.focusedRunables_(); - const config = this.getConfig_(); - - if (!runablesToRun) { - if (focusedRunables.length) { - runablesToRun = focusedRunables; - } else { - runablesToRun = [this.topSuite_.id]; + this.currentlyExecutingSuites_ = [] + this.currentSpec = null } - } - const order = new j$.Order({ - random: config.random, - seed: j$.isNumber_(config.seed) ? config.seed + '' : config.seed - }); + currentRunable() { + return this.currentSpec || this.currentSuite() + } - const processor = new j$.TreeProcessor({ - tree: this.topSuite_, - runnableIds: runablesToRun, - queueRunnerFactory: options => { - if (options.isLeaf) { - // A spec - options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; - } else { - // A suite - if (config.stopOnSpecFailure) { - options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy; - } else { - options.SkipPolicy = j$.SkipAfterBeforeAllErrorPolicy; + currentSuite() { + return this.currentlyExecutingSuites_[this.currentlyExecutingSuites_.length - 1] + } + + // Although execute returns a promise, it isn't async for backwards + // compatibility: The "Invalid order" exception needs to be propagated + // synchronously from Env#execute. + // TODO: make this and Env#execute async in the next major release + execute(runablesToRun) { + if (this.executedBefore_) { + this.topSuite_.reset() } - } + this.executedBefore_ = true - return this.queueRunnerFactory_(options); - }, - failSpecWithNoExpectations: config.failSpecWithNoExpectations, - nodeStart: (suite, next) => { - this.currentlyExecutingSuites_.push(suite); - this.runableResources_.initForRunable(suite.id, suite.parentSuite.id); - this.reporter_.suiteStarted(suite.result).then(next); - suite.startTimer(); - }, - nodeComplete: (suite, result, next) => { - if (suite !== this.currentSuite()) { - throw new Error('Tried to complete the wrong suite'); - } + this.hasFailures = false + const focusedRunables = this.focusedRunables_() + const config = this.getConfig_() - this.runableResources_.clearForRunable(suite.id); - this.currentlyExecutingSuites_.pop(); + if (!runablesToRun) { + if (focusedRunables.length) { + runablesToRun = focusedRunables + } else { + runablesToRun = [this.topSuite_.id] + } + } - if (result.status === 'failed') { - this.hasFailures = true; - } - suite.endTimer(); + const order = new j$.Order({ + random: config.random, + seed: j$.isNumber_(config.seed) ? config.seed + "" : config.seed, + }) - if (suite.hadBeforeAllFailure) { - this.reportChildrenOfBeforeAllFailure_(suite).then(() => { - this.reportSuiteDone_(suite, result, next); - }); - } else { - this.reportSuiteDone_(suite, result, next); - } - }, - orderChildren: function(node) { - return order.sort(node.children); - }, - excludeNode: function(spec) { - return !config.specFilter(spec); + const processor = new j$.TreeProcessor({ + tree: this.topSuite_, + runnableIds: runablesToRun, + queueRunnerFactory: (options) => { + if (options.isLeaf) { + // A spec + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy + } else { + // A suite + if (config.stopOnSpecFailure) { + options.SkipPolicy = j$.CompleteOnFirstErrorSkipPolicy + } else { + options.SkipPolicy = j$.SkipAfterBeforeAllErrorPolicy + } + } + + return this.queueRunnerFactory_(options) + }, + failSpecWithNoExpectations: config.failSpecWithNoExpectations, + nodeStart: (suite, next) => { + this.currentlyExecutingSuites_.push(suite) + this.runableResources_.initForRunable(suite.id, suite.parentSuite.id) + this.reporter_.suiteStarted(suite.result).then(next) + suite.startTimer() + }, + nodeComplete: (suite, result, next) => { + if (suite !== this.currentSuite()) { + throw new Error("Tried to complete the wrong suite") + } + + this.runableResources_.clearForRunable(suite.id) + this.currentlyExecutingSuites_.pop() + + if (result.status === "failed") { + this.hasFailures = true + } + suite.endTimer() + + if (suite.hadBeforeAllFailure) { + this.reportChildrenOfBeforeAllFailure_(suite).then(() => { + this.reportSuiteDone_(suite, result, next) + }) + } else { + this.reportSuiteDone_(suite, result, next) + } + }, + orderChildren: function(node) { + return order.sort(node.children) + }, + excludeNode: function(spec) { + return !config.specFilter(spec) + }, + }) + + if (!processor.processTree().valid) { + throw new Error("Invalid order: would cause a beforeAll or afterAll to be run multiple times") + } + + return this.execute2_(runablesToRun, order, processor) } - }); - if (!processor.processTree().valid) { - throw new Error( - 'Invalid order: would cause a beforeAll or afterAll to be run multiple times' - ); - } + async execute2_(runablesToRun, order, processor) { + const totalSpecsDefined = this.totalSpecsDefined_() - return this.execute2_(runablesToRun, order, processor); - } + this.runableResources_.initForRunable(this.topSuite_.id) + const jasmineTimer = new j$.Timer() + jasmineTimer.start() - async execute2_(runablesToRun, order, processor) { - const totalSpecsDefined = this.totalSpecsDefined_(); + /** + * Information passed to the {@link Reporter#jasmineStarted} event. + * @typedef JasmineStartedInfo + * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @since 2.0.0 + */ + await this.reporter_.jasmineStarted({ + totalSpecsDefined, + order: order, + }) - this.runableResources_.initForRunable(this.topSuite_.id); - const jasmineTimer = new j$.Timer(); - jasmineTimer.start(); + this.currentlyExecutingSuites_.push(this.topSuite_) + await processor.execute() - /** - * Information passed to the {@link Reporter#jasmineStarted} event. - * @typedef JasmineStartedInfo - * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @since 2.0.0 - */ - await this.reporter_.jasmineStarted({ - totalSpecsDefined, - order: order - }); + if (this.topSuite_.hadBeforeAllFailure) { + await this.reportChildrenOfBeforeAllFailure_(this.topSuite_) + } - this.currentlyExecutingSuites_.push(this.topSuite_); - await processor.execute(); + this.runableResources_.clearForRunable(this.topSuite_.id) + this.currentlyExecutingSuites_.pop() + let overallStatus, incompleteReason - if (this.topSuite_.hadBeforeAllFailure) { - await this.reportChildrenOfBeforeAllFailure_(this.topSuite_); - } + if (this.hasFailures || this.topSuite_.result.failedExpectations.length > 0) { + overallStatus = "failed" + } else if (this.focusedRunables_().length > 0) { + overallStatus = "incomplete" + incompleteReason = "fit() or fdescribe() was found" + } else if (totalSpecsDefined === 0) { + overallStatus = "incomplete" + incompleteReason = "No specs found" + } else { + overallStatus = "passed" + } - this.runableResources_.clearForRunable(this.topSuite_.id); - this.currentlyExecutingSuites_.pop(); - let overallStatus, incompleteReason; - - if ( - this.hasFailures || - this.topSuite_.result.failedExpectations.length > 0 - ) { - overallStatus = 'failed'; - } else if (this.focusedRunables_().length > 0) { - overallStatus = 'incomplete'; - incompleteReason = 'fit() or fdescribe() was found'; - } else if (totalSpecsDefined === 0) { - overallStatus = 'incomplete'; - incompleteReason = 'No specs found'; - } else { - overallStatus = 'passed'; - } - - /** - * Information passed to the {@link Reporter#jasmineDone} event. - * @typedef JasmineDoneInfo - * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. - * @property {Int} totalTime - The total time (in ms) that it took to execute the suite - * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. - * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. - * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. - * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. - * @since 2.4.0 - */ - const jasmineDoneInfo = { - overallStatus: overallStatus, - totalTime: jasmineTimer.elapsed(), - incompleteReason: incompleteReason, - order: order, - failedExpectations: this.topSuite_.result.failedExpectations, - deprecationWarnings: this.topSuite_.result.deprecationWarnings - }; - this.topSuite_.reportedDone = true; - await this.reporter_.jasmineDone(jasmineDoneInfo); - return jasmineDoneInfo; - } - - reportSuiteDone_(suite, result, next) { - suite.reportedDone = true; - this.reporter_.suiteDone(result).then(next); - } - - async reportChildrenOfBeforeAllFailure_(suite) { - for (const child of suite.children) { - if (child instanceof j$.Suite) { - await this.reporter_.suiteStarted(child.result); - await this.reportChildrenOfBeforeAllFailure_(child); - - // Marking the suite passed is consistent with how suites that - // contain failed specs but no suite-level failures are reported. - child.result.status = 'passed'; - - await this.reporter_.suiteDone(child.result); - } else { - /* a spec */ - await this.reporter_.specStarted(child.result); - - child.addExpectationResult( - false, - { - passed: false, - message: - 'Not run because a beforeAll function failed. The ' + - 'beforeAll failure will be reported on the suite that ' + - 'caused it.' - }, - true - ); - child.result.status = 'failed'; - - await new Promise(resolve => { - this.reportSpecDone_(child, child.result, resolve); - }); + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {Int} totalTime - The total time (in ms) that it took to execute the suite + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + * @since 2.4.0 + */ + const jasmineDoneInfo = { + overallStatus: overallStatus, + totalTime: jasmineTimer.elapsed(), + incompleteReason: incompleteReason, + order: order, + failedExpectations: this.topSuite_.result.failedExpectations, + deprecationWarnings: this.topSuite_.result.deprecationWarnings, + } + this.topSuite_.reportedDone = true + await this.reporter_.jasmineDone(jasmineDoneInfo) + return jasmineDoneInfo } - } - } - } - return Runner; -}; + reportSuiteDone_(suite, result, next) { + suite.reportedDone = true + this.reporter_.suiteDone(result).then(next) + } + + async reportChildrenOfBeforeAllFailure_(suite) { + for (const child of suite.children) { + if (child instanceof j$.Suite) { + await this.reporter_.suiteStarted(child.result) + await this.reportChildrenOfBeforeAllFailure_(child) + + // Marking the suite passed is consistent with how suites that + // contain failed specs but no suite-level failures are reported. + child.result.status = "passed" + + await this.reporter_.suiteDone(child.result) + } else { + /* a spec */ + await this.reporter_.specStarted(child.result) + + child.addExpectationResult( + false, + { + passed: false, + message: + "Not run because a beforeAll function failed. The " + + "beforeAll failure will be reported on the suite that " + + "caused it.", + }, + true + ) + child.result.status = "failed" + + await new Promise((resolve) => { + this.reportSpecDone_(child, child.result, resolve) + }) + } + } + } + } + + return Runner +} getJasmineRequireObj().SkipAfterBeforeAllErrorPolicy = function(j$) { - function SkipAfterBeforeAllErrorPolicy(queueableFns) { - this.queueableFns_ = queueableFns; - this.skipping_ = false; - } - - SkipAfterBeforeAllErrorPolicy.prototype.skipTo = function(lastRanFnIx) { - if (this.skipping_) { - return this.nextAfterAllAfter_(lastRanFnIx); - } else { - return lastRanFnIx + 1; + function SkipAfterBeforeAllErrorPolicy(queueableFns) { + this.queueableFns_ = queueableFns + this.skipping_ = false } - }; - SkipAfterBeforeAllErrorPolicy.prototype.nextAfterAllAfter_ = function(i) { - for ( - i++; - i < this.queueableFns_.length && - this.queueableFns_[i].type !== 'afterAll'; - i++ - ) {} - return i; - }; - - SkipAfterBeforeAllErrorPolicy.prototype.fnErrored = function(fnIx) { - if (this.queueableFns_[fnIx].type === 'beforeAll') { - this.skipping_ = true; - // Failures need to be reported for each contained spec. But we can't do - // that from here because reporting is async. This function isn't async - // (and can't be without greatly complicating QueueRunner). Mark the - // failure so that the code that reports the suite result (which is - // already async) can detect the failure and report the specs. - this.queueableFns_[fnIx].suite.hadBeforeAllFailure = true; + SkipAfterBeforeAllErrorPolicy.prototype.skipTo = function(lastRanFnIx) { + if (this.skipping_) { + return this.nextAfterAllAfter_(lastRanFnIx) + } else { + return lastRanFnIx + 1 + } } - }; - return SkipAfterBeforeAllErrorPolicy; -}; + SkipAfterBeforeAllErrorPolicy.prototype.nextAfterAllAfter_ = function(i) { + for (i++; i < this.queueableFns_.length && this.queueableFns_[i].type !== "afterAll"; i++) {} + return i + } + + SkipAfterBeforeAllErrorPolicy.prototype.fnErrored = function(fnIx) { + if (this.queueableFns_[fnIx].type === "beforeAll") { + this.skipping_ = true + // Failures need to be reported for each contained spec. But we can't do + // that from here because reporting is async. This function isn't async + // (and can't be without greatly complicating QueueRunner). Mark the + // failure so that the code that reports the suite result (which is + // already async) can detect the failure and report the specs. + this.queueableFns_[fnIx].suite.hadBeforeAllFailure = true + } + } + + return SkipAfterBeforeAllErrorPolicy +} getJasmineRequireObj().Spy = function(j$) { - const nextOrder = (function() { - let order = 0; + const nextOrder = (function() { + let order = 0 - return function() { - return order++; - }; - })(); - - /** - * @classdesc _Note:_ Do not construct this directly. Use {@link spyOn}, - * {@link spyOnProperty}, {@link jasmine.createSpy}, or - * {@link jasmine.createSpyObj} instead. - * @class Spy - * @hideconstructor - */ - function Spy(name, matchersUtil, optionals) { - const spy = function(context, args, invokeNew) { - /** - * @name Spy.callData - * @property {object} object - `this` context for the invocation. - * @property {number} invocationOrder - Order of the invocation. - * @property {Array} args - The arguments passed for this invocation. - * @property returnValue - The value that was returned from this invocation. - */ - const callData = { - object: context, - invocationOrder: nextOrder(), - args: Array.prototype.slice.apply(args) - }; - - callTracker.track(callData); - const returnValue = strategyDispatcher.exec(context, args, invokeNew); - callData.returnValue = returnValue; - - return returnValue; - }; - const { originalFn, customStrategies, defaultStrategyFn } = optionals || {}; - - const numArgs = typeof originalFn === 'function' ? originalFn.length : 0, - wrapper = makeFunc(numArgs, function(context, args, invokeNew) { - return spy(context, args, invokeNew); - }), - strategyDispatcher = new SpyStrategyDispatcher( - { - name: name, - fn: originalFn, - getSpy: function() { - return wrapper; - }, - customStrategies: customStrategies - }, - matchersUtil - ), - callTracker = new j$.CallTracker(); - - function makeFunc(length, fn) { - switch (length) { - case 1: - return function wrap1(a) { - return fn(this, arguments, this instanceof wrap1); - }; - case 2: - return function wrap2(a, b) { - return fn(this, arguments, this instanceof wrap2); - }; - case 3: - return function wrap3(a, b, c) { - return fn(this, arguments, this instanceof wrap3); - }; - case 4: - return function wrap4(a, b, c, d) { - return fn(this, arguments, this instanceof wrap4); - }; - case 5: - return function wrap5(a, b, c, d, e) { - return fn(this, arguments, this instanceof wrap5); - }; - case 6: - return function wrap6(a, b, c, d, e, f) { - return fn(this, arguments, this instanceof wrap6); - }; - case 7: - return function wrap7(a, b, c, d, e, f, g) { - return fn(this, arguments, this instanceof wrap7); - }; - case 8: - return function wrap8(a, b, c, d, e, f, g, h) { - return fn(this, arguments, this instanceof wrap8); - }; - case 9: - return function wrap9(a, b, c, d, e, f, g, h, i) { - return fn(this, arguments, this instanceof wrap9); - }; - default: - return function wrap() { - return fn(this, arguments, this instanceof wrap); - }; - } - } - - for (const prop in originalFn) { - if (prop === 'and' || prop === 'calls') { - throw new Error( - "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" - ); - } - - wrapper[prop] = originalFn[prop]; - } - - /** - * @member {SpyStrategy} - Accesses the default strategy for the spy. This strategy will be used - * whenever the spy is called with arguments that don't match any strategy - * created with {@link Spy#withArgs}. - * @name Spy#and - * @since 2.0.0 - * @example - * spyOn(someObj, 'func').and.returnValue(42); - */ - wrapper.and = strategyDispatcher.and; - /** - * Specifies a strategy to be used for calls to the spy that have the - * specified arguments. - * @name Spy#withArgs - * @since 3.0.0 - * @function - * @param {...*} args - The arguments to match - * @type {SpyStrategy} - * @example - * spyOn(someObj, 'func').withArgs(1, 2, 3).and.returnValue(42); - * someObj.func(1, 2, 3); // returns 42 - */ - wrapper.withArgs = function() { - return strategyDispatcher.withArgs.apply(strategyDispatcher, arguments); - }; - wrapper.calls = callTracker; - - if (defaultStrategyFn) { - defaultStrategyFn(wrapper.and); - } - - return wrapper; - } - - function SpyStrategyDispatcher(strategyArgs, matchersUtil) { - const baseStrategy = new j$.SpyStrategy(strategyArgs); - const argsStrategies = new StrategyDict(function() { - return new j$.SpyStrategy(strategyArgs); - }, matchersUtil); - - this.and = baseStrategy; - - this.exec = function(spy, args, invokeNew) { - let strategy = argsStrategies.get(args); - - if (!strategy) { - if (argsStrategies.any() && !baseStrategy.isConfigured()) { - throw new Error( - "Spy '" + - strategyArgs.name + - "' received a call with arguments " + - j$.basicPrettyPrinter_(Array.prototype.slice.call(args)) + - ' but all configured strategies specify other arguments.' - ); - } else { - strategy = baseStrategy; + return function() { + return order++ } - } + })() - return strategy.exec(spy, args, invokeNew); - }; + /** + * @classdesc _Note:_ Do not construct this directly. Use {@link spyOn}, + * {@link spyOnProperty}, {@link jasmine.createSpy}, or + * {@link jasmine.createSpyObj} instead. + * @class Spy + * @hideconstructor + */ + function Spy(name, matchersUtil, optionals) { + const spy = function(context, args, invokeNew) { + /** + * @name Spy.callData + * @property {object} object - `this` context for the invocation. + * @property {number} invocationOrder - Order of the invocation. + * @property {Array} args - The arguments passed for this invocation. + * @property returnValue - The value that was returned from this invocation. + */ + const callData = { + object: context, + invocationOrder: nextOrder(), + args: Array.prototype.slice.apply(args), + } - this.withArgs = function() { - return { and: argsStrategies.getOrCreate(arguments) }; - }; - } + callTracker.track(callData) + const returnValue = strategyDispatcher.exec(context, args, invokeNew) + callData.returnValue = returnValue - function StrategyDict(strategyFactory, matchersUtil) { - this.strategies = []; - this.strategyFactory = strategyFactory; - this.matchersUtil = matchersUtil; - } + return returnValue + } + const { originalFn, customStrategies, defaultStrategyFn } = optionals || {} - StrategyDict.prototype.any = function() { - return this.strategies.length > 0; - }; + const numArgs = typeof originalFn === "function" ? originalFn.length : 0, + wrapper = makeFunc(numArgs, function(context, args, invokeNew) { + return spy(context, args, invokeNew) + }), + strategyDispatcher = new SpyStrategyDispatcher( + { + name: name, + fn: originalFn, + getSpy: function() { + return wrapper + }, + customStrategies: customStrategies, + }, + matchersUtil + ), + callTracker = new j$.CallTracker() - StrategyDict.prototype.getOrCreate = function(args) { - let strategy = this.get(args); + function makeFunc(length, fn) { + switch (length) { + case 1: + return function wrap1(a) { + return fn(this, arguments, this instanceof wrap1) + } + case 2: + return function wrap2(a, b) { + return fn(this, arguments, this instanceof wrap2) + } + case 3: + return function wrap3(a, b, c) { + return fn(this, arguments, this instanceof wrap3) + } + case 4: + return function wrap4(a, b, c, d) { + return fn(this, arguments, this instanceof wrap4) + } + case 5: + return function wrap5(a, b, c, d, e) { + return fn(this, arguments, this instanceof wrap5) + } + case 6: + return function wrap6(a, b, c, d, e, f) { + return fn(this, arguments, this instanceof wrap6) + } + case 7: + return function wrap7(a, b, c, d, e, f, g) { + return fn(this, arguments, this instanceof wrap7) + } + case 8: + return function wrap8(a, b, c, d, e, f, g, h) { + return fn(this, arguments, this instanceof wrap8) + } + case 9: + return function wrap9(a, b, c, d, e, f, g, h, i) { + return fn(this, arguments, this instanceof wrap9) + } + default: + return function wrap() { + return fn(this, arguments, this instanceof wrap) + } + } + } - if (!strategy) { - strategy = this.strategyFactory(); - this.strategies.push({ - args: args, - strategy: strategy - }); + for (const prop in originalFn) { + if (prop === "and" || prop === "calls") { + throw new Error( + "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" + ) + } + + wrapper[prop] = originalFn[prop] + } + + /** + * @member {SpyStrategy} - Accesses the default strategy for the spy. This strategy will be used + * whenever the spy is called with arguments that don't match any strategy + * created with {@link Spy#withArgs}. + * @name Spy#and + * @since 2.0.0 + * @example + * spyOn(someObj, 'func').and.returnValue(42); + */ + wrapper.and = strategyDispatcher.and + /** + * Specifies a strategy to be used for calls to the spy that have the + * specified arguments. + * @name Spy#withArgs + * @since 3.0.0 + * @function + * @param {...*} args - The arguments to match + * @type {SpyStrategy} + * @example + * spyOn(someObj, 'func').withArgs(1, 2, 3).and.returnValue(42); + * someObj.func(1, 2, 3); // returns 42 + */ + wrapper.withArgs = function() { + return strategyDispatcher.withArgs.apply(strategyDispatcher, arguments) + } + wrapper.calls = callTracker + + if (defaultStrategyFn) { + defaultStrategyFn(wrapper.and) + } + + return wrapper } - return strategy; - }; + function SpyStrategyDispatcher(strategyArgs, matchersUtil) { + const baseStrategy = new j$.SpyStrategy(strategyArgs) + const argsStrategies = new StrategyDict(function() { + return new j$.SpyStrategy(strategyArgs) + }, matchersUtil) - StrategyDict.prototype.get = function(args) { - for (let i = 0; i < this.strategies.length; i++) { - if (this.matchersUtil.equals(args, this.strategies[i].args)) { - return this.strategies[i].strategy; - } + this.and = baseStrategy + + this.exec = function(spy, args, invokeNew) { + let strategy = argsStrategies.get(args) + + if (!strategy) { + if (argsStrategies.any() && !baseStrategy.isConfigured()) { + throw new Error( + "Spy '" + + strategyArgs.name + + "' received a call with arguments " + + j$.basicPrettyPrinter_(Array.prototype.slice.call(args)) + + " but all configured strategies specify other arguments." + ) + } else { + strategy = baseStrategy + } + } + + return strategy.exec(spy, args, invokeNew) + } + + this.withArgs = function() { + return { and: argsStrategies.getOrCreate(arguments) } + } } - }; - return Spy; -}; + function StrategyDict(strategyFactory, matchersUtil) { + this.strategies = [] + this.strategyFactory = strategyFactory + this.matchersUtil = matchersUtil + } + + StrategyDict.prototype.any = function() { + return this.strategies.length > 0 + } + + StrategyDict.prototype.getOrCreate = function(args) { + let strategy = this.get(args) + + if (!strategy) { + strategy = this.strategyFactory() + this.strategies.push({ + args: args, + strategy: strategy, + }) + } + + return strategy + } + + StrategyDict.prototype.get = function(args) { + for (let i = 0; i < this.strategies.length; i++) { + if (this.matchersUtil.equals(args, this.strategies[i].args)) { + return this.strategies[i].strategy + } + } + } + + return Spy +} getJasmineRequireObj().SpyFactory = function(j$) { - function SpyFactory( - getCustomStrategies, - getDefaultStrategyFn, - getMatchersUtil - ) { - this.createSpy = function(name, originalFn) { - if (j$.isFunction_(name) && originalFn === undefined) { - originalFn = name; - name = originalFn.name; - } + function SpyFactory(getCustomStrategies, getDefaultStrategyFn, getMatchersUtil) { + this.createSpy = function(name, originalFn) { + if (j$.isFunction_(name) && originalFn === undefined) { + originalFn = name + name = originalFn.name + } - return j$.Spy(name, getMatchersUtil(), { - originalFn, - customStrategies: getCustomStrategies(), - defaultStrategyFn: getDefaultStrategyFn() - }); - }; - - this.createSpyObj = function(baseName, methodNames, propertyNames) { - const baseNameIsCollection = - j$.isObject_(baseName) || j$.isArray_(baseName); - - if (baseNameIsCollection) { - propertyNames = methodNames; - methodNames = baseName; - baseName = 'unknown'; - } - - const obj = {}; - - const methods = normalizeKeyValues(methodNames); - for (let i = 0; i < methods.length; i++) { - const spy = (obj[methods[i][0]] = this.createSpy( - baseName + '.' + methods[i][0] - )); - if (methods[i].length > 1) { - spy.and.returnValue(methods[i][1]); + return j$.Spy(name, getMatchersUtil(), { + originalFn, + customStrategies: getCustomStrategies(), + defaultStrategyFn: getDefaultStrategyFn(), + }) } - } - const properties = normalizeKeyValues(propertyNames); - for (let i = 0; i < properties.length; i++) { - const descriptor = { - enumerable: true, - get: this.createSpy(baseName + '.' + properties[i][0] + '.get'), - set: this.createSpy(baseName + '.' + properties[i][0] + '.set') - }; - if (properties[i].length > 1) { - descriptor.get.and.returnValue(properties[i][1]); - descriptor.set.and.returnValue(properties[i][1]); + this.createSpyObj = function(baseName, methodNames, propertyNames) { + const baseNameIsCollection = j$.isObject_(baseName) || j$.isArray_(baseName) + + if (baseNameIsCollection) { + propertyNames = methodNames + methodNames = baseName + baseName = "unknown" + } + + const obj = {} + + const methods = normalizeKeyValues(methodNames) + for (let i = 0; i < methods.length; i++) { + const spy = (obj[methods[i][0]] = this.createSpy(baseName + "." + methods[i][0])) + if (methods[i].length > 1) { + spy.and.returnValue(methods[i][1]) + } + } + + const properties = normalizeKeyValues(propertyNames) + for (let i = 0; i < properties.length; i++) { + const descriptor = { + enumerable: true, + get: this.createSpy(baseName + "." + properties[i][0] + ".get"), + set: this.createSpy(baseName + "." + properties[i][0] + ".set"), + } + if (properties[i].length > 1) { + descriptor.get.and.returnValue(properties[i][1]) + descriptor.set.and.returnValue(properties[i][1]) + } + Object.defineProperty(obj, properties[i][0], descriptor) + } + + if (methods.length === 0 && properties.length === 0) { + throw "createSpyObj requires a non-empty array or object of method names to create spies for" + } + + return obj } - Object.defineProperty(obj, properties[i][0], descriptor); - } - - if (methods.length === 0 && properties.length === 0) { - throw 'createSpyObj requires a non-empty array or object of method names to create spies for'; - } - - return obj; - }; - } - - function normalizeKeyValues(object) { - const result = []; - if (j$.isArray_(object)) { - for (let i = 0; i < object.length; i++) { - result.push([object[i]]); - } - } else if (j$.isObject_(object)) { - for (const key in object) { - if (object.hasOwnProperty(key)) { - result.push([key, object[key]]); - } - } } - return result; - } - return SpyFactory; -}; + function normalizeKeyValues(object) { + const result = [] + if (j$.isArray_(object)) { + for (let i = 0; i < object.length; i++) { + result.push([object[i]]) + } + } else if (j$.isObject_(object)) { + for (const key in object) { + if (object.hasOwnProperty(key)) { + result.push([key, object[key]]) + } + } + } + return result + } + + return SpyFactory +} getJasmineRequireObj().SpyRegistry = function(j$) { - const spyOnMsg = j$.formatErrorMsg( - '', - 'spyOn(, )' - ); - const spyOnPropertyMsg = j$.formatErrorMsg( - '', - 'spyOnProperty(, , [accessType])' - ); + const spyOnMsg = j$.formatErrorMsg("", "spyOn(, )") + const spyOnPropertyMsg = j$.formatErrorMsg("", "spyOnProperty(, , [accessType])") - function SpyRegistry(options) { - options = options || {}; - const global = options.global || j$.getGlobal(); - const createSpy = options.createSpy; - const currentSpies = - options.currentSpies || - function() { - return []; - }; + function SpyRegistry(options) { + options = options || {} + const global = options.global || j$.getGlobal() + const createSpy = options.createSpy + const currentSpies = + options.currentSpies || + function() { + return [] + } - this.allowRespy = function(allow) { - this.respy = allow; - }; - - this.spyOn = function(obj, methodName) { - const getErrorMsg = spyOnMsg; - - if (j$.util.isUndefined(obj) || obj === null) { - throw new Error( - getErrorMsg( - 'could not find an object to spy upon for ' + methodName + '()' - ) - ); - } - - if (j$.util.isUndefined(methodName) || methodName === null) { - throw new Error(getErrorMsg('No method name supplied')); - } - - if (j$.util.isUndefined(obj[methodName])) { - throw new Error(getErrorMsg(methodName + '() method does not exist')); - } - - if (obj[methodName] && j$.isSpy(obj[methodName])) { - if (this.respy) { - return obj[methodName]; - } else { - throw new Error( - getErrorMsg(methodName + ' has already been spied upon') - ); + this.allowRespy = function(allow) { + this.respy = allow } - } - const descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + this.spyOn = function(obj, methodName) { + const getErrorMsg = spyOnMsg - if (descriptor && !(descriptor.writable || descriptor.set)) { - throw new Error( - getErrorMsg(methodName + ' is not declared writable or has no setter') - ); - } + if (j$.util.isUndefined(obj) || obj === null) { + throw new Error(getErrorMsg("could not find an object to spy upon for " + methodName + "()")) + } - const originalMethod = obj[methodName]; - const spiedMethod = createSpy(methodName, originalMethod); - let restoreStrategy; + if (j$.util.isUndefined(methodName) || methodName === null) { + throw new Error(getErrorMsg("No method name supplied")) + } - if ( - Object.prototype.hasOwnProperty.call(obj, methodName) || - (obj === global && methodName === 'onerror') - ) { - restoreStrategy = function() { - obj[methodName] = originalMethod; - }; - } else { - restoreStrategy = function() { - if (!delete obj[methodName]) { - obj[methodName] = originalMethod; - } - }; - } + if (j$.util.isUndefined(obj[methodName])) { + throw new Error(getErrorMsg(methodName + "() method does not exist")) + } - currentSpies().push({ - restoreObjectToOriginalState: restoreStrategy - }); + if (obj[methodName] && j$.isSpy(obj[methodName])) { + if (this.respy) { + return obj[methodName] + } else { + throw new Error(getErrorMsg(methodName + " has already been spied upon")) + } + } - obj[methodName] = spiedMethod; + const descriptor = Object.getOwnPropertyDescriptor(obj, methodName) - return spiedMethod; - }; + if (descriptor && !(descriptor.writable || descriptor.set)) { + throw new Error(getErrorMsg(methodName + " is not declared writable or has no setter")) + } - this.spyOnProperty = function(obj, propertyName, accessType) { - const getErrorMsg = spyOnPropertyMsg; + const originalMethod = obj[methodName] + const spiedMethod = createSpy(methodName, originalMethod) + let restoreStrategy - accessType = accessType || 'get'; + if (Object.prototype.hasOwnProperty.call(obj, methodName) || (obj === global && methodName === "onerror")) { + restoreStrategy = function() { + obj[methodName] = originalMethod + } + } else { + restoreStrategy = function() { + if (!delete obj[methodName]) { + obj[methodName] = originalMethod + } + } + } - if (j$.util.isUndefined(obj)) { - throw new Error( - getErrorMsg( - 'spyOn could not find an object to spy upon for ' + - propertyName + - '' - ) - ); - } + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy, + }) - if (j$.util.isUndefined(propertyName)) { - throw new Error(getErrorMsg('No property name supplied')); - } + obj[methodName] = spiedMethod - const descriptor = j$.util.getPropertyDescriptor(obj, propertyName); - - if (!descriptor) { - throw new Error(getErrorMsg(propertyName + ' property does not exist')); - } - - if (!descriptor.configurable) { - throw new Error( - getErrorMsg(propertyName + ' is not declared configurable') - ); - } - - if (!descriptor[accessType]) { - throw new Error( - getErrorMsg( - 'Property ' + - propertyName + - ' does not have access type ' + - accessType - ) - ); - } - - if (j$.isSpy(descriptor[accessType])) { - if (this.respy) { - return descriptor[accessType]; - } else { - throw new Error( - getErrorMsg( - propertyName + '#' + accessType + ' has already been spied upon' - ) - ); + return spiedMethod } - } - const originalDescriptor = j$.util.clone(descriptor); - const spy = createSpy(propertyName, descriptor[accessType]); - let restoreStrategy; + this.spyOnProperty = function(obj, propertyName, accessType) { + const getErrorMsg = spyOnPropertyMsg - if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { - restoreStrategy = function() { - Object.defineProperty(obj, propertyName, originalDescriptor); - }; - } else { - restoreStrategy = function() { - delete obj[propertyName]; - }; - } + accessType = accessType || "get" - currentSpies().push({ - restoreObjectToOriginalState: restoreStrategy - }); + if (j$.util.isUndefined(obj)) { + throw new Error(getErrorMsg("spyOn could not find an object to spy upon for " + propertyName + "")) + } - descriptor[accessType] = spy; + if (j$.util.isUndefined(propertyName)) { + throw new Error(getErrorMsg("No property name supplied")) + } - Object.defineProperty(obj, propertyName, descriptor); + const descriptor = j$.util.getPropertyDescriptor(obj, propertyName) - return spy; - }; + if (!descriptor) { + throw new Error(getErrorMsg(propertyName + " property does not exist")) + } - this.spyOnAllFunctions = function(obj, includeNonEnumerable) { - if (j$.util.isUndefined(obj)) { - throw new Error( - 'spyOnAllFunctions could not find an object to spy upon' - ); - } + if (!descriptor.configurable) { + throw new Error(getErrorMsg(propertyName + " is not declared configurable")) + } - let pointer = obj, - propsToSpyOn = [], - properties, - propertiesToSkip = []; + if (!descriptor[accessType]) { + throw new Error(getErrorMsg("Property " + propertyName + " does not have access type " + accessType)) + } - while ( - pointer && - (!includeNonEnumerable || pointer !== Object.prototype) - ) { - properties = getProps(pointer, includeNonEnumerable); - properties = properties.filter(function(prop) { - return propertiesToSkip.indexOf(prop) === -1; - }); - propertiesToSkip = propertiesToSkip.concat(properties); - propsToSpyOn = propsToSpyOn.concat( - getSpyableFunctionProps(pointer, properties) - ); - pointer = Object.getPrototypeOf(pointer); - } + if (j$.isSpy(descriptor[accessType])) { + if (this.respy) { + return descriptor[accessType] + } else { + throw new Error(getErrorMsg(propertyName + "#" + accessType + " has already been spied upon")) + } + } - for (const prop of propsToSpyOn) { - this.spyOn(obj, prop); - } + const originalDescriptor = j$.util.clone(descriptor) + const spy = createSpy(propertyName, descriptor[accessType]) + let restoreStrategy - return obj; - }; + if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { + restoreStrategy = function() { + Object.defineProperty(obj, propertyName, originalDescriptor) + } + } else { + restoreStrategy = function() { + delete obj[propertyName] + } + } - this.clearSpies = function() { - const spies = currentSpies(); - for (let i = spies.length - 1; i >= 0; i--) { - const spyEntry = spies[i]; - spyEntry.restoreObjectToOriginalState(); - } - }; - } + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy, + }) - function getProps(obj, includeNonEnumerable) { - const enumerableProperties = Object.keys(obj); + descriptor[accessType] = spy - if (!includeNonEnumerable) { - return enumerableProperties; + Object.defineProperty(obj, propertyName, descriptor) + + return spy + } + + this.spyOnAllFunctions = function(obj, includeNonEnumerable) { + if (j$.util.isUndefined(obj)) { + throw new Error("spyOnAllFunctions could not find an object to spy upon") + } + + let pointer = obj, + propsToSpyOn = [], + properties, + propertiesToSkip = [] + + while (pointer && (!includeNonEnumerable || pointer !== Object.prototype)) { + properties = getProps(pointer, includeNonEnumerable) + properties = properties.filter(function(prop) { + return propertiesToSkip.indexOf(prop) === -1 + }) + propertiesToSkip = propertiesToSkip.concat(properties) + propsToSpyOn = propsToSpyOn.concat(getSpyableFunctionProps(pointer, properties)) + pointer = Object.getPrototypeOf(pointer) + } + + for (const prop of propsToSpyOn) { + this.spyOn(obj, prop) + } + + return obj + } + + this.clearSpies = function() { + const spies = currentSpies() + for (let i = spies.length - 1; i >= 0; i--) { + const spyEntry = spies[i] + spyEntry.restoreObjectToOriginalState() + } + } } - return Object.getOwnPropertyNames(obj).filter(function(prop) { - return ( - prop !== 'constructor' || - enumerableProperties.indexOf('constructor') > -1 - ); - }); - } + function getProps(obj, includeNonEnumerable) { + const enumerableProperties = Object.keys(obj) - function getSpyableFunctionProps(obj, propertiesToCheck) { - const props = []; + if (!includeNonEnumerable) { + return enumerableProperties + } - for (const prop of propertiesToCheck) { - if ( - Object.prototype.hasOwnProperty.call(obj, prop) && - isSpyableProp(obj, prop) - ) { - props.push(prop); - } - } - return props; - } - - function isSpyableProp(obj, prop) { - let value; - try { - value = obj[prop]; - } catch (e) { - return false; + return Object.getOwnPropertyNames(obj).filter(function(prop) { + return prop !== "constructor" || enumerableProperties.indexOf("constructor") > -1 + }) } - if (value instanceof Function) { - const descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return (descriptor.writable || descriptor.set) && descriptor.configurable; - } - return false; - } + function getSpyableFunctionProps(obj, propertiesToCheck) { + const props = [] - return SpyRegistry; -}; + for (const prop of propertiesToCheck) { + if (Object.prototype.hasOwnProperty.call(obj, prop) && isSpyableProp(obj, prop)) { + props.push(prop) + } + } + return props + } + + function isSpyableProp(obj, prop) { + let value + try { + value = obj[prop] + } catch (e) { + return false + } + + if (value instanceof Function) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop) + return (descriptor.writable || descriptor.set) && descriptor.configurable + } + return false + } + + return SpyRegistry +} getJasmineRequireObj().SpyStrategy = function(j$) { - /** - * @interface SpyStrategy - */ - function SpyStrategy(options) { - options = options || {}; - /** - * Get the identifying information for the spy. - * @name SpyStrategy#identity - * @since 3.0.0 - * @member - * @type {String} + * @interface SpyStrategy */ - this.identity = options.name || 'unknown'; - this.originalFn = options.fn || function() {}; - this.getSpy = options.getSpy || function() {}; - this.plan = this._defaultPlan = function() {}; + function SpyStrategy(options) { + options = options || {} - const cs = options.customStrategies || {}; - for (const k in cs) { - if (j$.util.has(cs, k) && !this[k]) { - this[k] = createCustomPlan(cs[k]); - } + /** + * Get the identifying information for the spy. + * @name SpyStrategy#identity + * @since 3.0.0 + * @member + * @type {String} + */ + this.identity = options.name || "unknown" + this.originalFn = options.fn || function() {} + this.getSpy = options.getSpy || function() {} + this.plan = this._defaultPlan = function() {} + + const cs = options.customStrategies || {} + for (const k in cs) { + if (j$.util.has(cs, k) && !this[k]) { + this[k] = createCustomPlan(cs[k]) + } + } + + /** + * Tell the spy to return a promise resolving to the specified value when invoked. + * @name SpyStrategy#resolveTo + * @since 3.5.0 + * @function + * @param {*} value The value to return. + */ + this.resolveTo = function(value) { + this.plan = function() { + return Promise.resolve(value) + } + return this.getSpy() + } + + /** + * Tell the spy to return a promise rejecting with the specified value when invoked. + * @name SpyStrategy#rejectWith + * @since 3.5.0 + * @function + * @param {*} value The value to return. + */ + this.rejectWith = function(value) { + this.plan = function() { + return Promise.reject(value) + } + return this.getSpy() + } + } + + function createCustomPlan(factory) { + return function() { + const plan = factory.apply(null, arguments) + + if (!j$.isFunction_(plan)) { + throw new Error("Spy strategy must return a function") + } + + this.plan = plan + return this.getSpy() + } } /** - * Tell the spy to return a promise resolving to the specified value when invoked. - * @name SpyStrategy#resolveTo - * @since 3.5.0 + * Execute the current spy strategy. + * @name SpyStrategy#exec + * @since 2.0.0 * @function - * @param {*} value The value to return. */ - this.resolveTo = function(value) { - this.plan = function() { - return Promise.resolve(value); - }; - return this.getSpy(); - }; + SpyStrategy.prototype.exec = function(context, args, invokeNew) { + const contextArgs = [context].concat(args ? Array.prototype.slice.call(args) : []) + const target = this.plan.bind.apply(this.plan, contextArgs) + + return invokeNew ? new target() : target() + } /** - * Tell the spy to return a promise rejecting with the specified value when invoked. - * @name SpyStrategy#rejectWith - * @since 3.5.0 + * Tell the spy to call through to the real implementation when invoked. + * @name SpyStrategy#callThrough + * @since 2.0.0 + * @function + */ + SpyStrategy.prototype.callThrough = function() { + this.plan = this.originalFn + return this.getSpy() + } + + /** + * Tell the spy to return the value when invoked. + * @name SpyStrategy#returnValue + * @since 2.0.0 * @function * @param {*} value The value to return. */ - this.rejectWith = function(value) { - this.plan = function() { - return Promise.reject(value); - }; - return this.getSpy(); - }; - } - - function createCustomPlan(factory) { - return function() { - const plan = factory.apply(null, arguments); - - if (!j$.isFunction_(plan)) { - throw new Error('Spy strategy must return a function'); - } - - this.plan = plan; - return this.getSpy(); - }; - } - - /** - * Execute the current spy strategy. - * @name SpyStrategy#exec - * @since 2.0.0 - * @function - */ - SpyStrategy.prototype.exec = function(context, args, invokeNew) { - const contextArgs = [context].concat( - args ? Array.prototype.slice.call(args) : [] - ); - const target = this.plan.bind.apply(this.plan, contextArgs); - - return invokeNew ? new target() : target(); - }; - - /** - * Tell the spy to call through to the real implementation when invoked. - * @name SpyStrategy#callThrough - * @since 2.0.0 - * @function - */ - SpyStrategy.prototype.callThrough = function() { - this.plan = this.originalFn; - return this.getSpy(); - }; - - /** - * Tell the spy to return the value when invoked. - * @name SpyStrategy#returnValue - * @since 2.0.0 - * @function - * @param {*} value The value to return. - */ - SpyStrategy.prototype.returnValue = function(value) { - this.plan = function() { - return value; - }; - return this.getSpy(); - }; - - /** - * Tell the spy to return one of the specified values (sequentially) each time the spy is invoked. - * @name SpyStrategy#returnValues - * @since 2.1.0 - * @function - * @param {...*} values - Values to be returned on subsequent calls to the spy. - */ - SpyStrategy.prototype.returnValues = function() { - const values = Array.prototype.slice.call(arguments); - this.plan = function() { - return values.shift(); - }; - return this.getSpy(); - }; - - /** - * Tell the spy to throw an error when invoked. - * @name SpyStrategy#throwError - * @since 2.0.0 - * @function - * @param {Error|Object|String} something Thing to throw - */ - SpyStrategy.prototype.throwError = function(something) { - const error = j$.isString_(something) ? new Error(something) : something; - this.plan = function() { - throw error; - }; - return this.getSpy(); - }; - - /** - * Tell the spy to call a fake implementation when invoked. - * @name SpyStrategy#callFake - * @since 2.0.0 - * @function - * @param {Function} fn The function to invoke with the passed parameters. - */ - SpyStrategy.prototype.callFake = function(fn) { - if ( - !( - j$.isFunction_(fn) || - j$.isAsyncFunction_(fn) || - j$.isGeneratorFunction_(fn) - ) - ) { - throw new Error( - 'Argument passed to callFake should be a function, got ' + fn - ); + SpyStrategy.prototype.returnValue = function(value) { + this.plan = function() { + return value + } + return this.getSpy() } - this.plan = fn; - return this.getSpy(); - }; - /** - * Tell the spy to do nothing when invoked. This is the default. - * @name SpyStrategy#stub - * @since 2.0.0 - * @function - */ - SpyStrategy.prototype.stub = function(fn) { - this.plan = function() {}; - return this.getSpy(); - }; + /** + * Tell the spy to return one of the specified values (sequentially) each time the spy is invoked. + * @name SpyStrategy#returnValues + * @since 2.1.0 + * @function + * @param {...*} values - Values to be returned on subsequent calls to the spy. + */ + SpyStrategy.prototype.returnValues = function() { + const values = Array.prototype.slice.call(arguments) + this.plan = function() { + return values.shift() + } + return this.getSpy() + } - SpyStrategy.prototype.isConfigured = function() { - return this.plan !== this._defaultPlan; - }; + /** + * Tell the spy to throw an error when invoked. + * @name SpyStrategy#throwError + * @since 2.0.0 + * @function + * @param {Error|Object|String} something Thing to throw + */ + SpyStrategy.prototype.throwError = function(something) { + const error = j$.isString_(something) ? new Error(something) : something + this.plan = function() { + throw error + } + return this.getSpy() + } - return SpyStrategy; -}; + /** + * Tell the spy to call a fake implementation when invoked. + * @name SpyStrategy#callFake + * @since 2.0.0 + * @function + * @param {Function} fn The function to invoke with the passed parameters. + */ + SpyStrategy.prototype.callFake = function(fn) { + if (!(j$.isFunction_(fn) || j$.isAsyncFunction_(fn) || j$.isGeneratorFunction_(fn))) { + throw new Error("Argument passed to callFake should be a function, got " + fn) + } + this.plan = fn + return this.getSpy() + } + + /** + * Tell the spy to do nothing when invoked. This is the default. + * @name SpyStrategy#stub + * @since 2.0.0 + * @function + */ + SpyStrategy.prototype.stub = function(fn) { + this.plan = function() {} + return this.getSpy() + } + + SpyStrategy.prototype.isConfigured = function() { + return this.plan !== this._defaultPlan + } + + return SpyStrategy +} getJasmineRequireObj().StackTrace = function(j$) { - function StackTrace(error) { - let lines = error.stack.split('\n').filter(function(line) { - return line !== ''; - }); + function StackTrace(error) { + let lines = error.stack.split("\n").filter(function(line) { + return line !== "" + }) - const extractResult = extractMessage(error.message, lines); + const extractResult = extractMessage(error.message, lines) - if (extractResult) { - this.message = extractResult.message; - lines = extractResult.remainder; - } - - const parseResult = tryParseFrames(lines); - this.frames = parseResult.frames; - this.style = parseResult.style; - } - - const framePatterns = [ - // Node, Chrome, Edge - // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" - // Note that the "function name" can include a surprisingly large set of - // characters, including angle brackets and square brackets. - { - re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, - fnIx: 1, - fileLineColIx: 2, - style: 'v8' - }, - - // NodeJS alternate form, often mixed in with the Chrome style - // e.g. " at /some/path:4320:20 - { re: /\s*at (.+)$/, fileLineColIx: 1, style: 'v8' }, - - // PhantomJS on OS X, Safari, Firefox - // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" - // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" - { - re: /^(?:(([^@\s]+)@)|@)?([^\s]+)$/, - fnIx: 2, - fileLineColIx: 3, - style: 'webkit' - } - ]; - - // regexes should capture the function name (if any) as group 1 - // and the file, line, and column as group 2. - function tryParseFrames(lines) { - let style = null; - const frames = lines.map(function(line) { - const convertedLine = first(framePatterns, function(pattern) { - const overallMatch = line.match(pattern.re); - if (!overallMatch) { - return null; + if (extractResult) { + this.message = extractResult.message + lines = extractResult.remainder } - const fileLineColMatch = overallMatch[pattern.fileLineColIx].match( - /^(.*):(\d+):\d+$/ - ); - if (!fileLineColMatch) { - return null; - } + const parseResult = tryParseFrames(lines) + this.frames = parseResult.frames + this.style = parseResult.style + } + + const framePatterns = [ + // Node, Chrome, Edge + // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" + // Note that the "function name" can include a surprisingly large set of + // characters, including angle brackets and square brackets. + { + re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, + fnIx: 1, + fileLineColIx: 2, + style: "v8", + }, + + // NodeJS alternate form, often mixed in with the Chrome style + // e.g. " at /some/path:4320:20 + { re: /\s*at (.+)$/, fileLineColIx: 1, style: "v8" }, + + // PhantomJS on OS X, Safari, Firefox + // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" + // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" + { + re: /^(?:(([^@\s]+)@)|@)?([^\s]+)$/, + fnIx: 2, + fileLineColIx: 3, + style: "webkit", + }, + ] + + // regexes should capture the function name (if any) as group 1 + // and the file, line, and column as group 2. + function tryParseFrames(lines) { + let style = null + const frames = lines.map(function(line) { + const convertedLine = first(framePatterns, function(pattern) { + const overallMatch = line.match(pattern.re) + if (!overallMatch) { + return null + } + + const fileLineColMatch = overallMatch[pattern.fileLineColIx].match(/^(.*):(\d+):\d+$/) + if (!fileLineColMatch) { + return null + } + + style = style || pattern.style + return { + raw: line, + file: fileLineColMatch[1], + line: parseInt(fileLineColMatch[2], 10), + func: overallMatch[pattern.fnIx], + } + }) + + return convertedLine || { raw: line } + }) - style = style || pattern.style; return { - raw: line, - file: fileLineColMatch[1], - line: parseInt(fileLineColMatch[2], 10), - func: overallMatch[pattern.fnIx] - }; - }); - - return convertedLine || { raw: line }; - }); - - return { - style: style, - frames: frames - }; - } - - function first(items, fn) { - for (const item of items) { - const result = fn(item); - - if (result) { - return result; - } - } - } - - function extractMessage(message, stackLines) { - const len = messagePrefixLength(message, stackLines); - - if (len > 0) { - return { - message: stackLines.slice(0, len).join('\n'), - remainder: stackLines.slice(len) - }; - } - } - - function messagePrefixLength(message, stackLines) { - if (!stackLines[0].match(/^\w*Error/)) { - return 0; + style: style, + frames: frames, + } } - const messageLines = message.split('\n'); + function first(items, fn) { + for (const item of items) { + const result = fn(item) - for (let i = 1; i < messageLines.length; i++) { - if (messageLines[i] !== stackLines[i]) { - return 0; - } + if (result) { + return result + } + } } - return messageLines.length; - } + function extractMessage(message, stackLines) { + const len = messagePrefixLength(message, stackLines) - return StackTrace; -}; + if (len > 0) { + return { + message: stackLines.slice(0, len).join("\n"), + remainder: stackLines.slice(len), + } + } + } + + function messagePrefixLength(message, stackLines) { + if (!stackLines[0].match(/^\w*Error/)) { + return 0 + } + + const messageLines = message.split("\n") + + for (let i = 1; i < messageLines.length; i++) { + if (messageLines[i] !== stackLines[i]) { + return 0 + } + } + + return messageLines.length + } + + return StackTrace +} getJasmineRequireObj().Suite = function(j$) { - function Suite(attrs) { - this.env = attrs.env; - this.id = attrs.id; - this.parentSuite = attrs.parentSuite; - this.description = attrs.description; - this.expectationFactory = attrs.expectationFactory; - this.asyncExpectationFactory = attrs.asyncExpectationFactory; - this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; - this.autoCleanClosures = - attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures; - this.onLateError = attrs.onLateError || function() {}; + function Suite(attrs) { + this.env = attrs.env + this.id = attrs.id + this.parentSuite = attrs.parentSuite + this.description = attrs.description + this.expectationFactory = attrs.expectationFactory + this.asyncExpectationFactory = attrs.asyncExpectationFactory + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure + this.autoCleanClosures = attrs.autoCleanClosures === undefined ? true : !!attrs.autoCleanClosures + this.onLateError = attrs.onLateError || function() {} - this.beforeFns = []; - this.afterFns = []; - this.beforeAllFns = []; - this.afterAllFns = []; - this.timer = attrs.timer || new j$.Timer(); - this.children = []; + this.beforeFns = [] + this.afterFns = [] + this.beforeAllFns = [] + this.afterAllFns = [] + this.timer = attrs.timer || new j$.Timer() + this.children = [] - this.reset(); - } - - Suite.prototype.setSuiteProperty = function(key, value) { - this.result.properties = this.result.properties || {}; - this.result.properties[key] = value; - }; - - Suite.prototype.expect = function(actual) { - return this.expectationFactory(actual, this); - }; - - Suite.prototype.expectAsync = function(actual) { - return this.asyncExpectationFactory(actual, this); - }; - - Suite.prototype.getFullName = function() { - const fullName = []; - for ( - let parentSuite = this; - parentSuite; - parentSuite = parentSuite.parentSuite - ) { - if (parentSuite.parentSuite) { - fullName.unshift(parentSuite.description); - } - } - return fullName.join(' '); - }; - - /* - * Mark the suite with "pending" status - */ - Suite.prototype.pend = function() { - this.markedPending = true; - }; - - /* - * Like {@link Suite#pend}, but pending state will survive {@link Spec#reset} - * Useful for fdescribe, xdescribe, where pending state should remain. - */ - Suite.prototype.exclude = function() { - this.pend(); - this.markedExcluding = true; - }; - - Suite.prototype.beforeEach = function(fn) { - this.beforeFns.unshift({ ...fn, suite: this }); - }; - - Suite.prototype.beforeAll = function(fn) { - this.beforeAllFns.push({ ...fn, type: 'beforeAll', suite: this }); - }; - - Suite.prototype.afterEach = function(fn) { - this.afterFns.unshift({ ...fn, suite: this, type: 'afterEach' }); - }; - - Suite.prototype.afterAll = function(fn) { - this.afterAllFns.unshift({ ...fn, type: 'afterAll' }); - }; - - Suite.prototype.startTimer = function() { - this.timer.start(); - }; - - Suite.prototype.endTimer = function() { - this.result.duration = this.timer.elapsed(); - }; - - function removeFns(queueableFns) { - for (const qf of queueableFns) { - qf.fn = null; - } - } - - Suite.prototype.cleanupBeforeAfter = function() { - if (this.autoCleanClosures) { - removeFns(this.beforeAllFns); - removeFns(this.afterAllFns); - removeFns(this.beforeFns); - removeFns(this.afterFns); - } - }; - - Suite.prototype.reset = function() { - /** - * @typedef SuiteResult - * @property {String} id - The unique id of this suite. - * @property {String} description - The description text passed to the {@link describe} that made this suite. - * @property {String} fullName - The full description including all ancestors of this suite. - * @property {Expectation[]} failedExpectations - The list of expectations that failed in an {@link afterAll} for this suite. - * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred on this suite. - * @property {String} status - Once the suite has completed, this string represents the pass/fail status of this suite. - * @property {number} duration - The time in ms for Suite execution, including any before/afterAll, before/afterEach. - * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSuiteProperty} - * @since 2.0.0 - */ - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [], - deprecationWarnings: [], - duration: null, - properties: null - }; - this.markedPending = this.markedExcluding; - this.children.forEach(function(child) { - child.reset(); - }); - this.reportedDone = false; - }; - - Suite.prototype.addChild = function(child) { - this.children.push(child); - }; - - Suite.prototype.status = function() { - if (this.markedPending) { - return 'pending'; + this.reset() } - if (this.result.failedExpectations.length > 0) { - return 'failed'; - } else { - return 'passed'; - } - }; - - Suite.prototype.canBeReentered = function() { - return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; - }; - - Suite.prototype.getResult = function() { - this.result.status = this.status(); - return this.result; - }; - - Suite.prototype.sharedUserContext = function() { - if (!this.sharedContext) { - this.sharedContext = this.parentSuite - ? this.parentSuite.clonedSharedUserContext() - : new j$.UserContext(); + Suite.prototype.setSuiteProperty = function(key, value) { + this.result.properties = this.result.properties || {} + this.result.properties[key] = value } - return this.sharedContext; - }; - - Suite.prototype.clonedSharedUserContext = function() { - return j$.UserContext.fromExisting(this.sharedUserContext()); - }; - - Suite.prototype.handleException = function() { - if (arguments[0] instanceof j$.errors.ExpectationFailed) { - return; + Suite.prototype.expect = function(actual) { + return this.expectationFactory(actual, this) } - const data = { - matcherName: '', - passed: false, - expected: '', - actual: '', - error: arguments[0] - }; - const failedExpectation = j$.buildExpectationResult(data); - - if (!this.parentSuite) { - failedExpectation.globalErrorType = 'afterAll'; + Suite.prototype.expectAsync = function(actual) { + return this.asyncExpectationFactory(actual, this) } - if (this.reportedDone) { - this.onLateError(failedExpectation); - } else { - this.result.failedExpectations.push(failedExpectation); - } - }; - - Suite.prototype.onMultipleDone = function() { - let msg; - - // Issue a deprecation. Include the context ourselves and pass - // ignoreRunnable: true, since getting here always means that we've already - // moved on and the current runnable isn't the one that caused the problem. - if (this.parentSuite) { - msg = - "An asynchronous beforeAll or afterAll function called its 'done' " + - 'callback more than once.\n' + - '(in suite: ' + - this.getFullName() + - ')'; - } else { - msg = - 'A top-level beforeAll or afterAll function called its ' + - "'done' callback more than once."; - } - - this.onLateError(new Error(msg)); - }; - - Suite.prototype.addExpectationResult = function() { - if (isFailure(arguments)) { - const data = arguments[1]; - const expectationResult = j$.buildExpectationResult(data); - - if (this.reportedDone) { - this.onLateError(expectationResult); - } else { - this.result.failedExpectations.push(expectationResult); - - // TODO: refactor so that we don't need to override cached status - if (this.result.status) { - this.result.status = 'failed'; + Suite.prototype.getFullName = function() { + const fullName = [] + for (let parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) { + if (parentSuite.parentSuite) { + fullName.unshift(parentSuite.description) + } } - } - - if (this.throwOnExpectationFailure) { - throw new j$.errors.ExpectationFailed(); - } + return fullName.join(" ") } - }; - Suite.prototype.addDeprecationWarning = function(deprecation) { - if (typeof deprecation === 'string') { - deprecation = { message: deprecation }; + /* + * Mark the suite with "pending" status + */ + Suite.prototype.pend = function() { + this.markedPending = true } - this.result.deprecationWarnings.push( - j$.buildExpectationResult(deprecation) - ); - }; - Object.defineProperty(Suite.prototype, 'metadata', { - get: function() { - if (!this.metadata_) { - this.metadata_ = new SuiteMetadata(this); - } - - return this.metadata_; + /* + * Like {@link Suite#pend}, but pending state will survive {@link Spec#reset} + * Useful for fdescribe, xdescribe, where pending state should remain. + */ + Suite.prototype.exclude = function() { + this.pend() + this.markedExcluding = true } - }); - /** - * @interface Suite - * @see Env#topSuite - * @since 2.0.0 - */ - function SuiteMetadata(suite) { - this.suite_ = suite; + Suite.prototype.beforeEach = function(fn) { + this.beforeFns.unshift({ ...fn, suite: this }) + } + + Suite.prototype.beforeAll = function(fn) { + this.beforeAllFns.push({ ...fn, type: "beforeAll", suite: this }) + } + + Suite.prototype.afterEach = function(fn) { + this.afterFns.unshift({ ...fn, suite: this, type: "afterEach" }) + } + + Suite.prototype.afterAll = function(fn) { + this.afterAllFns.unshift({ ...fn, type: "afterAll" }) + } + + Suite.prototype.startTimer = function() { + this.timer.start() + } + + Suite.prototype.endTimer = function() { + this.result.duration = this.timer.elapsed() + } + + function removeFns(queueableFns) { + for (const qf of queueableFns) { + qf.fn = null + } + } + + Suite.prototype.cleanupBeforeAfter = function() { + if (this.autoCleanClosures) { + removeFns(this.beforeAllFns) + removeFns(this.afterAllFns) + removeFns(this.beforeFns) + removeFns(this.afterFns) + } + } + + Suite.prototype.reset = function() { + /** + * @typedef SuiteResult + * @property {String} id - The unique id of this suite. + * @property {String} description - The description text passed to the {@link describe} that made this suite. + * @property {String} fullName - The full description including all ancestors of this suite. + * @property {Expectation[]} failedExpectations - The list of expectations that failed in an {@link afterAll} for this suite. + * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred on this suite. + * @property {String} status - Once the suite has completed, this string represents the pass/fail status of this suite. + * @property {number} duration - The time in ms for Suite execution, including any before/afterAll, before/afterEach. + * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSuiteProperty} + * @since 2.0.0 + */ + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + deprecationWarnings: [], + duration: null, + properties: null, + } + this.markedPending = this.markedExcluding + this.children.forEach(function(child) { + child.reset() + }) + this.reportedDone = false + } + + Suite.prototype.addChild = function(child) { + this.children.push(child) + } + + Suite.prototype.status = function() { + if (this.markedPending) { + return "pending" + } + + if (this.result.failedExpectations.length > 0) { + return "failed" + } else { + return "passed" + } + } + + Suite.prototype.canBeReentered = function() { + return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0 + } + + Suite.prototype.getResult = function() { + this.result.status = this.status() + return this.result + } + + Suite.prototype.sharedUserContext = function() { + if (!this.sharedContext) { + this.sharedContext = this.parentSuite ? this.parentSuite.clonedSharedUserContext() : new j$.UserContext() + } + + return this.sharedContext + } + + Suite.prototype.clonedSharedUserContext = function() { + return j$.UserContext.fromExisting(this.sharedUserContext()) + } + + Suite.prototype.handleException = function() { + if (arguments[0] instanceof j$.errors.ExpectationFailed) { + return + } + + const data = { + matcherName: "", + passed: false, + expected: "", + actual: "", + error: arguments[0], + } + const failedExpectation = j$.buildExpectationResult(data) + + if (!this.parentSuite) { + failedExpectation.globalErrorType = "afterAll" + } + + if (this.reportedDone) { + this.onLateError(failedExpectation) + } else { + this.result.failedExpectations.push(failedExpectation) + } + } + + Suite.prototype.onMultipleDone = function() { + let msg + + // Issue a deprecation. Include the context ourselves and pass + // ignoreRunnable: true, since getting here always means that we've already + // moved on and the current runnable isn't the one that caused the problem. + if (this.parentSuite) { + msg = + "An asynchronous beforeAll or afterAll function called its 'done' " + + "callback more than once.\n" + + "(in suite: " + + this.getFullName() + + ")" + } else { + msg = "A top-level beforeAll or afterAll function called its " + "'done' callback more than once." + } + + this.onLateError(new Error(msg)) + } + + Suite.prototype.addExpectationResult = function() { + if (isFailure(arguments)) { + const data = arguments[1] + const expectationResult = j$.buildExpectationResult(data) + + if (this.reportedDone) { + this.onLateError(expectationResult) + } else { + this.result.failedExpectations.push(expectationResult) + + // TODO: refactor so that we don't need to override cached status + if (this.result.status) { + this.result.status = "failed" + } + } + + if (this.throwOnExpectationFailure) { + throw new j$.errors.ExpectationFailed() + } + } + } + + Suite.prototype.addDeprecationWarning = function(deprecation) { + if (typeof deprecation === "string") { + deprecation = { message: deprecation } + } + this.result.deprecationWarnings.push(j$.buildExpectationResult(deprecation)) + } + + Object.defineProperty(Suite.prototype, "metadata", { + get: function() { + if (!this.metadata_) { + this.metadata_ = new SuiteMetadata(this) + } + + return this.metadata_ + }, + }) + /** - * The unique ID of this suite. - * @name Suite#id - * @readonly - * @type {string} + * @interface Suite + * @see Env#topSuite * @since 2.0.0 */ - this.id = suite.id; + function SuiteMetadata(suite) { + this.suite_ = suite + /** + * The unique ID of this suite. + * @name Suite#id + * @readonly + * @type {string} + * @since 2.0.0 + */ + this.id = suite.id + + /** + * The parent of this suite, or null if this is the top suite. + * @name Suite#parentSuite + * @readonly + * @type {Suite} + */ + this.parentSuite = suite.parentSuite ? suite.parentSuite.metadata : null + + /** + * The description passed to the {@link describe} that created this suite. + * @name Suite#description + * @readonly + * @type {string} + * @since 2.0.0 + */ + this.description = suite.description + } /** - * The parent of this suite, or null if this is the top suite. - * @name Suite#parentSuite - * @readonly - * @type {Suite} - */ - this.parentSuite = suite.parentSuite ? suite.parentSuite.metadata : null; - - /** - * The description passed to the {@link describe} that created this suite. - * @name Suite#description - * @readonly - * @type {string} + * The full description including all ancestors of this suite. + * @name Suite#getFullName + * @function + * @returns {string} * @since 2.0.0 */ - this.description = suite.description; - } - - /** - * The full description including all ancestors of this suite. - * @name Suite#getFullName - * @function - * @returns {string} - * @since 2.0.0 - */ - SuiteMetadata.prototype.getFullName = function() { - return this.suite_.getFullName(); - }; - - /** - * The suite's children. - * @name Suite#children - * @type {Array.<(Spec|Suite)>} - * @since 2.0.0 - */ - Object.defineProperty(SuiteMetadata.prototype, 'children', { - get: function() { - return this.suite_.children.map(child => child.metadata); + SuiteMetadata.prototype.getFullName = function() { + return this.suite_.getFullName() } - }); - function isFailure(args) { - return !args[0]; - } + /** + * The suite's children. + * @name Suite#children + * @type {Array.<(Spec|Suite)>} + * @since 2.0.0 + */ + Object.defineProperty(SuiteMetadata.prototype, "children", { + get: function() { + return this.suite_.children.map((child) => child.metadata) + }, + }) - return Suite; -}; + function isFailure(args) { + return !args[0] + } + + return Suite +} getJasmineRequireObj().SuiteBuilder = function(j$) { - class SuiteBuilder { - constructor(options) { - this.env_ = options.env; - this.expectationFactory_ = options.expectationFactory; - this.suiteAsyncExpectationFactory_ = function(actual, suite) { - return options.asyncExpectationFactory(actual, suite, 'Suite'); - }; - this.specAsyncExpectationFactory_ = function(actual, suite) { - return options.asyncExpectationFactory(actual, suite, 'Spec'); - }; - this.onLateError_ = options.onLateError; - this.specResultCallback_ = options.specResultCallback; - this.specStarted_ = options.specStarted; + class SuiteBuilder { + constructor(options) { + this.env_ = options.env + this.expectationFactory_ = options.expectationFactory + this.suiteAsyncExpectationFactory_ = function(actual, suite) { + return options.asyncExpectationFactory(actual, suite, "Suite") + } + this.specAsyncExpectationFactory_ = function(actual, suite) { + return options.asyncExpectationFactory(actual, suite, "Spec") + } + this.onLateError_ = options.onLateError + this.specResultCallback_ = options.specResultCallback + this.specStarted_ = options.specStarted - this.nextSuiteId_ = 0; - this.nextSpecId_ = 0; + this.nextSuiteId_ = 0 + this.nextSpecId_ = 0 - this.topSuite = this.suiteFactory_('Jasmine__TopLevel__Suite'); - this.currentDeclarationSuite_ = this.topSuite; - this.totalSpecsDefined = 0; - this.focusedRunables = []; - } - - describe(description, definitionFn) { - ensureIsFunction(definitionFn, 'describe'); - const suite = this.suiteFactory_(description); - if (definitionFn.length > 0) { - throw new Error('describe does not expect any arguments'); - } - if (this.currentDeclarationSuite_.markedExcluding) { - suite.exclude(); - } - this.addSpecsToSuite_(suite, definitionFn); - return suite; - } - - fdescribe(description, definitionFn) { - ensureIsFunction(definitionFn, 'fdescribe'); - const suite = this.suiteFactory_(description); - suite.isFocused = true; - - this.focusedRunables.push(suite.id); - this.unfocusAncestor_(); - this.addSpecsToSuite_(suite, definitionFn); - - return suite; - } - - xdescribe(description, definitionFn) { - ensureIsFunction(definitionFn, 'xdescribe'); - const suite = this.suiteFactory_(description); - suite.exclude(); - this.addSpecsToSuite_(suite, definitionFn); - - return suite; - } - - it(description, fn, timeout) { - // it() sometimes doesn't have a fn argument, so only check the type if - // it's given. - if (arguments.length > 1 && typeof fn !== 'undefined') { - ensureIsFunctionOrAsync(fn, 'it'); - } - - return this.it_(description, fn, timeout); - } - - xit(description, fn, timeout) { - // xit(), like it(), doesn't always have a fn argument, so only check the - // type when needed. - if (arguments.length > 1 && typeof fn !== 'undefined') { - ensureIsFunctionOrAsync(fn, 'xit'); - } - const spec = this.it_(description, fn, timeout); - spec.exclude('Temporarily disabled with xit'); - return spec; - } - - fit(description, fn, timeout) { - // Unlike it and xit, the function is required because it doesn't make - // sense to focus on nothing. - ensureIsFunctionOrAsync(fn, 'fit'); - - if (timeout) { - j$.util.validateTimeout(timeout); - } - const spec = this.specFactory_(description, fn, timeout); - this.currentDeclarationSuite_.addChild(spec); - this.focusedRunables.push(spec.id); - this.unfocusAncestor_(); - return spec; - } - - beforeEach(beforeEachFunction, timeout) { - ensureIsFunctionOrAsync(beforeEachFunction, 'beforeEach'); - - if (timeout) { - j$.util.validateTimeout(timeout); - } - - this.currentDeclarationSuite_.beforeEach({ - fn: beforeEachFunction, - timeout: timeout || 0 - }); - } - - beforeAll(beforeAllFunction, timeout) { - ensureIsFunctionOrAsync(beforeAllFunction, 'beforeAll'); - - if (timeout) { - j$.util.validateTimeout(timeout); - } - - this.currentDeclarationSuite_.beforeAll({ - fn: beforeAllFunction, - timeout: timeout || 0 - }); - } - - afterEach(afterEachFunction, timeout) { - ensureIsFunctionOrAsync(afterEachFunction, 'afterEach'); - - if (timeout) { - j$.util.validateTimeout(timeout); - } - - afterEachFunction.isCleanup = true; - this.currentDeclarationSuite_.afterEach({ - fn: afterEachFunction, - timeout: timeout || 0 - }); - } - - afterAll(afterAllFunction, timeout) { - ensureIsFunctionOrAsync(afterAllFunction, 'afterAll'); - - if (timeout) { - j$.util.validateTimeout(timeout); - } - - this.currentDeclarationSuite_.afterAll({ - fn: afterAllFunction, - timeout: timeout || 0 - }); - } - - it_(description, fn, timeout) { - if (timeout) { - j$.util.validateTimeout(timeout); - } - - const spec = this.specFactory_(description, fn, timeout); - if (this.currentDeclarationSuite_.markedExcluding) { - spec.exclude(); - } - this.currentDeclarationSuite_.addChild(spec); - - return spec; - } - - suiteFactory_(description) { - const config = this.env_.configuration(); - return new j$.Suite({ - id: 'suite' + this.nextSuiteId_++, - description, - parentSuite: this.currentDeclarationSuite_, - timer: new j$.Timer(), - expectationFactory: this.expectationFactory_, - asyncExpectationFactory: this.suiteAsyncExpectationFactory_, - throwOnExpectationFailure: config.stopSpecOnExpectationFailure, - autoCleanClosures: config.autoCleanClosures, - onLateError: this.onLateError_ - }); - } - - addSpecsToSuite_(suite, definitionFn) { - const parentSuite = this.currentDeclarationSuite_; - parentSuite.addChild(suite); - this.currentDeclarationSuite_ = suite; - let threw = false; - - try { - definitionFn(); - } catch (e) { - suite.handleException(e); - threw = true; - } - - if (suite.parentSuite && !suite.children.length && !threw) { - throw new Error( - `describe with no children (describe() or it()): ${suite.getFullName()}` - ); - } - - this.currentDeclarationSuite_ = parentSuite; - } - - specFactory_(description, fn, timeout) { - this.totalSpecsDefined++; - const config = this.env_.configuration(); - const suite = this.currentDeclarationSuite_; - const spec = new j$.Spec({ - id: 'spec' + this.nextSpecId_++, - beforeAndAfterFns: beforeAndAfterFns(suite), - expectationFactory: this.expectationFactory_, - asyncExpectationFactory: this.specAsyncExpectationFactory_, - onLateError: this.onLateError_, - resultCallback: (result, next) => { - this.specResultCallback_(spec, result, next); - }, - getSpecName: function(spec) { - return getSpecName(spec, suite); - }, - onStart: (spec, next) => this.specStarted_(spec, suite, next), - description: description, - userContext: function() { - return suite.clonedSharedUserContext(); - }, - queueableFn: { - fn: fn, - timeout: timeout || 0 - }, - throwOnExpectationFailure: config.stopSpecOnExpectationFailure, - autoCleanClosures: config.autoCleanClosures, - timer: new j$.Timer() - }); - return spec; - } - - unfocusAncestor_() { - const focusedAncestor = findFocusedAncestor( - this.currentDeclarationSuite_ - ); - - if (focusedAncestor) { - for (let i = 0; i < this.focusedRunables.length; i++) { - if (this.focusedRunables[i] === focusedAncestor) { - this.focusedRunables.splice(i, 1); - break; - } + this.topSuite = this.suiteFactory_("Jasmine__TopLevel__Suite") + this.currentDeclarationSuite_ = this.topSuite + this.totalSpecsDefined = 0 + this.focusedRunables = [] } - } - } - } - function findFocusedAncestor(suite) { - while (suite) { - if (suite.isFocused) { - return suite.id; - } - suite = suite.parentSuite; + describe(description, definitionFn) { + ensureIsFunction(definitionFn, "describe") + const suite = this.suiteFactory_(description) + if (definitionFn.length > 0) { + throw new Error("describe does not expect any arguments") + } + if (this.currentDeclarationSuite_.markedExcluding) { + suite.exclude() + } + this.addSpecsToSuite_(suite, definitionFn) + return suite + } + + fdescribe(description, definitionFn) { + ensureIsFunction(definitionFn, "fdescribe") + const suite = this.suiteFactory_(description) + suite.isFocused = true + + this.focusedRunables.push(suite.id) + this.unfocusAncestor_() + this.addSpecsToSuite_(suite, definitionFn) + + return suite + } + + xdescribe(description, definitionFn) { + ensureIsFunction(definitionFn, "xdescribe") + const suite = this.suiteFactory_(description) + suite.exclude() + this.addSpecsToSuite_(suite, definitionFn) + + return suite + } + + it(description, fn, timeout) { + // it() sometimes doesn't have a fn argument, so only check the type if + // it's given. + if (arguments.length > 1 && typeof fn !== "undefined") { + ensureIsFunctionOrAsync(fn, "it") + } + + return this.it_(description, fn, timeout) + } + + xit(description, fn, timeout) { + // xit(), like it(), doesn't always have a fn argument, so only check the + // type when needed. + if (arguments.length > 1 && typeof fn !== "undefined") { + ensureIsFunctionOrAsync(fn, "xit") + } + const spec = this.it_(description, fn, timeout) + spec.exclude("Temporarily disabled with xit") + return spec + } + + fit(description, fn, timeout) { + // Unlike it and xit, the function is required because it doesn't make + // sense to focus on nothing. + ensureIsFunctionOrAsync(fn, "fit") + + if (timeout) { + j$.util.validateTimeout(timeout) + } + const spec = this.specFactory_(description, fn, timeout) + this.currentDeclarationSuite_.addChild(spec) + this.focusedRunables.push(spec.id) + this.unfocusAncestor_() + return spec + } + + beforeEach(beforeEachFunction, timeout) { + ensureIsFunctionOrAsync(beforeEachFunction, "beforeEach") + + if (timeout) { + j$.util.validateTimeout(timeout) + } + + this.currentDeclarationSuite_.beforeEach({ + fn: beforeEachFunction, + timeout: timeout || 0, + }) + } + + beforeAll(beforeAllFunction, timeout) { + ensureIsFunctionOrAsync(beforeAllFunction, "beforeAll") + + if (timeout) { + j$.util.validateTimeout(timeout) + } + + this.currentDeclarationSuite_.beforeAll({ + fn: beforeAllFunction, + timeout: timeout || 0, + }) + } + + afterEach(afterEachFunction, timeout) { + ensureIsFunctionOrAsync(afterEachFunction, "afterEach") + + if (timeout) { + j$.util.validateTimeout(timeout) + } + + afterEachFunction.isCleanup = true + this.currentDeclarationSuite_.afterEach({ + fn: afterEachFunction, + timeout: timeout || 0, + }) + } + + afterAll(afterAllFunction, timeout) { + ensureIsFunctionOrAsync(afterAllFunction, "afterAll") + + if (timeout) { + j$.util.validateTimeout(timeout) + } + + this.currentDeclarationSuite_.afterAll({ + fn: afterAllFunction, + timeout: timeout || 0, + }) + } + + it_(description, fn, timeout) { + if (timeout) { + j$.util.validateTimeout(timeout) + } + + const spec = this.specFactory_(description, fn, timeout) + if (this.currentDeclarationSuite_.markedExcluding) { + spec.exclude() + } + this.currentDeclarationSuite_.addChild(spec) + + return spec + } + + suiteFactory_(description) { + const config = this.env_.configuration() + return new j$.Suite({ + id: "suite" + this.nextSuiteId_++, + description, + parentSuite: this.currentDeclarationSuite_, + timer: new j$.Timer(), + expectationFactory: this.expectationFactory_, + asyncExpectationFactory: this.suiteAsyncExpectationFactory_, + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, + autoCleanClosures: config.autoCleanClosures, + onLateError: this.onLateError_, + }) + } + + addSpecsToSuite_(suite, definitionFn) { + const parentSuite = this.currentDeclarationSuite_ + parentSuite.addChild(suite) + this.currentDeclarationSuite_ = suite + let threw = false + + try { + definitionFn() + } catch (e) { + suite.handleException(e) + threw = true + } + + if (suite.parentSuite && !suite.children.length && !threw) { + throw new Error(`describe with no children (describe() or it()): ${suite.getFullName()}`) + } + + this.currentDeclarationSuite_ = parentSuite + } + + specFactory_(description, fn, timeout) { + this.totalSpecsDefined++ + const config = this.env_.configuration() + const suite = this.currentDeclarationSuite_ + const spec = new j$.Spec({ + id: "spec" + this.nextSpecId_++, + beforeAndAfterFns: beforeAndAfterFns(suite), + expectationFactory: this.expectationFactory_, + asyncExpectationFactory: this.specAsyncExpectationFactory_, + onLateError: this.onLateError_, + resultCallback: (result, next) => { + this.specResultCallback_(spec, result, next) + }, + getSpecName: function(spec) { + return getSpecName(spec, suite) + }, + onStart: (spec, next) => this.specStarted_(spec, suite, next), + description: description, + userContext: function() { + return suite.clonedSharedUserContext() + }, + queueableFn: { + fn: fn, + timeout: timeout || 0, + }, + throwOnExpectationFailure: config.stopSpecOnExpectationFailure, + autoCleanClosures: config.autoCleanClosures, + timer: new j$.Timer(), + }) + return spec + } + + unfocusAncestor_() { + const focusedAncestor = findFocusedAncestor(this.currentDeclarationSuite_) + + if (focusedAncestor) { + for (let i = 0; i < this.focusedRunables.length; i++) { + if (this.focusedRunables[i] === focusedAncestor) { + this.focusedRunables.splice(i, 1) + break + } + } + } + } } - return null; - } + function findFocusedAncestor(suite) { + while (suite) { + if (suite.isFocused) { + return suite.id + } + suite = suite.parentSuite + } - function ensureIsFunction(fn, caller) { - if (!j$.isFunction_(fn)) { - throw new Error( - caller + ' expects a function argument; received ' + j$.getType_(fn) - ); + return null } - } - function ensureIsFunctionOrAsync(fn, caller) { - if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { - throw new Error( - caller + ' expects a function argument; received ' + j$.getType_(fn) - ); + function ensureIsFunction(fn, caller) { + if (!j$.isFunction_(fn)) { + throw new Error(caller + " expects a function argument; received " + j$.getType_(fn)) + } } - } - function beforeAndAfterFns(targetSuite) { - return function() { - let befores = [], - afters = [], - suite = targetSuite; - - while (suite) { - befores = befores.concat(suite.beforeFns); - afters = afters.concat(suite.afterFns); - - suite = suite.parentSuite; - } - - return { - befores: befores.reverse(), - afters: afters - }; - }; - } - - function getSpecName(spec, suite) { - const fullName = [spec.description], - suiteFullName = suite.getFullName(); - - if (suiteFullName !== '') { - fullName.unshift(suiteFullName); + function ensureIsFunctionOrAsync(fn, caller) { + if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { + throw new Error(caller + " expects a function argument; received " + j$.getType_(fn)) + } } - return fullName.join(' '); - } - return SuiteBuilder; -}; + function beforeAndAfterFns(targetSuite) { + return function() { + let befores = [], + afters = [], + suite = targetSuite + + while (suite) { + befores = befores.concat(suite.beforeFns) + afters = afters.concat(suite.afterFns) + + suite = suite.parentSuite + } + + return { + befores: befores.reverse(), + afters: afters, + } + } + } + + function getSpecName(spec, suite) { + const fullName = [spec.description], + suiteFullName = suite.getFullName() + + if (suiteFullName !== "") { + fullName.unshift(suiteFullName) + } + return fullName.join(" ") + } + + return SuiteBuilder +} getJasmineRequireObj().Timer = function() { - const defaultNow = (function(Date) { - return function() { - return new Date().getTime(); - }; - })(Date); + const defaultNow = (function(Date) { + return function() { + return new Date().getTime() + } + })(Date) - function Timer(options) { - options = options || {}; + function Timer(options) { + options = options || {} - const now = options.now || defaultNow; - let startTime; + const now = options.now || defaultNow + let startTime - this.start = function() { - startTime = now(); - }; + this.start = function() { + startTime = now() + } - this.elapsed = function() { - return now() - startTime; - }; - } + this.elapsed = function() { + return now() - startTime + } + } - return Timer; -}; + return Timer +} getJasmineRequireObj().TreeProcessor = function() { - function TreeProcessor(attrs) { - const tree = attrs.tree; - const runnableIds = attrs.runnableIds; - const queueRunnerFactory = attrs.queueRunnerFactory; - const nodeStart = attrs.nodeStart || function() {}; - const nodeComplete = attrs.nodeComplete || function() {}; - const failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations; - const orderChildren = - attrs.orderChildren || - function(node) { - return node.children; - }; - const excludeNode = - attrs.excludeNode || - function(node) { - return false; - }; - let stats = { valid: true }; - let processed = false; - const defaultMin = Infinity; - const defaultMax = 1 - Infinity; - - this.processTree = function() { - processNode(tree, true); - processed = true; - return stats; - }; - - this.execute = async function() { - if (!processed) { - this.processTree(); - } - - if (!stats.valid) { - throw 'invalid order'; - } - - const childFns = wrapChildren(tree, 0); - - await new Promise(function(resolve) { - queueRunnerFactory({ - queueableFns: childFns, - userContext: tree.sharedUserContext(), - onException: function() { - tree.handleException.apply(tree, arguments); - }, - onComplete: resolve, - onMultipleDone: tree.onMultipleDone - ? tree.onMultipleDone.bind(tree) - : null - }); - }); - }; - - function runnableIndex(id) { - for (let i = 0; i < runnableIds.length; i++) { - if (runnableIds[i] === id) { - return i; - } - } - } - - function processNode(node, parentExcluded) { - const executableIndex = runnableIndex(node.id); - - if (executableIndex !== undefined) { - parentExcluded = false; - } - - if (!node.children) { - const excluded = parentExcluded || excludeNode(node); - stats[node.id] = { - excluded: excluded, - willExecute: !excluded && !node.markedPending, - segments: [ - { - index: 0, - owner: node, - nodes: [node], - min: startingMin(executableIndex), - max: startingMax(executableIndex) + function TreeProcessor(attrs) { + const tree = attrs.tree + const runnableIds = attrs.runnableIds + const queueRunnerFactory = attrs.queueRunnerFactory + const nodeStart = attrs.nodeStart || function() {} + const nodeComplete = attrs.nodeComplete || function() {} + const failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations + const orderChildren = + attrs.orderChildren || + function(node) { + return node.children } - ] - }; - } else { - let hasExecutableChild = false; + const excludeNode = + attrs.excludeNode || + function(node) { + return false + } + let stats = { valid: true } + let processed = false + const defaultMin = Infinity + const defaultMax = 1 - Infinity - const orderedChildren = orderChildren(node); - - for (let i = 0; i < orderedChildren.length; i++) { - const child = orderedChildren[i]; - - processNode(child, parentExcluded); - - if (!stats.valid) { - return; - } - - const childStats = stats[child.id]; - - hasExecutableChild = hasExecutableChild || childStats.willExecute; + this.processTree = function() { + processNode(tree, true) + processed = true + return stats } - stats[node.id] = { - excluded: parentExcluded, - willExecute: hasExecutableChild - }; + this.execute = async function() { + if (!processed) { + this.processTree() + } - segmentChildren(node, orderedChildren, stats[node.id], executableIndex); + if (!stats.valid) { + throw "invalid order" + } - if (!node.canBeReentered() && stats[node.id].segments.length > 1) { - stats = { valid: false }; - } - } - } + const childFns = wrapChildren(tree, 0) - function startingMin(executableIndex) { - return executableIndex === undefined ? defaultMin : executableIndex; - } - - function startingMax(executableIndex) { - return executableIndex === undefined ? defaultMax : executableIndex; - } - - function segmentChildren( - node, - orderedChildren, - nodeStats, - executableIndex - ) { - let currentSegment = { - index: 0, - owner: node, - nodes: [], - min: startingMin(executableIndex), - max: startingMax(executableIndex) - }, - result = [currentSegment], - lastMax = defaultMax, - orderedChildSegments = orderChildSegments(orderedChildren); - - function isSegmentBoundary(minIndex) { - return ( - lastMax !== defaultMax && - minIndex !== defaultMin && - lastMax < minIndex - 1 - ); - } - - for (let i = 0; i < orderedChildSegments.length; i++) { - const childSegment = orderedChildSegments[i], - maxIndex = childSegment.max, - minIndex = childSegment.min; - - if (isSegmentBoundary(minIndex)) { - currentSegment = { - index: result.length, - owner: node, - nodes: [], - min: defaultMin, - max: defaultMax - }; - result.push(currentSegment); + await new Promise(function(resolve) { + queueRunnerFactory({ + queueableFns: childFns, + userContext: tree.sharedUserContext(), + onException: function() { + tree.handleException.apply(tree, arguments) + }, + onComplete: resolve, + onMultipleDone: tree.onMultipleDone ? tree.onMultipleDone.bind(tree) : null, + }) + }) } - currentSegment.nodes.push(childSegment); - currentSegment.min = Math.min(currentSegment.min, minIndex); - currentSegment.max = Math.max(currentSegment.max, maxIndex); - lastMax = maxIndex; - } - - nodeStats.segments = result; - } - - function orderChildSegments(children) { - const specifiedOrder = [], - unspecifiedOrder = []; - - for (let i = 0; i < children.length; i++) { - const child = children[i], - segments = stats[child.id].segments; - - for (let j = 0; j < segments.length; j++) { - const seg = segments[j]; - - if (seg.min === defaultMin) { - unspecifiedOrder.push(seg); - } else { - specifiedOrder.push(seg); - } + function runnableIndex(id) { + for (let i = 0; i < runnableIds.length; i++) { + if (runnableIds[i] === id) { + return i + } + } } - } - specifiedOrder.sort(function(a, b) { - return a.min - b.min; - }); + function processNode(node, parentExcluded) { + const executableIndex = runnableIndex(node.id) - return specifiedOrder.concat(unspecifiedOrder); + if (executableIndex !== undefined) { + parentExcluded = false + } + + if (!node.children) { + const excluded = parentExcluded || excludeNode(node) + stats[node.id] = { + excluded: excluded, + willExecute: !excluded && !node.markedPending, + segments: [ + { + index: 0, + owner: node, + nodes: [node], + min: startingMin(executableIndex), + max: startingMax(executableIndex), + }, + ], + } + } else { + let hasExecutableChild = false + + const orderedChildren = orderChildren(node) + + for (let i = 0; i < orderedChildren.length; i++) { + const child = orderedChildren[i] + + processNode(child, parentExcluded) + + if (!stats.valid) { + return + } + + const childStats = stats[child.id] + + hasExecutableChild = hasExecutableChild || childStats.willExecute + } + + stats[node.id] = { + excluded: parentExcluded, + willExecute: hasExecutableChild, + } + + segmentChildren(node, orderedChildren, stats[node.id], executableIndex) + + if (!node.canBeReentered() && stats[node.id].segments.length > 1) { + stats = { valid: false } + } + } + } + + function startingMin(executableIndex) { + return executableIndex === undefined ? defaultMin : executableIndex + } + + function startingMax(executableIndex) { + return executableIndex === undefined ? defaultMax : executableIndex + } + + function segmentChildren(node, orderedChildren, nodeStats, executableIndex) { + let currentSegment = { + index: 0, + owner: node, + nodes: [], + min: startingMin(executableIndex), + max: startingMax(executableIndex), + }, + result = [currentSegment], + lastMax = defaultMax, + orderedChildSegments = orderChildSegments(orderedChildren) + + function isSegmentBoundary(minIndex) { + return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1 + } + + for (let i = 0; i < orderedChildSegments.length; i++) { + const childSegment = orderedChildSegments[i], + maxIndex = childSegment.max, + minIndex = childSegment.min + + if (isSegmentBoundary(minIndex)) { + currentSegment = { + index: result.length, + owner: node, + nodes: [], + min: defaultMin, + max: defaultMax, + } + result.push(currentSegment) + } + + currentSegment.nodes.push(childSegment) + currentSegment.min = Math.min(currentSegment.min, minIndex) + currentSegment.max = Math.max(currentSegment.max, maxIndex) + lastMax = maxIndex + } + + nodeStats.segments = result + } + + function orderChildSegments(children) { + const specifiedOrder = [], + unspecifiedOrder = [] + + for (let i = 0; i < children.length; i++) { + const child = children[i], + segments = stats[child.id].segments + + for (let j = 0; j < segments.length; j++) { + const seg = segments[j] + + if (seg.min === defaultMin) { + unspecifiedOrder.push(seg) + } else { + specifiedOrder.push(seg) + } + } + } + + specifiedOrder.sort(function(a, b) { + return a.min - b.min + }) + + return specifiedOrder.concat(unspecifiedOrder) + } + + function executeNode(node, segmentNumber) { + if (node.children) { + return { + fn: function(done) { + const onStart = { + fn: function(next) { + nodeStart(node, next) + }, + } + + queueRunnerFactory({ + onComplete: function() { + const args = Array.prototype.slice.call(arguments, [0]) + node.cleanupBeforeAfter() + nodeComplete(node, node.getResult(), function() { + done.apply(undefined, args) + }) + }, + queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), + userContext: node.sharedUserContext(), + onException: function() { + node.handleException.apply(node, arguments) + }, + onMultipleDone: node.onMultipleDone ? node.onMultipleDone.bind(node) : null, + }) + }, + } + } else { + return { + fn: function(done) { + node.execute(queueRunnerFactory, done, stats[node.id].excluded, failSpecWithNoExpectations) + }, + } + } + } + + function wrapChildren(node, segmentNumber) { + const result = [], + segmentChildren = stats[node.id].segments[segmentNumber].nodes + + for (let i = 0; i < segmentChildren.length; i++) { + result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index)) + } + + if (!stats[node.id].willExecute) { + return result + } + + return node.beforeAllFns.concat(result).concat(node.afterAllFns) + } } - function executeNode(node, segmentNumber) { - if (node.children) { - return { - fn: function(done) { - const onStart = { - fn: function(next) { - nodeStart(node, next); - } - }; - - queueRunnerFactory({ - onComplete: function() { - const args = Array.prototype.slice.call(arguments, [0]); - node.cleanupBeforeAfter(); - nodeComplete(node, node.getResult(), function() { - done.apply(undefined, args); - }); - }, - queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), - userContext: node.sharedUserContext(), - onException: function() { - node.handleException.apply(node, arguments); - }, - onMultipleDone: node.onMultipleDone - ? node.onMultipleDone.bind(node) - : null - }); - } - }; - } else { - return { - fn: function(done) { - node.execute( - queueRunnerFactory, - done, - stats[node.id].excluded, - failSpecWithNoExpectations - ); - } - }; - } - } - - function wrapChildren(node, segmentNumber) { - const result = [], - segmentChildren = stats[node.id].segments[segmentNumber].nodes; - - for (let i = 0; i < segmentChildren.length; i++) { - result.push( - executeNode(segmentChildren[i].owner, segmentChildren[i].index) - ); - } - - if (!stats[node.id].willExecute) { - return result; - } - - return node.beforeAllFns.concat(result).concat(node.afterAllFns); - } - } - - return TreeProcessor; -}; + return TreeProcessor +} getJasmineRequireObj().UserContext = function(j$) { - function UserContext() {} + function UserContext() {} - UserContext.fromExisting = function(oldContext) { - const context = new UserContext(); + UserContext.fromExisting = function(oldContext) { + const context = new UserContext() - for (const prop in oldContext) { - if (oldContext.hasOwnProperty(prop)) { - context[prop] = oldContext[prop]; - } + for (const prop in oldContext) { + if (oldContext.hasOwnProperty(prop)) { + context[prop] = oldContext[prop] + } + } + + return context } - return context; - }; - - return UserContext; -}; + return UserContext +} getJasmineRequireObj().version = function() { - return '4.5.0'; -}; + return "4.5.0" +} diff --git a/ui/plugins/ui/jasmineSpec.js b/ui/plugins/ui/jasmineSpec.js index b97bbd4c..9637e9ac 100644 --- a/ui/plugins/ui/jasmineSpec.js +++ b/ui/plugins/ui/jasmineSpec.js @@ -2,34 +2,34 @@ const JASMINE_SESSION_ID = `jasmine-${String(Date.now()).slice(8)}` -beforeEach(function () { +beforeEach(function() { jasmine.DEFAULT_TIMEOUT_INTERVAL = 15 * 60 * 1000 // Test timeout after 15 minutes jasmine.addMatchers({ - toBeOneOf: function () { + toBeOneOf: function() { return { - compare: function (actual, expected) { + compare: function(actual, expected) { return { - pass: expected.includes(actual) + pass: expected.includes(actual), } - } + }, } - } + }, }) }) -describe('stable-diffusion-ui', function() { +describe("stable-diffusion-ui", function() { beforeEach(function() { - expect(typeof SD).toBe('object') - expect(typeof SD.serverState).toBe('object') - expect(typeof SD.serverState.status).toBe('string') + expect(typeof SD).toBe("object") + expect(typeof SD.serverState).toBe("object") + expect(typeof SD.serverState.status).toBe("string") }) - it('should be able to reach the backend', async function() { + it("should be able to reach the backend", async function() { expect(SD.serverState.status).toBe(SD.ServerStates.unavailable) SD.sessionId = JASMINE_SESSION_ID await SD.init() expect(SD.isServerAvailable()).toBeTrue() }) - it('enfore the current task state', function() { + it("enfore the current task state", function() { const task = new SD.Task() expect(task.status).toBe(SD.TaskStatus.init) expect(task.isPending).toBeTrue() @@ -65,149 +65,161 @@ describe('stable-diffusion-ui', function() { task._setStatus(SD.TaskStatus.completed) }).toThrowError() }) - it('should be able to run tasks', async function() { - expect(typeof SD.Task.run).toBe('function') + it("should be able to run tasks", async function() { + expect(typeof SD.Task.run).toBe("function") const promiseGenerator = (function*(val) { - expect(val).toBe('start') + expect(val).toBe("start") expect(yield 1 + 1).toBe(4) expect(yield 2 + 2).toBe(8) yield asyncDelay(500) expect(yield 3 + 3).toBe(12) expect(yield 4 + 4).toBe(16) return 8 + 8 - })('start') - const callback = function({value, done}) { - return {value: 2 * value, done} + })("start") + const callback = function({ value, done }) { + return { value: 2 * value, done } } - expect(await SD.Task.run(promiseGenerator, {callback})).toBe(32) + expect(await SD.Task.run(promiseGenerator, { callback })).toBe(32) }) - it('should be able to queue tasks', async function() { - expect(typeof SD.Task.enqueue).toBe('function') + it("should be able to queue tasks", async function() { + expect(typeof SD.Task.enqueue).toBe("function") const promiseGenerator = (function*(val) { - expect(val).toBe('start') + expect(val).toBe("start") expect(yield 1 + 1).toBe(4) expect(yield 2 + 2).toBe(8) yield asyncDelay(500) expect(yield 3 + 3).toBe(12) expect(yield 4 + 4).toBe(16) return 8 + 8 - })('start') - const callback = function({value, done}) { - return {value: 2 * value, done} + })("start") + const callback = function({ value, done }) { + return { value: 2 * value, done } } - const gen = SD.Task.asGenerator({generator: promiseGenerator, callback}) + const gen = SD.Task.asGenerator({ generator: promiseGenerator, callback }) expect(await SD.Task.enqueue(gen)).toBe(32) }) - it('should be able to chain handlers', async function() { - expect(typeof SD.Task.enqueue).toBe('function') + it("should be able to chain handlers", async function() { + expect(typeof SD.Task.enqueue).toBe("function") const promiseGenerator = (function*(val) { - expect(val).toBe('start') - expect(yield {test: '1'}).toEqual({test: '1', foo: 'bar'}) + expect(val).toBe("start") + expect(yield { test: "1" }).toEqual({ test: "1", foo: "bar" }) expect(yield 2 + 2).toEqual(8) yield asyncDelay(500) expect(yield 3 + 3).toEqual(12) - expect(yield {test: 4}).toEqual({test: 8, foo: 'bar'}) - return {test: 8} - })('start') - const gen1 = SD.Task.asGenerator({generator: promiseGenerator, callback: function({value, done}) { - if (typeof value === "object") { - value['foo'] = 'bar' - } - return {value, done} - }}) - const gen2 = SD.Task.asGenerator({generator: gen1, callback: function({value, done}) { - if (typeof value === 'number') { - value = 2 * value - } - if (typeof value === 'object' && typeof value.test === 'number') { - value.test = 2 * value.test - } - return {value, done} - }}) - expect(await SD.Task.enqueue(gen2)).toEqual({test:32, foo: 'bar'}) + expect(yield { test: 4 }).toEqual({ test: 8, foo: "bar" }) + return { test: 8 } + })("start") + const gen1 = SD.Task.asGenerator({ + generator: promiseGenerator, + callback: function({ value, done }) { + if (typeof value === "object") { + value["foo"] = "bar" + } + return { value, done } + }, + }) + const gen2 = SD.Task.asGenerator({ + generator: gen1, + callback: function({ value, done }) { + if (typeof value === "number") { + value = 2 * value + } + if (typeof value === "object" && typeof value.test === "number") { + value.test = 2 * value.test + } + return { value, done } + }, + }) + expect(await SD.Task.enqueue(gen2)).toEqual({ test: 32, foo: "bar" }) }) - describe('ServiceContainer', function() { - it('should be able to register providers', function() { + describe("ServiceContainer", function() { + it("should be able to register providers", function() { const cont = new ServiceContainer( function foo() { - this.bar = '' + this.bar = "" }, function bar() { return () => 0 }, - { name: 'zero', definition: 0 }, - { name: 'ctx', definition: () => Object.create(null), singleton: true }, - { name: 'test', + { name: "zero", definition: 0 }, + { name: "ctx", definition: () => Object.create(null), singleton: true }, + { + name: "test", definition: (ctx, missing, one, foo) => { - expect(ctx).toEqual({ran: true}) + expect(ctx).toEqual({ ran: true }) expect(one).toBe(1) - expect(typeof foo).toBe('object') + expect(typeof foo).toBe("object") expect(foo.bar).toBeDefined() - expect(typeof missing).toBe('undefined') - return {foo: 'bar'} - }, dependencies: ['ctx', 'missing', 'one', 'foo'] + expect(typeof missing).toBe("undefined") + return { foo: "bar" } + }, + dependencies: ["ctx", "missing", "one", "foo"], } ) - const fooObj = cont.get('foo') - expect(typeof fooObj).toBe('object') + const fooObj = cont.get("foo") + expect(typeof fooObj).toBe("object") fooObj.ran = true - const ctx = cont.get('ctx') + const ctx = cont.get("ctx") expect(ctx).toEqual({}) ctx.ran = true - const bar = cont.get('bar') - expect(typeof bar).toBe('function') + const bar = cont.get("bar") + expect(typeof bar).toBe("function") expect(bar()).toBe(0) - cont.register({name: 'one', definition: 1}) - const test = cont.get('test') - expect(typeof test).toBe('object') - expect(test.foo).toBe('bar') + cont.register({ name: "one", definition: 1 }) + const test = cont.get("test") + expect(typeof test).toBe("object") + expect(test.foo).toBe("bar") }) }) - it('should be able to stream data in chunks', async function() { + it("should be able to stream data in chunks", async function() { expect(SD.isServerAvailable()).toBeTrue() const nbr_steps = 15 - let res = await fetch('/render', { - method: 'POST', + let res = await fetch("/render", { + method: "POST", headers: { - 'Content-Type': 'application/json' + "Content-Type": "application/json", }, body: JSON.stringify({ - "prompt": "a photograph of an astronaut riding a horse", - "negative_prompt": "", - "width": 128, - "height": 128, - "seed": Math.floor(Math.random() * 10000000), + prompt: "a photograph of an astronaut riding a horse", + negative_prompt: "", + width: 128, + height: 128, + seed: Math.floor(Math.random() * 10000000), - "sampler": "plms", - "use_stable_diffusion_model": "sd-v1-4", - "num_inference_steps": nbr_steps, - "guidance_scale": 7.5, + sampler: "plms", + use_stable_diffusion_model: "sd-v1-4", + num_inference_steps: nbr_steps, + guidance_scale: 7.5, - "numOutputsParallel": 1, - "stream_image_progress": true, - "show_only_filtered_image": true, - "output_format": "jpeg", + numOutputsParallel: 1, + stream_image_progress: true, + show_only_filtered_image: true, + output_format: "jpeg", - "session_id": JASMINE_SESSION_ID, + session_id: JASMINE_SESSION_ID, }), }) expect(res.ok).toBeTruthy() const renderRequest = await res.json() - expect(typeof renderRequest.stream).toBe('string') + expect(typeof renderRequest.stream).toBe("string") expect(renderRequest.task).toBeDefined() // Wait for server status to update. - await SD.waitUntil(() => { - console.log('Waiting for %s to be received...', renderRequest.task) - return (!SD.serverState.tasks || SD.serverState.tasks[String(renderRequest.task)]) - }, 250, 10 * 60 * 1000) + await SD.waitUntil( + () => { + console.log("Waiting for %s to be received...", renderRequest.task) + return !SD.serverState.tasks || SD.serverState.tasks[String(renderRequest.task)] + }, + 250, + 10 * 60 * 1000 + ) // Wait for task to start on server. await SD.waitUntil(() => { - console.log('Waiting for %s to start...', renderRequest.task) - return !SD.serverState.tasks || SD.serverState.tasks[String(renderRequest.task)] !== 'pending' + console.log("Waiting for %s to start...", renderRequest.task) + return !SD.serverState.tasks || SD.serverState.tasks[String(renderRequest.task)] !== "pending" }, 250) const reader = new SD.ChunkedStreamReader(renderRequest.stream) @@ -217,24 +229,24 @@ describe('stable-diffusion-ui', function() { if (!value || value.length <= 0) { return } - return reader.readStreamAsJSON(value.join('')) + return reader.readStreamAsJSON(value.join("")) } - reader.onNext = function({done, value}) { + reader.onNext = function({ done, value }) { console.log(value) - if (typeof value === 'object' && 'status' in value) { + if (typeof value === "object" && "status" in value) { done = true } - return {done, value} + return { done, value } } let lastUpdate = undefined let stepCount = 0 let complete = false //for await (const stepUpdate of reader) { for await (const stepUpdate of reader.open()) { - console.log('ChunkedStreamReader received ', stepUpdate) + console.log("ChunkedStreamReader received ", stepUpdate) lastUpdate = stepUpdate if (complete) { - expect(stepUpdate.status).toBe('succeeded') + expect(stepUpdate.status).toBe("succeeded") expect(stepUpdate.output).toHaveSize(1) } else { expect(stepUpdate.total_steps).toBe(nbr_steps) @@ -246,70 +258,76 @@ describe('stable-diffusion-ui', function() { } } } - for(let i=1; i <= 5; ++i) { + for (let i = 1; i <= 5; ++i) { res = await fetch(renderRequest.stream) expect(res.ok).toBeTruthy() const cachedResponse = await res.json() - console.log('Cache test %s received %o', i, cachedResponse) + console.log("Cache test %s received %o", i, cachedResponse) expect(lastUpdate).toEqual(cachedResponse) } }) - describe('should be able to make renders', function() { + describe("should be able to make renders", function() { beforeEach(function() { expect(SD.isServerAvailable()).toBeTrue() }) - it('basic inline request', async function() { + it("basic inline request", async function() { let stepCount = 0 let complete = false - const result = await SD.render({ - "prompt": "a photograph of an astronaut riding a horse", - "width": 128, - "height": 128, - "num_inference_steps": 10, - "show_only_filtered_image": false, - //"use_face_correction": 'GFPGANv1.3', - "use_upscale": "RealESRGAN_x4plus", - "session_id": JASMINE_SESSION_ID, - }, function(event) { - console.log(this, event) - if ('update' in event) { - const stepUpdate = event.update - if (complete || (stepUpdate.status && stepUpdate.step === stepUpdate.total_steps)) { - expect(stepUpdate.status).toBe('succeeded') - expect(stepUpdate.output).toHaveSize(2) - } else { - expect(stepUpdate.step).toBe(stepCount) - if (stepUpdate.step === stepUpdate.total_steps) { - complete = true + const result = await SD.render( + { + prompt: "a photograph of an astronaut riding a horse", + width: 128, + height: 128, + num_inference_steps: 10, + show_only_filtered_image: false, + //"use_face_correction": 'GFPGANv1.3', + use_upscale: "RealESRGAN_x4plus", + session_id: JASMINE_SESSION_ID, + }, + function(event) { + console.log(this, event) + if ("update" in event) { + const stepUpdate = event.update + if (complete || (stepUpdate.status && stepUpdate.step === stepUpdate.total_steps)) { + expect(stepUpdate.status).toBe("succeeded") + expect(stepUpdate.output).toHaveSize(2) } else { - stepCount++ + expect(stepUpdate.step).toBe(stepCount) + if (stepUpdate.step === stepUpdate.total_steps) { + complete = true + } else { + stepCount++ + } } } } - }) + ) console.log(result) - expect(result.status).toBe('succeeded') + expect(result.status).toBe("succeeded") expect(result.output).toHaveSize(2) }) - it('post and reader request', async function() { + it("post and reader request", async function() { const renderTask = new SD.RenderTask({ - "prompt": "a photograph of an astronaut riding a horse", - "width": 128, - "height": 128, - "seed": SD.MAX_SEED_VALUE, - "num_inference_steps": 10, - "session_id": JASMINE_SESSION_ID, + prompt: "a photograph of an astronaut riding a horse", + width: 128, + height: 128, + seed: SD.MAX_SEED_VALUE, + num_inference_steps: 10, + session_id: JASMINE_SESSION_ID, }) expect(renderTask.status).toBe(SD.TaskStatus.init) const timeout = -1 const renderRequest = await renderTask.post(timeout) - expect(typeof renderRequest.stream).toBe('string') + expect(typeof renderRequest.stream).toBe("string") expect(renderTask.status).toBe(SD.TaskStatus.waiting) expect(renderTask.streamUrl).toBe(renderRequest.stream) - await renderTask.waitUntil({state: SD.TaskStatus.processing, callback: () => console.log('Waiting for render task to start...') }) + await renderTask.waitUntil({ + state: SD.TaskStatus.processing, + callback: () => console.log("Waiting for render task to start..."), + }) expect(renderTask.status).toBe(SD.TaskStatus.processing) let stepCount = 0 @@ -318,7 +336,7 @@ describe('stable-diffusion-ui', function() { for await (const stepUpdate of renderTask.reader.open()) { console.log(stepUpdate) if (complete || (stepUpdate.status && stepUpdate.step === stepUpdate.total_steps)) { - expect(stepUpdate.status).toBe('succeeded') + expect(stepUpdate.status).toBe("succeeded") expect(stepUpdate.output).toHaveSize(1) } else { expect(stepUpdate.step).toBe(stepCount) @@ -330,28 +348,28 @@ describe('stable-diffusion-ui', function() { } } expect(renderTask.status).toBe(SD.TaskStatus.completed) - expect(renderTask.result.status).toBe('succeeded') + expect(renderTask.result.status).toBe("succeeded") expect(renderTask.result.output).toHaveSize(1) }) - it('queued request', async function() { + it("queued request", async function() { let stepCount = 0 let complete = false const renderTask = new SD.RenderTask({ - "prompt": "a photograph of an astronaut riding a horse", - "width": 128, - "height": 128, - "num_inference_steps": 10, - "show_only_filtered_image": false, + prompt: "a photograph of an astronaut riding a horse", + width: 128, + height: 128, + num_inference_steps: 10, + show_only_filtered_image: false, //"use_face_correction": 'GFPGANv1.3', - "use_upscale": "RealESRGAN_x4plus", - "session_id": JASMINE_SESSION_ID, + use_upscale: "RealESRGAN_x4plus", + session_id: JASMINE_SESSION_ID, }) await renderTask.enqueue(function(event) { console.log(this, event) - if ('update' in event) { + if ("update" in event) { const stepUpdate = event.update if (complete || (stepUpdate.status && stepUpdate.step === stepUpdate.total_steps)) { - expect(stepUpdate.status).toBe('succeeded') + expect(stepUpdate.status).toBe("succeeded") expect(stepUpdate.output).toHaveSize(2) } else { expect(stepUpdate.step).toBe(stepCount) @@ -364,12 +382,12 @@ describe('stable-diffusion-ui', function() { } }) console.log(renderTask.result) - expect(renderTask.result.status).toBe('succeeded') + expect(renderTask.result.status).toBe("succeeded") expect(renderTask.result.output).toHaveSize(2) }) }) - describe('# Special cases', function() { - it('should throw an exception on set for invalid sessionId', function() { + describe("# Special cases", function() { + it("should throw an exception on set for invalid sessionId", function() { expect(function() { SD.sessionId = undefined }).toThrowError("Can't set sessionId to undefined.") @@ -386,16 +404,17 @@ if (!PLUGINS.SELFTEST) { PLUGINS.SELFTEST = {} } loadUIPlugins().then(function() { - console.log('loadCompleted', loadEvent) - describe('@Plugins', function() { - it('exposes hooks to overide', function() { - expect(typeof PLUGINS.IMAGE_INFO_BUTTONS).toBe('object') - expect(typeof PLUGINS.TASK_CREATE).toBe('object') + console.log("loadCompleted", loadEvent) + describe("@Plugins", function() { + it("exposes hooks to overide", function() { + expect(typeof PLUGINS.IMAGE_INFO_BUTTONS).toBe("object") + expect(typeof PLUGINS.TASK_CREATE).toBe("object") }) - describe('supports selftests', function() { // Hook to allow plugins to define tests. + describe("supports selftests", function() { + // Hook to allow plugins to define tests. const pluginsTests = Object.keys(PLUGINS.SELFTEST).filter((key) => PLUGINS.SELFTEST.hasOwnProperty(key)) if (!pluginsTests || pluginsTests.length <= 0) { - it('but nothing loaded...', function() { + it("but nothing loaded...", function() { expect(true).toBeTruthy() }) return diff --git a/ui/plugins/ui/merge.plugin.js b/ui/plugins/ui/merge.plugin.js index 6ff97286..d3ddedbf 100644 --- a/ui/plugins/ui/merge.plugin.js +++ b/ui/plugins/ui/merge.plugin.js @@ -1,4 +1,4 @@ -(function() { +;(function() { "use strict" ///////////////////// Function section @@ -18,146 +18,133 @@ return y } function getCurrentTime() { - const now = new Date(); - let hours = now.getHours(); - let minutes = now.getMinutes(); - let seconds = now.getSeconds(); + const now = new Date() + let hours = now.getHours() + let minutes = now.getMinutes() + let seconds = now.getSeconds() - hours = hours < 10 ? `0${hours}` : hours; - minutes = minutes < 10 ? `0${minutes}` : minutes; - seconds = seconds < 10 ? `0${seconds}` : seconds; + hours = hours < 10 ? `0${hours}` : hours + minutes = minutes < 10 ? `0${minutes}` : minutes + seconds = seconds < 10 ? `0${seconds}` : seconds - return `${hours}:${minutes}:${seconds}`; + return `${hours}:${minutes}:${seconds}` } function addLogMessage(message) { - const logContainer = document.getElementById('merge-log'); - logContainer.innerHTML += `${getCurrentTime()} ${message}
    `; + const logContainer = document.getElementById("merge-log") + logContainer.innerHTML += `${getCurrentTime()} ${message}
    ` // Scroll to the bottom of the log - logContainer.scrollTop = logContainer.scrollHeight; + logContainer.scrollTop = logContainer.scrollHeight - document.querySelector('#merge-log-container').style.display = 'block' - } + document.querySelector("#merge-log-container").style.display = "block" + } function addLogSeparator() { - const logContainer = document.getElementById('merge-log'); - logContainer.innerHTML += '
    ' + const logContainer = document.getElementById("merge-log") + logContainer.innerHTML += "
    " - logContainer.scrollTop = logContainer.scrollHeight; + logContainer.scrollTop = logContainer.scrollHeight } function drawDiagram(fn) { const SIZE = 300 - const canvas = document.getElementById('merge-canvas'); + const canvas = document.getElementById("merge-canvas") canvas.height = canvas.width = SIZE - const ctx = canvas.getContext('2d'); + const ctx = canvas.getContext("2d") // Draw coordinate system - ctx.scale(1, -1); - ctx.translate(0, -canvas.height); - ctx.lineWidth = 1; - ctx.beginPath(); + ctx.scale(1, -1) + ctx.translate(0, -canvas.height) + ctx.lineWidth = 1 + ctx.beginPath() - ctx.strokeStyle = 'white' - ctx.moveTo(0,0); ctx.lineTo(0,SIZE); ctx.lineTo(SIZE,SIZE); ctx.lineTo(SIZE,0); ctx.lineTo(0,0); ctx.lineTo(SIZE,SIZE); + ctx.strokeStyle = "white" + ctx.moveTo(0, 0) + ctx.lineTo(0, SIZE) + ctx.lineTo(SIZE, SIZE) + ctx.lineTo(SIZE, 0) + ctx.lineTo(0, 0) + ctx.lineTo(SIZE, SIZE) ctx.stroke() ctx.beginPath() - ctx.setLineDash([1,2]) + ctx.setLineDash([1, 2]) const n = SIZE / 10 - for (let i=n; i>0 + let start = parseFloat(document.querySelector("#merge-start").value) + let step = parseFloat(document.querySelector("#merge-step").value) + let iterations = document.querySelector("#merge-count").value >> 0 ctx.beginPath() ctx.fillStyle = "yellow" - for (let i=0; i< iterations; i++) { - const alpha = ( start + i * step ) / 100 - const x = alpha*SIZE + for (let i = 0; i < iterations; i++) { + const alpha = (start + i * step) / 100 + const x = alpha * SIZE const y = fn(alpha) * SIZE if (x <= SIZE) { - ctx.rect(x-3,y-3,6,6) + ctx.rect(x - 3, y - 3, 6, 6) ctx.fill() } else { - ctx.strokeStyle = 'red' - ctx.moveTo(0,0); ctx.lineTo(0,SIZE); ctx.lineTo(SIZE,SIZE); ctx.lineTo(SIZE,0); ctx.lineTo(0,0); ctx.lineTo(SIZE,SIZE); + ctx.strokeStyle = "red" + ctx.moveTo(0, 0) + ctx.lineTo(0, SIZE) + ctx.lineTo(SIZE, SIZE) + ctx.lineTo(SIZE, 0) + ctx.lineTo(0, 0) + ctx.lineTo(SIZE, SIZE) ctx.stroke() - addLogMessage('Warning: maximum ratio is ≥ 100%') + addLogMessage("Warning: maximum ratio is ≥ 100%") } } } function updateChart() { let fn = (x) => x - switch (document.querySelector('#merge-interpolation').value) { - case 'SmoothStep': + switch (document.querySelector("#merge-interpolation").value) { + case "SmoothStep": fn = smoothstep break - case 'SmootherStep': + case "SmootherStep": fn = smootherstep break - case 'SmoothestStep': + case "SmoothestStep": fn = smootheststep break } drawDiagram(fn) } - - /////////////////////// Tab implementation - document.querySelector('.tab-container')?.insertAdjacentHTML('beforeend', ` - - Merge models - - `) - - document.querySelector('#tab-content-wrapper')?.insertAdjacentHTML('beforeend', ` -
    -
    - Loading.. -
    -
    - `) - - const tabMerge = document.querySelector('#tab-merge') - if (tabMerge) { - linkTabContents(tabMerge) - } - const merge = document.querySelector('#merge') - if (!merge) { - // merge tab not found, dont exec plugin code. - return - } - - document.querySelector('body').insertAdjacentHTML('beforeend', ` - - `) - - merge.innerHTML = ` -
    -
    -

    - -

    - -

    -

    Important: Please merge models of similar type.
    For e.g. SD 1.4 models with only SD 1.4/1.5 models,
    SD 2.0 with SD 2.0-type, and SD 2.1 with SD 2.1-type models.

    -
    - - - - - - - - - - - - - -
    Base name of the output file.
    Mix ratio and file suffix will be appended to this.
    - Image generation uses fp16, so it's a good choice.
    Use fp32 if you want to use the result models for more mixes
    -
    -
    -
    -
    -

    -
    -
    -
    -
    -
    - - Make a single file - - - Make multiple variations - -
    -
    -
    -
    - Saves a single merged model file, at the specified merge ratio.

    - - - % - Model A's contribution to the mix. The rest will be from Model B. + }`, + content: ` +
    +
    +

    + +

    + +

    +

    Important: Please merge models of similar type.
    For e.g. SD 1.4 models with only SD 1.4/1.5 models,
    SD 2.0 with SD 2.0-type, and SD 2.1 with SD 2.1-type models.

    +
    + + + + + + + + + + + + + +
    Base name of the output file.
    Mix ratio and file suffix will be appended to this.
    + Image generation uses fp16, so it's a good choice.
    Use fp32 if you want to use the result models for more mixes
    +
    +
    +
    +
    +

    +
    +
    +
    +
    +
    + + Make a single file + + + Make multiple variations + +
    +
    +
    +
    + Saves a single merged model file, at the specified merge ratio.

    + + + % + Model A's contribution to the mix. The rest will be from Model B. +
    -
    -
    -
    - Saves multiple variations of the model, at different merge ratios.
    Each variation will be saved as a separate file.


    - - - - - - - - - - - - - -
    Number of models to create
    % Smallest share of model A in the mix
    % Share of model A added into the mix per step
    Sigmoid function to be applied to the model share before mixing
    -
    - Preview of variation ratios:
    - +
    +
    + Saves multiple variations of the model, at different merge ratios.
    Each variation will be saved as a separate file.


    + + + + + + + + + + + + + +
    Number of models to create
    % Smallest share of model A in the mix
    % Share of model A added into the mix per step
    Sigmoid function to be applied to the model share before mixing
    +
    + Preview of variation ratios:
    + +
    -
    -
    -
    -
    - -
    -
    ` - - const tabSettingsSingle = document.querySelector('#tab-merge-opts-single') - const tabSettingsBatch = document.querySelector('#tab-merge-opts-batch') - linkTabContents(tabSettingsSingle) - linkTabContents(tabSettingsBatch) - - console.log('Activate') - let mergeModelAField = new ModelDropdown(document.querySelector('#mergeModelA'), 'stable-diffusion') - let mergeModelBField = new ModelDropdown(document.querySelector('#mergeModelB'), 'stable-diffusion') - updateChart() - - // slider - const singleMergeRatioField = document.querySelector('#single-merge-ratio') - const singleMergeRatioSlider = document.querySelector('#single-merge-ratio-slider') - - function updateSingleMergeRatio() { - singleMergeRatioField.value = singleMergeRatioSlider.value / 10 - singleMergeRatioField.dispatchEvent(new Event("change")) - } - - function updateSingleMergeRatioSlider() { - if (singleMergeRatioField.value < 0) { - singleMergeRatioField.value = 0 - } else if (singleMergeRatioField.value > 100) { - singleMergeRatioField.value = 100 - } - - singleMergeRatioSlider.value = singleMergeRatioField.value * 10 - singleMergeRatioSlider.dispatchEvent(new Event("change")) - } - - singleMergeRatioSlider.addEventListener('input', updateSingleMergeRatio) - singleMergeRatioField.addEventListener('input', updateSingleMergeRatioSlider) - updateSingleMergeRatio() - - document.querySelector('.merge-config').addEventListener('change', updateChart) - - document.querySelector('#merge-button').addEventListener('click', async function(e) { - // Build request template - let model0 = mergeModelAField.value - let model1 = mergeModelBField.value - let request = { model0: model0, model1: model1 } - request['use_fp16'] = document.querySelector('#merge-fp').value == 'fp16' - let iterations = document.querySelector('#merge-count').value>>0 - let start = parseFloat( document.querySelector('#merge-start').value ) - let step = parseFloat( document.querySelector('#merge-step').value ) - - if (isTabActive(tabSettingsSingle)) { - start = parseFloat(singleMergeRatioField.value) - step = 0 - iterations = 1 - addLogMessage(`merge ratio = ${start}%`) - } else { - addLogMessage(`start = ${start}%`) - addLogMessage(`step = ${step}%`) - } - - if (start + (iterations-1) * step >= 100) { - addLogMessage('Aborting: maximum ratio is ≥ 100%') - addLogMessage('Reduce the number of variations or the step size') - addLogSeparator() - document.querySelector('#merge-count').focus() - return - } - - if (document.querySelector('#merge-filename').value == "") { - addLogMessage('Aborting: No output file name specified') - addLogSeparator() - document.querySelector('#merge-filename').focus() - return - } - - // Disable merge button - e.target.disabled=true - e.target.classList.add('disabled') - let cursor = $("body").css("cursor"); - let label = document.querySelector('#merge-button').innerHTML - $("body").css("cursor", "progress"); - document.querySelector('#merge-button').innerHTML = 'Merging models ...' - - addLogMessage("Merging models") - addLogMessage("Model A: "+model0) - addLogMessage("Model B: "+model1) - - // Batch main loop - for (let i=0; i +
    +
    + +
    +
    `, + onOpen: ({ firstOpen }) => { + if (!firstOpen) { + return } - addLogMessage(`merging batch job ${i+1}/${iterations}, alpha = ${alpha.toFixed(5)}...`) - request['out_path'] = document.querySelector('#merge-filename').value - request['out_path'] += '-' + alpha.toFixed(5) + '.' + document.querySelector('#merge-format').value - addLogMessage(`  filename: ${request['out_path']}`) + const tabSettingsSingle = document.querySelector("#tab-merge-opts-single") + const tabSettingsBatch = document.querySelector("#tab-merge-opts-batch") + linkTabContents(tabSettingsSingle) + linkTabContents(tabSettingsBatch) - request['ratio'] = alpha - let res = await fetch('/model/merge', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(request) }) - const data = await res.json(); - addLogMessage(JSON.stringify(data)) - } - addLogMessage("Done. The models have been saved to your models/stable-diffusion folder.") - addLogSeparator() - // Re-enable merge button - $("body").css("cursor", cursor); - document.querySelector('#merge-button').innerHTML = label - e.target.disabled=false - e.target.classList.remove('disabled') + console.log("Activate") + let mergeModelAField = new ModelDropdown(document.querySelector("#mergeModelA"), "stable-diffusion") + let mergeModelBField = new ModelDropdown(document.querySelector("#mergeModelB"), "stable-diffusion") + updateChart() - // Update model list - stableDiffusionModelField.innerHTML = '' - vaeModelField.innerHTML = '' - hypernetworkModelField.innerHTML = '' - await getModels() + // slider + const singleMergeRatioField = document.querySelector("#single-merge-ratio") + const singleMergeRatioSlider = document.querySelector("#single-merge-ratio-slider") + + function updateSingleMergeRatio() { + singleMergeRatioField.value = singleMergeRatioSlider.value / 10 + singleMergeRatioField.dispatchEvent(new Event("change")) + } + + function updateSingleMergeRatioSlider() { + if (singleMergeRatioField.value < 0) { + singleMergeRatioField.value = 0 + } else if (singleMergeRatioField.value > 100) { + singleMergeRatioField.value = 100 + } + + singleMergeRatioSlider.value = singleMergeRatioField.value * 10 + singleMergeRatioSlider.dispatchEvent(new Event("change")) + } + + singleMergeRatioSlider.addEventListener("input", updateSingleMergeRatio) + singleMergeRatioField.addEventListener("input", updateSingleMergeRatioSlider) + updateSingleMergeRatio() + + document.querySelector(".merge-config").addEventListener("change", updateChart) + + document.querySelector("#merge-button").addEventListener("click", async function(e) { + // Build request template + let model0 = mergeModelAField.value + let model1 = mergeModelBField.value + let request = { model0: model0, model1: model1 } + request["use_fp16"] = document.querySelector("#merge-fp").value == "fp16" + let iterations = document.querySelector("#merge-count").value >> 0 + let start = parseFloat(document.querySelector("#merge-start").value) + let step = parseFloat(document.querySelector("#merge-step").value) + + if (isTabActive(tabSettingsSingle)) { + start = parseFloat(singleMergeRatioField.value) + step = 0 + iterations = 1 + addLogMessage(`merge ratio = ${start}%`) + } else { + addLogMessage(`start = ${start}%`) + addLogMessage(`step = ${step}%`) + } + + if (start + (iterations - 1) * step >= 100) { + addLogMessage("Aborting: maximum ratio is ≥ 100%") + addLogMessage("Reduce the number of variations or the step size") + addLogSeparator() + document.querySelector("#merge-count").focus() + return + } + + if (document.querySelector("#merge-filename").value == "") { + addLogMessage("Aborting: No output file name specified") + addLogSeparator() + document.querySelector("#merge-filename").focus() + return + } + + // Disable merge button + e.target.disabled = true + e.target.classList.add("disabled") + let cursor = $("body").css("cursor") + let label = document.querySelector("#merge-button").innerHTML + $("body").css("cursor", "progress") + document.querySelector("#merge-button").innerHTML = "Merging models ..." + + addLogMessage("Merging models") + addLogMessage("Model A: " + model0) + addLogMessage("Model B: " + model1) + + // Batch main loop + for (let i = 0; i < iterations; i++) { + let alpha = (start + i * step) / 100 + + if (isTabActive(tabSettingsBatch)) { + switch (document.querySelector("#merge-interpolation").value) { + case "SmoothStep": + alpha = smoothstep(alpha) + break + case "SmootherStep": + alpha = smootherstep(alpha) + break + case "SmoothestStep": + alpha = smootheststep(alpha) + break + } + } + addLogMessage(`merging batch job ${i + 1}/${iterations}, alpha = ${alpha.toFixed(5)}...`) + + request["out_path"] = document.querySelector("#merge-filename").value + request["out_path"] += "-" + alpha.toFixed(5) + "." + document.querySelector("#merge-format").value + addLogMessage(`  filename: ${request["out_path"]}`) + + // sdkit documentation: "ratio - the ratio of the second model. 1 means only the second model will be used." + request["ratio"] = 1-alpha + let res = await fetch("/model/merge", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(request), + }) + const data = await res.json() + addLogMessage(JSON.stringify(data)) + } + addLogMessage( + "Done. The models have been saved to your models/stable-diffusion folder." + ) + addLogSeparator() + // Re-enable merge button + $("body").css("cursor", cursor) + document.querySelector("#merge-button").innerHTML = label + e.target.disabled = false + e.target.classList.remove("disabled") + + // Update model list + stableDiffusionModelField.innerHTML = "" + vaeModelField.innerHTML = "" + hypernetworkModelField.innerHTML = "" + await getModels() + }) + }, }) - })() diff --git a/ui/plugins/ui/modifiers-toggle.plugin.js b/ui/plugins/ui/modifiers-toggle.plugin.js index 14eb5627..74b3666e 100644 --- a/ui/plugins/ui/modifiers-toggle.plugin.js +++ b/ui/plugins/ui/modifiers-toggle.plugin.js @@ -1,52 +1,52 @@ -(function () { +;(function() { "use strict" - var styleSheet = document.createElement("style"); + var styleSheet = document.createElement("style") styleSheet.textContent = ` .modifier-card-tiny.modifier-toggle-inactive { background: transparent; border: 2px dashed red; opacity:0.2; } - `; - document.head.appendChild(styleSheet); + ` + document.head.appendChild(styleSheet) // observe for changes in tag list - var observer = new MutationObserver(function (mutations) { - // mutations.forEach(function (mutation) { - if (editorModifierTagsList.childNodes.length > 0) { - ModifierToggle() - } - // }) + var observer = new MutationObserver(function(mutations) { + // mutations.forEach(function (mutation) { + if (editorModifierTagsList.childNodes.length > 0) { + ModifierToggle() + } + // }) }) observer.observe(editorModifierTagsList, { - childList: true + childList: true, }) function ModifierToggle() { - let overlays = document.querySelector('#editor-inputs-tags-list').querySelectorAll('.modifier-card-overlay') - overlays.forEach (i => { + let overlays = document.querySelector("#editor-inputs-tags-list").querySelectorAll(".modifier-card-overlay") + overlays.forEach((i) => { i.oncontextmenu = (e) => { e.preventDefault() - if (i.parentElement.classList.contains('modifier-toggle-inactive')) { - i.parentElement.classList.remove('modifier-toggle-inactive') - } - else - { - i.parentElement.classList.add('modifier-toggle-inactive') + if (i.parentElement.classList.contains("modifier-toggle-inactive")) { + i.parentElement.classList.remove("modifier-toggle-inactive") + } else { + i.parentElement.classList.add("modifier-toggle-inactive") } // refresh activeTags - let modifierName = i.parentElement.getElementsByClassName('modifier-card-label')[0].getElementsByTagName("p")[0].dataset.fullName - activeTags = activeTags.map(obj => { + let modifierName = i.parentElement + .getElementsByClassName("modifier-card-label")[0] + .getElementsByTagName("p")[0].dataset.fullName + activeTags = activeTags.map((obj) => { if (trimModifiers(obj.name) === trimModifiers(modifierName)) { - return {...obj, inactive: (obj.element.classList.contains('modifier-toggle-inactive'))}; + return { ...obj, inactive: obj.element.classList.contains("modifier-toggle-inactive") } } - - return obj; - }); - document.dispatchEvent(new Event('refreshImageModifiers')) + + return obj + }) + document.dispatchEvent(new Event("refreshImageModifiers")) } }) } diff --git a/ui/plugins/ui/release-notes.plugin.js b/ui/plugins/ui/release-notes.plugin.js index da7b79de..b0746d65 100644 --- a/ui/plugins/ui/release-notes.plugin.js +++ b/ui/plugins/ui/release-notes.plugin.js @@ -1,64 +1,53 @@ -(function() { +;(function() { // Register selftests when loaded by jasmine. - if (typeof PLUGINS?.SELFTEST === 'object') { + if (typeof PLUGINS?.SELFTEST === "object") { PLUGINS.SELFTEST["release-notes"] = function() { - it('should be able to fetch CHANGES.md', async function() { - let releaseNotes = await fetch(`https://raw.githubusercontent.com/cmdr2/stable-diffusion-ui/main/CHANGES.md`) + it("should be able to fetch CHANGES.md", async function() { + let releaseNotes = await fetch( + `https://raw.githubusercontent.com/easydiffusion/easydiffusion/main/CHANGES.md` + ) expect(releaseNotes.status).toBe(200) }) } } - document.querySelector('.tab-container')?.insertAdjacentHTML('beforeend', ` - - What's new? - - `) - - document.querySelector('#tab-content-wrapper')?.insertAdjacentHTML('beforeend', ` -
    -
    - Loading.. -
    -
    - `) - - const tabNews = document.querySelector('#tab-news') - if (tabNews) { - linkTabContents(tabNews) - } - const news = document.querySelector('#news') - if (!news) { - // news tab not found, dont exec plugin code. - return - } - - document.querySelector('body').insertAdjacentHTML('beforeend', ` - - `) + `, + onOpen: async ({ firstOpen }) => { + if (firstOpen) { + const loadMarkedScriptPromise = loadScript("/media/js/marked.min.js") - loadScript('/media/js/marked.min.js').then(async function() { - let appConfig = await fetch('/get/app_config') - if (!appConfig.ok) { - console.error('[release-notes] Failed to get app_config.') - return - } - appConfig = await appConfig.json() + let appConfig = await fetch("/get/app_config") + if (!appConfig.ok) { + console.error("[release-notes] Failed to get app_config.") + return + } + appConfig = await appConfig.json() - const updateBranch = appConfig.update_branch || 'main' + const updateBranch = appConfig.update_branch || "main" - let releaseNotes = await fetch(`https://raw.githubusercontent.com/cmdr2/stable-diffusion-ui/${updateBranch}/CHANGES.md`) - if (!releaseNotes.ok) { - console.error('[release-notes] Failed to get CHANGES.md.') - return - } - releaseNotes = await releaseNotes.text() - news.innerHTML = marked.parse(releaseNotes) + let releaseNotes = await fetch( + `https://raw.githubusercontent.com/easydiffusion/easydiffusion/${updateBranch}/CHANGES.md` + ) + if (!releaseNotes.ok) { + console.error("[release-notes] Failed to get CHANGES.md.") + return + } + releaseNotes = await releaseNotes.text() + + await loadMarkedScriptPromise + + return marked.parse(releaseNotes) + } + }, }) -})() \ No newline at end of file +})() diff --git a/ui/plugins/ui/selftest.plugin.js b/ui/plugins/ui/selftest.plugin_.js similarity index 60% rename from ui/plugins/ui/selftest.plugin.js rename to ui/plugins/ui/selftest.plugin_.js index f7c59eb1..b615852d 100644 --- a/ui/plugins/ui/selftest.plugin.js +++ b/ui/plugins/ui/selftest.plugin_.js @@ -1,6 +1,7 @@ /* SD-UI Selftest Plugin.js */ -(function() { "use strict" +;(function() { + "use strict" const ID_PREFIX = "selftest-plugin" const links = document.getElementById("community-links") @@ -10,16 +11,18 @@ } // Add link to Jasmine SpecRunner - const pluginLink = document.createElement('li') + const pluginLink = document.createElement("li") const options = { - 'stopSpecOnExpectationFailure': "true", - 'stopOnSpecFailure': 'false', - 'random': 'false', - 'hideDisabled': 'false' + stopSpecOnExpectationFailure: "true", + stopOnSpecFailure: "false", + random: "false", + hideDisabled: "false", } - const optStr = Object.entries(options).map(([key, val]) => `${key}=${val}`).join('&') + const optStr = Object.entries(options) + .map(([key, val]) => `${key}=${val}`) + .join("&") pluginLink.innerHTML = ` Start SelfTest` links.appendChild(pluginLink) - console.log('%s loaded!', ID_PREFIX) + console.log("%s loaded!", ID_PREFIX) })() diff --git a/ui/plugins/ui/tiled-image-download.plugin.js b/ui/plugins/ui/tiled-image-download.plugin.js new file mode 100644 index 00000000..0fe00c2e --- /dev/null +++ b/ui/plugins/ui/tiled-image-download.plugin.js @@ -0,0 +1,326 @@ +;(function(){ + "use strict"; + const PAPERSIZE = [ + {id: "a3p", width: 297, height: 420, unit: "mm"}, + {id: "a3l", width: 420, height: 297, unit: "mm"}, + {id: "a4p", width: 210, height: 297, unit: "mm"}, + {id: "a4l", width: 297, height: 210, unit: "mm"}, + {id: "ll", width: 279, height: 216, unit: "mm"}, + {id: "lp", width: 216, height: 279, unit: "mm"}, + {id: "hd", width: 1920, height: 1080, unit: "pixels"}, + {id: "4k", width: 3840, height: 2160, unit: "pixels"}, + ] + + // ---- Register plugin + PLUGINS['IMAGE_INFO_BUTTONS'].push({ + html: ' Download tiled image', + on_click: onDownloadTiledImage, + filter: (req, img) => req.tiling != "none", + }) + + var thisImage + + function onDownloadTiledImage(req, img) { + document.getElementById("download-tiled-image-dialog").showModal() + thisImage = new Image() + thisImage.src = img.src + thisImage.dataset["prompt"] = img.dataset["prompt"] + } + + // ---- Add HTML + document.getElementById('container').lastElementChild.insertAdjacentHTML("afterend", + ` +

    Download tiled image

    +
    +
    +
    + + Number of tiles + + + Image dimensions + +
    +
    +
    +
    + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    +
    + Some standard sizes:
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + + Tile placement + +
    +
    +
    +
    + +
    + +
    + +
    +
    +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    `) + + let downloadTiledImageDialog = document.getElementById("download-tiled-image-dialog") + let dtim1_width = document.getElementById("dtim1-width") + let dtim1_height = document.getElementById("dtim1-height") + let dtim2_width = document.getElementById("dtim2-width") + let dtim2_height = document.getElementById("dtim2-height") + let dtim2_unit = document.getElementById("dtim2-unit") + let dtim2_dpi = document.getElementById("dtim2-dpi") + let tabTiledTilesOptions = document.getElementById("tab-image-tiles") + let tabTiledSizeOptions = document.getElementById("tab-image-size") + + linkTabContents(tabTiledTilesOptions) + linkTabContents(tabTiledSizeOptions) + + prettifyInputs(downloadTiledImageDialog) + + // ---- Predefined image dimensions + PAPERSIZE.forEach( function(p) { + document.getElementById("dtim2-" + p.id).addEventListener("click", (e) => { + dtim2_unit.value = p.unit + dtim2_width.value = p.width + dtim2_height.value = p.height + }) + }) + + // ---- Close popup + document.getElementById("dti-cancel").addEventListener("click", (e) => downloadTiledImageDialog.close()) + downloadTiledImageDialog.addEventListener('click', function (event) { + var rect = downloadTiledImageDialog.getBoundingClientRect(); + var isInDialog=(rect.top <= event.clientY && event.clientY <= rect.top + rect.height + && rect.left <= event.clientX && event.clientX <= rect.left + rect.width); + if (!isInDialog) { + downloadTiledImageDialog.close(); + } + }); + + // ---- Stylesheet + const styleSheet = document.createElement("style") + styleSheet.textContent = ` + dialog { + background: var(--background-color2); + color: var(--text-color); + border-radius: 7px; + border: 1px solid var(--background-color3); + } + + dialog::backdrop { + background: rgba(0, 0, 0, 0.5); + } + + + button[disabled] { + opacity: 0.5; + } + + .method-2-dpi { + margin-top: 1em; + margin-bottom: 1em; + } + + .method-2-paper button { + width: 10em; + padding: 4px; + margin: 4px; + } + + .download-tiled-image .tab-content { + background: var(--background-color1); + border-radius: 3pt; + } + + .dtim-container { display: grid; + grid-template-columns: auto auto; + grid-template-rows: auto auto; + gap: 1em 0px; + grid-auto-flow: row; + grid-template-areas: + "dtim-tab dtim-tab dtim-plc" + "dtim-ok dtim-newtab dtim-cancel"; + } + + .download-tiled-image-top { + justify-self: center; + grid-area: dtim-tab; + } + + .download-tiled-image-placement { + justify-self: center; + grid-area: dtim-plc; + margin-left: 1em; + } + + .dtim-ok { + justify-self: center; + align-self: start; + grid-area: dtim-ok; + } + + .dtim-newtab { + justify-self: center; + align-self: start; + grid-area: dtim-newtab; + } + + .dtim-cancel { + justify-self: center; + align-self: start; + grid-area: dtim-cancel; + } + + #tab-content-image-placement img { + margin: 4px; + opacity: 0.3; + border: solid 2px var(--background-color1); + } + + #tab-content-image-placement img:hover { + margin: 4px; + opacity: 1; + border: solid 2px var(--accent-color); + filter: brightness(2); + } + + #tab-content-image-placement img.active { + margin: 4px; + opacity: 1; + border: solid 2px var(--background-color1); + } + + ` + document.head.appendChild(styleSheet) + + // ---- Placement widget + + function updatePlacementWidget(event) { + document.querySelector("#tab-content-image-placement img.active").classList.remove("active") + event.target.classList.add("active") + } + + document.querySelectorAll("#tab-content-image-placement img").forEach( + (i) => i.addEventListener("click", updatePlacementWidget) + ) + + function getPlacement() { + return document.querySelector("#tab-content-image-placement img.active").id.substr(5) + } + + // ---- Make the image + function downloadTiledImage(image, width, height, offsetX=0, offsetY=0, new_tab=false) { + + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + const context = canvas.getContext('2d') + + const w = image.width + const h = image.height + + for (var x = offsetX; x < width; x += w) { + for (var y = offsetY; y < height; y += h) { + context.drawImage(image, x, y, w, h) + } + } + if (new_tab) { + var newTab = window.open("") + newTab.document.write(`${width}×${height}, "${image.dataset["prompt"]}"`) + } else { + const link = document.createElement('a') + link.href = canvas.toDataURL() + link.download = image.dataset["prompt"].replace(/[^a-zA-Z0-9]+/g, "-").substr(0,22)+crypto.randomUUID()+".png" + link.click() + } + } + + function onDownloadTiledImageClick(e, newtab=false) { + var width, height, offsetX, offsetY + + if (isTabActive(tabTiledTilesOptions)) { + width = thisImage.width * dtim1_width.value + height = thisImage.height * dtim1_height.value + } else { + if ( dtim2_unit.value == "pixels" ) { + width = dtim2_width.value + height= dtim2_height.value + } else if ( dtim2_unit.value == "mm" ) { + width = Math.floor( dtim2_width.value * dtim2_dpi.value / 25.4 ) + height = Math.floor( dtim2_height.value * dtim2_dpi.value / 25.4 ) + } else { // inch + width = Math.floor( dtim2_width.value * dtim2_dpi.value ) + height = Math.floor( dtim2_height.value * dtim2_dpi.value ) + } + } + + var placement = getPlacement() + if (placement == "1tl") { + offsetX = 0 + offsetY = 0 + } else if (placement == "1tr") { + offsetX = width - thisImage.width * Math.ceil( width / thisImage.width ) + offsetY = 0 + } else if (placement == "1bl") { + offsetX = 0 + offsetY = height - thisImage.height * Math.ceil( height / thisImage.height ) + } else if (placement == "1br") { + offsetX = width - thisImage.width * Math.ceil( width / thisImage.width ) + offsetY = height - thisImage.height * Math.ceil( height / thisImage.height ) + } else if (placement == "4center") { + offsetX = width/2 - thisImage.width * Math.ceil( width/2 / thisImage.width ) + offsetY = height/2 - thisImage.height * Math.ceil( height/2 / thisImage.height ) + } else if (placement == "1center") { + offsetX = width/2 - thisImage.width/2 - thisImage.width * Math.ceil( (width/2 - thisImage.width/2) / thisImage.width ) + offsetY = height/2 - thisImage.height/2 - thisImage.height * Math.ceil( (height/2 - thisImage.height/2) / thisImage.height ) + } + downloadTiledImage(thisImage, width, height, offsetX, offsetY, newtab) + downloadTiledImageDialog.close() + } + + document.getElementById("dti-ok").addEventListener("click", onDownloadTiledImageClick) + document.getElementById("dti-newtab").addEventListener("click", (e) => onDownloadTiledImageClick(e,true)) + +})()