├── .castor ├── docker.php └── qa.php ├── .env ├── .env.test ├── .gitattributes ├── .gitignore ├── .php-cs-fixer.php ├── README.md ├── assets └── vendor │ ├── @hotwired │ ├── stimulus │ │ └── stimulus.index.js │ └── turbo │ │ └── turbo.index.js │ └── installed.php ├── bin ├── console └── phpunit ├── castor.php ├── composer.json ├── composer.lock ├── config ├── bundles.php ├── packages │ ├── cache.yaml │ ├── debug.yaml │ ├── doctrine.yaml │ ├── doctrine_migrations.yaml │ ├── framework.yaml │ ├── messenger.yaml │ ├── monolog.yaml │ ├── routing.yaml │ ├── twig.yaml │ └── web_profiler.yaml ├── preload.php ├── routes.yaml ├── routes │ ├── framework.yaml │ └── web_profiler.yaml └── services.yaml ├── infrastructure └── docker │ ├── docker-compose.builder.yml │ ├── docker-compose.docker-for-x.yml │ ├── docker-compose.yml │ ├── redash.env │ └── services │ ├── elasticsearch │ ├── Dockerfile │ └── elasticsearch.yml │ ├── php │ ├── Dockerfile │ ├── base │ │ └── php-configuration │ │ │ └── mods-available │ │ │ └── app-default.ini │ ├── builder │ │ ├── etc │ │ │ └── sudoers.d │ │ │ │ └── sudo │ │ └── php-configuration │ │ │ └── mods-available │ │ │ └── app-builder.ini │ ├── entrypoint │ └── frontend │ │ ├── etc │ │ ├── nginx │ │ │ ├── environments │ │ │ └── nginx.conf │ │ └── service │ │ │ ├── nginx │ │ │ └── run │ │ │ └── php-fpm │ │ │ └── run │ │ └── php-configuration │ │ ├── fpm │ │ └── php-fpm.conf │ │ └── mods-available │ │ └── app-fpm.ini │ ├── redash.env │ ├── router │ ├── Dockerfile │ ├── certs │ │ └── .gitkeep │ ├── generate-ssl.sh │ ├── openssl.cnf │ └── traefik │ │ ├── dynamic_conf.yaml │ │ └── traefik.yaml │ └── vector │ └── vector.yaml ├── migrations ├── .gitignore └── Version20240224081951.php ├── phpstan.neon ├── phpunit.xml.dist ├── public └── index.php ├── src ├── Controller │ ├── .gitignore │ └── HomepageController.php ├── Dto │ └── User.php ├── Entity │ └── .gitignore ├── Kernel.php ├── Message │ └── MyMessage.php ├── MessageHandler │ └── MyMessageHandler.php ├── Messenger │ └── Middleware │ │ ├── LogMiddleware.php │ │ └── Stamp │ │ └── LogStamp.php ├── Monolog │ └── Processor │ │ ├── Model │ │ ├── ExportExtraContextInterface.php │ │ └── ToLogInterface.php │ │ ├── ModelProcessor.php │ │ ├── SapiProcessor.php │ │ └── UuidProcessor.php └── Repository │ └── .gitignore ├── symfony.lock ├── templates ├── base.html.twig └── homepage │ └── homepage.html.twig ├── tests └── bootstrap.php └── tools ├── bin ├── php-cs-fixer └── phpstan ├── php-cs-fixer ├── .gitignore ├── composer.json └── composer.lock └── phpstan ├── .gitignore ├── composer.json └── composer.lock /.castor/docker.php: -------------------------------------------------------------------------------- 1 | section('About this project'); 27 | 28 | io()->comment('Run castor to display all available commands.'); 29 | io()->comment('Run castor about to display this project help.'); 30 | io()->comment('Run castor help [command] to display Castor help.'); 31 | 32 | io()->section('Available URLs for this project:'); 33 | $urls = [variable('root_domain'), ...variable('extra_domains')]; 34 | 35 | $payload = @file_get_contents(sprintf('http://%s:8080/api/http/routers', variable('root_domain'))); 36 | if ($payload) { 37 | $routers = json_decode($payload, true); 38 | $projectName = variable('project_name'); 39 | foreach ($routers as $router) { 40 | if (!preg_match("{^{$projectName}-(.*)@docker$}", $router['name'])) { 41 | continue; 42 | } 43 | if ("frontend-{$projectName}" === $router['service']) { 44 | continue; 45 | } 46 | if (!preg_match('{^Host\\(`(?P.*)`\\)$}', $router['rule'], $matches)) { 47 | continue; 48 | } 49 | $hosts = explode('`) || Host(`', $matches['hosts']); 50 | $urls = [...$urls, ...$hosts]; 51 | } 52 | } 53 | io()->listing(array_map(fn ($url) => "https://{$url}", $urls)); 54 | } 55 | 56 | #[AsTask(description: 'Builds the infrastructure', aliases: ['build'])] 57 | function build(): void 58 | { 59 | $userId = variable('user_id'); 60 | $phpVersion = variable('php_version'); 61 | 62 | $command = [ 63 | 'build', 64 | '--build-arg', "USER_ID={$userId}", 65 | '--build-arg', "PHP_VERSION={$phpVersion}", 66 | ]; 67 | 68 | docker_compose($command, withBuilder: true); 69 | } 70 | 71 | #[AsTask(description: 'Builds and starts the infrastructure', aliases: ['up'])] 72 | function up(): void 73 | { 74 | try { 75 | docker_compose(['up', '--detach', '--no-build']); 76 | } catch (ExceptionInterface $e) { 77 | io()->error('An error occured while starting the infrastructure.'); 78 | io()->note('Did you forget to run "castor docker:build"?'); 79 | io()->note('Or you forget to login to the registry?'); 80 | 81 | throw $e; 82 | } 83 | } 84 | 85 | #[AsTask(description: 'Stops the infrastructure', aliases: ['stop'])] 86 | function stop(): void 87 | { 88 | docker_compose(['stop']); 89 | } 90 | 91 | #[AsTask(description: 'Opens a shell (bash) into a builder container', aliases: ['builder'])] 92 | function builder(): void 93 | { 94 | $c = context() 95 | ->withTimeout(null) 96 | ->withTty() 97 | ->withEnvironment($_ENV + $_SERVER) 98 | ->withAllowFailure() 99 | ; 100 | docker_compose_run('bash', c: $c); 101 | } 102 | 103 | #[AsTask(description: 'Displays infrastructure logs', aliases: ['logs'])] 104 | function logs(): void 105 | { 106 | docker_compose(['logs', '-f', '--tail', '150'], c: context()->withTty()); 107 | } 108 | 109 | #[AsTask(description: 'Lists containers status', aliases: ['ps'])] 110 | function ps(): void 111 | { 112 | docker_compose(['ps'], withBuilder: false); 113 | } 114 | 115 | #[AsTask(description: 'Cleans the infrastructure (remove container, volume, networks)', aliases: ['destroy'])] 116 | function destroy( 117 | #[AsOption(description: 'Force the destruction without confirmation', shortcut: 'f')] 118 | bool $force = false, 119 | ): void { 120 | if (!$force) { 121 | io()->warning('This will permanently remove all containers, volumes, networks... created for this project.'); 122 | io()->note('You can use the --force option to avoid this confirmation.'); 123 | if (!io()->confirm('Are you sure?', false)) { 124 | io()->comment('Aborted.'); 125 | 126 | return; 127 | } 128 | } 129 | 130 | docker_compose(['down', '--remove-orphans', '--volumes', '--rmi=local'], withBuilder: true); 131 | $files = finder() 132 | ->in(variable('root_dir') . '/infrastructure/docker/services/router/certs/') 133 | ->name('*.pem') 134 | ->files() 135 | ; 136 | fs()->remove($files); 137 | } 138 | 139 | #[AsTask(description: 'Generates SSL certificates (with mkcert if available or self-signed if not)')] 140 | function generate_certificates( 141 | #[AsOption(description: 'Force the certificates re-generation without confirmation', shortcut: 'f')] 142 | bool $force = false, 143 | ): void { 144 | $sslDir = variable('root_dir') . '/infrastructure/docker/services/router/certs'; 145 | 146 | if (file_exists("{$sslDir}/cert.pem") && !$force) { 147 | io()->comment('SSL certificates already exists.'); 148 | io()->note('Run "castor docker:generate-certificates --force" to generate new certificates.'); 149 | 150 | return; 151 | } 152 | 153 | if ($force) { 154 | if (file_exists($f = "{$sslDir}/cert.pem")) { 155 | io()->comment('Removing existing certificates in infrastructure/docker/services/router/certs/*.pem.'); 156 | unlink($f); 157 | } 158 | 159 | if (file_exists($f = "{$sslDir}/key.pem")) { 160 | unlink($f); 161 | } 162 | } 163 | 164 | $finder = new ExecutableFinder(); 165 | $mkcert = $finder->find('mkcert'); 166 | 167 | if ($mkcert) { 168 | $pathCaRoot = capture(['mkcert', '-CAROOT']); 169 | 170 | if (!is_dir($pathCaRoot)) { 171 | io()->warning('You must have mkcert CA Root installed on your host with "mkcert -install" command.'); 172 | 173 | return; 174 | } 175 | 176 | $rootDomain = variable('root_domain'); 177 | 178 | run([ 179 | 'mkcert', 180 | '-cert-file', "{$sslDir}/cert.pem", 181 | '-key-file', "{$sslDir}/key.pem", 182 | $rootDomain, 183 | "*.{$rootDomain}", 184 | ...variable('extra_domains'), 185 | ]); 186 | 187 | io()->success('Successfully generated SSL certificates with mkcert.'); 188 | 189 | if ($force) { 190 | io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".'); 191 | } 192 | 193 | return; 194 | } 195 | 196 | run(['infrastructure/docker/services/router/generate-ssl.sh'], quiet: true); 197 | 198 | io()->success('Successfully generated self-signed SSL certificates in infrastructure/docker/services/router/certs/*.pem.'); 199 | io()->comment('Consider installing mkcert to generate locally trusted SSL certificates and run "castor docker:generate-certificates --force".'); 200 | 201 | if ($force) { 202 | io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".'); 203 | } 204 | } 205 | 206 | #[AsContext(default: true)] 207 | function create_default_context(): Context 208 | { 209 | $data = create_default_variables() + [ 210 | 'project_name' => 'app', 211 | 'root_domain' => 'app.test', 212 | 'extra_domains' => [], 213 | 'php_version' => '8.3', 214 | 'docker_compose_files' => [ 215 | 'docker-compose.yml', 216 | ], 217 | 'macos' => false, 218 | 'power_shell' => false, 219 | 'user_id' => posix_geteuid(), 220 | 'root_dir' => \dirname(__DIR__), 221 | 'env' => $_SERVER['CI'] ?? false ? 'ci' : 'dev', 222 | ]; 223 | 224 | if (file_exists($data['root_dir'] . '/infrastructure/docker/docker-compose.override.yml')) { 225 | $data['docker_compose_files'][] = 'docker-compose.override.yml'; 226 | } 227 | 228 | // We need an empty context to run command, since the default context has 229 | // not been set in castor, since we ARE creating it right now 230 | $emptyContext = new Context(); 231 | 232 | $data['composer_cache_dir'] = cache('composer_cache_dir', function () use ($emptyContext): string { 233 | $composerCacheDir = capture(['composer', 'global', 'config', 'cache-dir', '-q'], onFailure: '', context: $emptyContext); 234 | // If PHP is broken, the output will not be a valid path but an error message 235 | if (!is_dir($composerCacheDir)) { 236 | $composerCacheDir = sys_get_temp_dir() . '/castor/composer'; 237 | } 238 | 239 | return $composerCacheDir; 240 | }); 241 | 242 | $platform = strtolower(php_uname('s')); 243 | if (str_contains($platform, 'darwin')) { 244 | $data['macos'] = true; 245 | $data['docker_compose_files'][] = 'docker-compose.docker-for-x.yml'; 246 | } elseif (\in_array($platform, ['win32', 'win64'])) { 247 | $data['docker_compose_files'][] = 'docker-compose.docker-for-x.yml'; 248 | $data['power_shell'] = true; 249 | } 250 | 251 | if ($data['user_id'] > 256000) { 252 | $data['user_id'] = 1000; 253 | } 254 | 255 | if (0 === $data['user_id']) { 256 | log('Running as root? Fallback to fake user id.', 'warning'); 257 | $data['user_id'] = 1000; 258 | } 259 | 260 | return new Context($data, pty: 'dev' === $data['env']); 261 | } 262 | 263 | /** 264 | * @param array $subCommand 265 | */ 266 | function docker_compose(array $subCommand, Context $c = null, bool $withBuilder = false): Process 267 | { 268 | $c ??= context(); 269 | 270 | $domains = [variable('root_domain'), ...variable('extra_domains')]; 271 | $domains = '`' . implode('`) || Host(`', $domains) . '`'; 272 | 273 | $c = $c 274 | ->withTimeout(null) 275 | ->withEnvironment([ 276 | 'PROJECT_NAME' => variable('project_name'), 277 | 'PROJECT_ROOT_DOMAIN' => variable('root_domain'), 278 | 'PROJECT_DOMAINS' => $domains, 279 | 'USER_ID' => variable('user_id'), 280 | 'COMPOSER_CACHE_DIR' => variable('composer_cache_dir'), 281 | 'PHP_VERSION' => variable('php_version'), 282 | 'BUILDKIT_PROGRESS' => 'plain', 283 | ]) 284 | ; 285 | 286 | $command = [ 287 | 'docker', 288 | 'compose', 289 | '-p', variable('project_name'), 290 | ]; 291 | 292 | foreach (variable('docker_compose_files') as $file) { 293 | $command[] = '-f'; 294 | $command[] = variable('root_dir') . '/infrastructure/docker/' . $file; 295 | } 296 | 297 | if ($withBuilder) { 298 | $command[] = '-f'; 299 | $command[] = variable('root_dir') . '/infrastructure/docker/docker-compose.builder.yml'; 300 | } 301 | 302 | $command = array_merge($command, $subCommand); 303 | 304 | return run($command, context: $c); 305 | } 306 | 307 | function docker_compose_exec( 308 | string $runCommand, 309 | Context $c = null, 310 | string $service = 'builder', 311 | bool $withBuilder = false 312 | ): Process { 313 | $command = [ 314 | 'exec', 315 | ]; 316 | 317 | $command[] = $service; 318 | $command[] = '/bin/sh'; 319 | $command[] = '-c'; 320 | $command[] = "exec {$runCommand}"; 321 | 322 | return docker_compose($command, c: $c, withBuilder: $withBuilder); 323 | } 324 | 325 | function docker_compose_run( 326 | string $runCommand, 327 | Context $c = null, 328 | string $service = 'builder', 329 | bool $noDeps = true, 330 | string $workDir = null, 331 | bool $portMapping = false, 332 | bool $withBuilder = true, 333 | ): Process { 334 | $command = [ 335 | 'run', 336 | '--rm', 337 | ]; 338 | 339 | if ($noDeps) { 340 | $command[] = '--no-deps'; 341 | } 342 | 343 | if ($portMapping) { 344 | $command[] = '--service-ports'; 345 | } 346 | 347 | if (null !== $workDir) { 348 | $command[] = '-w'; 349 | $command[] = $workDir; 350 | } 351 | 352 | $command[] = $service; 353 | $command[] = '/bin/sh'; 354 | $command[] = '-c'; 355 | $command[] = "exec {$runCommand}"; 356 | 357 | return docker_compose($command, c: $c, withBuilder: $withBuilder); 358 | } 359 | 360 | function docker_exit_code( 361 | string $runCommand, 362 | Context $c = null, 363 | string $service = 'builder', 364 | bool $noDeps = true, 365 | string $workDir = null, 366 | bool $withBuilder = true, 367 | ): int { 368 | $c = ($c ?? context())->withAllowFailure(); 369 | 370 | $process = docker_compose_run( 371 | runCommand: $runCommand, 372 | c: $c, 373 | service: $service, 374 | noDeps: $noDeps, 375 | workDir: $workDir, 376 | withBuilder: $withBuilder, 377 | ); 378 | 379 | return $process->getExitCode() ?? 0; 380 | } 381 | 382 | // Mac users have a lot of problems running Yarn / Webpack on the Docker stack 383 | // so this func allow them to run these tools on their host 384 | function run_in_docker_or_locally_for_mac(string $command, Context $c = null): void 385 | { 386 | $c ??= context(); 387 | 388 | if (variable('macos')) { 389 | run($command, context: $c->withPath(variable('root_dir'))); 390 | } else { 391 | docker_compose_run($command, c: $c); 392 | } 393 | } 394 | -------------------------------------------------------------------------------- /.castor/qa.php: -------------------------------------------------------------------------------- 1 | =1.2). 15 | # https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration 16 | 17 | ###> symfony/framework-bundle ### 18 | APP_ENV=dev 19 | APP_SECRET=f3d49e4421fc399215e28640deafc752 20 | ###< symfony/framework-bundle ### 21 | 22 | ###> doctrine/doctrine-bundle ### 23 | # Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url 24 | # IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml 25 | # 26 | # DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db" 27 | # DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8.0.32&charset=utf8mb4" 28 | # DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=10.11.2-MariaDB&charset=utf8mb4" 29 | DATABASE_URL="postgresql://app:app@postgres:5432/app?serverVersion=16&charset=utf8" 30 | ###< doctrine/doctrine-bundle ### 31 | 32 | ###> symfony/messenger ### 33 | # Choose one of the transports below 34 | # MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages 35 | # MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages 36 | MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0 37 | ###< symfony/messenger ### 38 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | # define your env variables for the test env here 2 | KERNEL_CLASS='App\Kernel' 3 | APP_SECRET='$ecretf0rt3st' 4 | SYMFONY_DEPRECATIONS_HELPER=999999 5 | PANTHER_APP_ENV=panther 6 | PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots 7 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Force LF line ending (mandatory for Windows) 2 | * text=auto eol=lf 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Castor 2 | /.castor.stub.php 3 | /infrastructure/docker/docker-compose.override.yml 4 | /infrastructure/docker/services/router/certs/*.pem 5 | 6 | # Tools 7 | .php-cs-fixer.cache 8 | 9 | ###> symfony/framework-bundle ### 10 | /.env.local 11 | /.env.local.php 12 | /.env.*.local 13 | /config/secrets/prod/prod.decrypt.private.php 14 | /public/bundles/ 15 | /var/ 16 | /vendor/ 17 | ###< symfony/framework-bundle ### 18 | 19 | ###> phpunit/phpunit ### 20 | /phpunit.xml 21 | .phpunit.result.cache 22 | ###< phpunit/phpunit ### 23 | ###> symfony/phpunit-bridge ### 24 | .phpunit.result.cache 25 | /phpunit.xml 26 | ###< symfony/phpunit-bridge ### 27 | -------------------------------------------------------------------------------- /.php-cs-fixer.php: -------------------------------------------------------------------------------- 1 | ignoreVCSIgnored(true) 5 | ->ignoreDotFiles(false) 6 | ->in(__DIR__) 7 | ->append([ 8 | __FILE__, 9 | ]) 10 | ; 11 | 12 | return (new PhpCsFixer\Config()) 13 | ->setRiskyAllowed(true) 14 | ->setRules([ 15 | '@PHP81Migration' => true, 16 | '@PhpCsFixer' => true, 17 | '@Symfony' => true, 18 | '@Symfony:risky' => true, 19 | 'php_unit_internal_class' => false, // From @PhpCsFixer but we don't want it 20 | 'php_unit_test_class_requires_covers' => false, // From @PhpCsFixer but we don't want it 21 | 'phpdoc_add_missing_param_annotation' => false, // From @PhpCsFixer but we don't want it 22 | 'concat_space' => ['spacing' => 'one'], 23 | 'ordered_class_elements' => true, // Symfony(PSR12) override the default value, but we don't want 24 | 'blank_line_before_statement' => true, // Symfony(PSR12) override the default value, but we don't want 25 | ]) 26 | ->setFinder($finder) 27 | ; 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Symfony Demo - Observability - Log 2 | 3 | Read the [slides (in french)](https://s.lyrixx.info/log) to know more about this 4 | project and monolog. 5 | 6 | ## Running the application locally 7 | 8 | ### Requirements 9 | 10 | A Docker environment is provided and requires you to have these tools available: 11 | 12 | * Docker 13 | * [Castor](https://github.com/jolicode/castor#installation) 14 | 15 | ### Docker environment 16 | 17 | The Docker infrastructure provides a web stack with: 18 | - NGINX 19 | - PHP 20 | - PostgreSQL 21 | - Elasticsearch 22 | - Kibana 23 | - ClickHouse 24 | - Loki 25 | - Grafana 26 | - Vector 27 | - Traefik 28 | - A container with some tooling: 29 | - Composer 30 | 31 | ### Domain configuration (first time only) 32 | 33 | Before running the application for the first time, ensure your domain names 34 | point the IP of your Docker daemon by editing your `/etc/hosts` file. 35 | 36 | This IP is probably `127.0.0.1` unless you run Docker in a special VM (like docker-machine for example). 37 | 38 | > [!NOTE] 39 | > The router binds port 80 and 443, that's why it will work with `127.0.0.1` 40 | 41 | ``` 42 | echo '127.0.0.1 observability.test clickhouse.observability.test elasticsearch.observability.test grafana.observability.test kibana.observability.test loki.observability.test redash.observability.test vector.observability.test ' | sudo tee -a /etc/hosts 43 | ``` 44 | 45 | ### Starting the stack 46 | 47 | Launch the stack by running this command: 48 | 49 | ```bash 50 | castor start 51 | ``` 52 | 53 | > [!NOTE] 54 | > the first start of the stack should take a few minutes. 55 | 56 | The site is now accessible at https://observability.test (you may need to accept 57 | self-signed SSL certificate if you do not have mkcert installed on your computer 58 | - see below). 59 | 60 | ### Other tasks 61 | 62 | Checkout `castor` to have the list of available tasks. 63 | -------------------------------------------------------------------------------- /assets/vendor/@hotwired/stimulus/stimulus.index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2. 3 | * Original file: /npm/@hotwired/stimulus@3.2.2/dist/stimulus.js 4 | * 5 | * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files 6 | */ 7 | class e{constructor(e,t,s){this.eventTarget=e,this.eventName=t,this.eventOptions=s,this.unorderedBindings=new Set}connect(){this.eventTarget.addEventListener(this.eventName,this,this.eventOptions)}disconnect(){this.eventTarget.removeEventListener(this.eventName,this,this.eventOptions)}bindingConnected(e){this.unorderedBindings.add(e)}bindingDisconnected(e){this.unorderedBindings.delete(e)}handleEvent(e){const t=function(e){if("immediatePropagationStopped"in e)return e;{const{stopImmediatePropagation:t}=e;return Object.assign(e,{immediatePropagationStopped:!1,stopImmediatePropagation(){this.immediatePropagationStopped=!0,t.call(this)}})}}(e);for(const e of this.bindings){if(t.immediatePropagationStopped)break;e.handleEvent(t)}}hasBindings(){return this.unorderedBindings.size>0}get bindings(){return Array.from(this.unorderedBindings).sort(((e,t)=>{const s=e.index,r=t.index;return sr?1:0}))}}class t{constructor(e){this.application=e,this.eventListenerMaps=new Map,this.started=!1}start(){this.started||(this.started=!0,this.eventListeners.forEach((e=>e.connect())))}stop(){this.started&&(this.started=!1,this.eventListeners.forEach((e=>e.disconnect())))}get eventListeners(){return Array.from(this.eventListenerMaps.values()).reduce(((e,t)=>e.concat(Array.from(t.values()))),[])}bindingConnected(e){this.fetchEventListenerForBinding(e).bindingConnected(e)}bindingDisconnected(e,t=!1){this.fetchEventListenerForBinding(e).bindingDisconnected(e),t&&this.clearEventListenersForBinding(e)}handleError(e,t,s={}){this.application.handleError(e,`Error ${t}`,s)}clearEventListenersForBinding(e){const t=this.fetchEventListenerForBinding(e);t.hasBindings()||(t.disconnect(),this.removeMappedEventListenerFor(e))}removeMappedEventListenerFor(e){const{eventTarget:t,eventName:s,eventOptions:r}=e,n=this.fetchEventListenerMapForEventTarget(t),i=this.cacheKey(s,r);n.delete(i),0==n.size&&this.eventListenerMaps.delete(t)}fetchEventListenerForBinding(e){const{eventTarget:t,eventName:s,eventOptions:r}=e;return this.fetchEventListener(t,s,r)}fetchEventListener(e,t,s){const r=this.fetchEventListenerMapForEventTarget(e),n=this.cacheKey(t,s);let i=r.get(n);return i||(i=this.createEventListener(e,t,s),r.set(n,i)),i}createEventListener(t,s,r){const n=new e(t,s,r);return this.started&&n.connect(),n}fetchEventListenerMapForEventTarget(e){let t=this.eventListenerMaps.get(e);return t||(t=new Map,this.eventListenerMaps.set(e,t)),t}cacheKey(e,t){const s=[e];return Object.keys(t).sort().forEach((e=>{s.push(`${t[e]?"":"!"}${e}`)})),s.join(":")}}const s={stop:({event:e,value:t})=>(t&&e.stopPropagation(),!0),prevent:({event:e,value:t})=>(t&&e.preventDefault(),!0),self:({event:e,value:t,element:s})=>!t||s===e.target},r=/^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;function n(e){return"window"==e?window:"document"==e?document:void 0}function i(e){return e.replace(/(?:[_-])([a-z0-9])/g,((e,t)=>t.toUpperCase()))}function o(e){return i(e.replace(/--/g,"-").replace(/__/g,"_"))}function a(e){return e.charAt(0).toUpperCase()+e.slice(1)}function c(e){return e.replace(/([A-Z])/g,((e,t)=>`-${t.toLowerCase()}`))}function l(e){return null!=e}function h(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const u=["meta","ctrl","alt","shift"];class d{constructor(e,t,s,r){this.element=e,this.index=t,this.eventTarget=s.eventTarget||e,this.eventName=s.eventName||function(e){const t=e.tagName.toLowerCase();if(t in m)return m[t](e)}(e)||g("missing event name"),this.eventOptions=s.eventOptions||{},this.identifier=s.identifier||g("missing identifier"),this.methodName=s.methodName||g("missing method name"),this.keyFilter=s.keyFilter||"",this.schema=r}static forToken(e,t){return new this(e.element,e.index,function(e){const t=e.trim().match(r)||[];let s=t[2],i=t[3];return i&&!["keydown","keyup","keypress"].includes(s)&&(s+=`.${i}`,i=""),{eventTarget:n(t[4]),eventName:s,eventOptions:t[7]?(o=t[7],o.split(":").reduce(((e,t)=>Object.assign(e,{[t.replace(/^!/,"")]:!/^!/.test(t)})),{})):{},identifier:t[5],methodName:t[6],keyFilter:t[1]||i};var o}(e.content),t)}toString(){const e=this.keyFilter?`.${this.keyFilter}`:"",t=this.eventTargetName?`@${this.eventTargetName}`:"";return`${this.eventName}${e}${t}->${this.identifier}#${this.methodName}`}shouldIgnoreKeyboardEvent(e){if(!this.keyFilter)return!1;const t=this.keyFilter.split("+");if(this.keyFilterDissatisfied(e,t))return!0;const s=t.filter((e=>!u.includes(e)))[0];return!!s&&(h(this.keyMappings,s)||g(`contains unknown key filter: ${this.keyFilter}`),this.keyMappings[s].toLowerCase()!==e.key.toLowerCase())}shouldIgnoreMouseEvent(e){if(!this.keyFilter)return!1;const t=[this.keyFilter];return!!this.keyFilterDissatisfied(e,t)}get params(){const e={},t=new RegExp(`^data-${this.identifier}-(.+)-param$`,"i");for(const{name:s,value:r}of Array.from(this.element.attributes)){const n=s.match(t),o=n&&n[1];o&&(e[i(o)]=p(r))}return e}get eventTargetName(){return(e=this.eventTarget)==window?"window":e==document?"document":void 0;var e}get keyMappings(){return this.schema.keyMappings}keyFilterDissatisfied(e,t){const[s,r,n,i]=u.map((e=>t.includes(e)));return e.metaKey!==s||e.ctrlKey!==r||e.altKey!==n||e.shiftKey!==i}}const m={a:()=>"click",button:()=>"click",form:()=>"submit",details:()=>"toggle",input:e=>"submit"==e.getAttribute("type")?"click":"input",select:()=>"change",textarea:()=>"input"};function g(e){throw new Error(e)}function p(e){try{return JSON.parse(e)}catch(t){return e}}class f{constructor(e,t){this.context=e,this.action=t}get index(){return this.action.index}get eventTarget(){return this.action.eventTarget}get eventOptions(){return this.action.eventOptions}get identifier(){return this.context.identifier}handleEvent(e){const t=this.prepareActionEvent(e);this.willBeInvokedByEvent(e)&&this.applyEventModifiers(t)&&this.invokeWithEvent(t)}get eventName(){return this.action.eventName}get method(){const e=this.controller[this.methodName];if("function"==typeof e)return e;throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`)}applyEventModifiers(e){const{element:t}=this.action,{actionDescriptorFilters:s}=this.context.application,{controller:r}=this.context;let n=!0;for(const[i,o]of Object.entries(this.eventOptions))if(i in s){const a=s[i];n=n&&a({name:i,value:o,event:e,element:t,controller:r})}return n}prepareActionEvent(e){return Object.assign(e,{params:this.action.params})}invokeWithEvent(e){const{target:t,currentTarget:s}=e;try{this.method.call(this.controller,e),this.context.logDebugActivity(this.methodName,{event:e,target:t,currentTarget:s,action:this.methodName})}catch(t){const{identifier:s,controller:r,element:n,index:i}=this,o={identifier:s,controller:r,element:n,index:i,event:e};this.context.handleError(t,`invoking action "${this.action}"`,o)}}willBeInvokedByEvent(e){const t=e.target;return!(e instanceof KeyboardEvent&&this.action.shouldIgnoreKeyboardEvent(e))&&(!(e instanceof MouseEvent&&this.action.shouldIgnoreMouseEvent(e))&&(this.element===t||(t instanceof Element&&this.element.contains(t)?this.scope.containsElement(t):this.scope.containsElement(this.action.element))))}get controller(){return this.context.controller}get methodName(){return this.action.methodName}get element(){return this.scope.element}get scope(){return this.context.scope}}class b{constructor(e,t){this.mutationObserverInit={attributes:!0,childList:!0,subtree:!0},this.element=e,this.started=!1,this.delegate=t,this.elements=new Set,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,this.mutationObserverInit),this.refresh())}pause(e){this.started&&(this.mutationObserver.disconnect(),this.started=!1),e(),this.started||(this.mutationObserver.observe(this.element,this.mutationObserverInit),this.started=!0)}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started){const e=new Set(this.matchElementsInTree());for(const t of Array.from(this.elements))e.has(t)||this.removeElement(t);for(const t of Array.from(e))this.addElement(t)}}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){"attributes"==e.type?this.processAttributeChange(e.target,e.attributeName):"childList"==e.type&&(this.processRemovedNodes(e.removedNodes),this.processAddedNodes(e.addedNodes))}processAttributeChange(e,t){this.elements.has(e)?this.delegate.elementAttributeChanged&&this.matchElement(e)?this.delegate.elementAttributeChanged(e,t):this.removeElement(e):this.matchElement(e)&&this.addElement(e)}processRemovedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.processTree(e,this.removeElement)}}processAddedNodes(e){for(const t of Array.from(e)){const e=this.elementFromNode(t);e&&this.elementIsActive(e)&&this.processTree(e,this.addElement)}}matchElement(e){return this.delegate.matchElement(e)}matchElementsInTree(e=this.element){return this.delegate.matchElementsInTree(e)}processTree(e,t){for(const s of this.matchElementsInTree(e))t.call(this,s)}elementFromNode(e){if(e.nodeType==Node.ELEMENT_NODE)return e}elementIsActive(e){return e.isConnected==this.element.isConnected&&this.element.contains(e)}addElement(e){this.elements.has(e)||this.elementIsActive(e)&&(this.elements.add(e),this.delegate.elementMatched&&this.delegate.elementMatched(e))}removeElement(e){this.elements.has(e)&&(this.elements.delete(e),this.delegate.elementUnmatched&&this.delegate.elementUnmatched(e))}}class v{constructor(e,t,s){this.attributeName=t,this.delegate=s,this.elementObserver=new b(e,this)}get element(){return this.elementObserver.element}get selector(){return`[${this.attributeName}]`}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get started(){return this.elementObserver.started}matchElement(e){return e.hasAttribute(this.attributeName)}matchElementsInTree(e){const t=this.matchElement(e)?[e]:[],s=Array.from(e.querySelectorAll(this.selector));return t.concat(s)}elementMatched(e){this.delegate.elementMatchedAttribute&&this.delegate.elementMatchedAttribute(e,this.attributeName)}elementUnmatched(e){this.delegate.elementUnmatchedAttribute&&this.delegate.elementUnmatchedAttribute(e,this.attributeName)}elementAttributeChanged(e,t){this.delegate.elementAttributeValueChanged&&this.attributeName==t&&this.delegate.elementAttributeValueChanged(e,t)}}function y(e,t,s){A(e,t).add(s)}function O(e,t,s){A(e,t).delete(s),E(e,t)}function A(e,t){let s=e.get(t);return s||(s=new Set,e.set(t,s)),s}function E(e,t){const s=e.get(t);null!=s&&0==s.size&&e.delete(t)}class w{constructor(){this.valuesByKey=new Map}get keys(){return Array.from(this.valuesByKey.keys())}get values(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e.concat(Array.from(t))),[])}get size(){return Array.from(this.valuesByKey.values()).reduce(((e,t)=>e+t.size),0)}add(e,t){y(this.valuesByKey,e,t)}delete(e,t){O(this.valuesByKey,e,t)}has(e,t){const s=this.valuesByKey.get(e);return null!=s&&s.has(t)}hasKey(e){return this.valuesByKey.has(e)}hasValue(e){return Array.from(this.valuesByKey.values()).some((t=>t.has(e)))}getValuesForKey(e){const t=this.valuesByKey.get(e);return t?Array.from(t):[]}getKeysForValue(e){return Array.from(this.valuesByKey).filter((([t,s])=>s.has(e))).map((([e,t])=>e))}}class M extends w{constructor(){super(),this.keysByValue=new Map}get values(){return Array.from(this.keysByValue.keys())}add(e,t){super.add(e,t),y(this.keysByValue,t,e)}delete(e,t){super.delete(e,t),O(this.keysByValue,t,e)}hasValue(e){return this.keysByValue.has(e)}getKeysForValue(e){const t=this.keysByValue.get(e);return t?Array.from(t):[]}}class k{constructor(e,t,s,r){this._selector=t,this.details=r,this.elementObserver=new b(e,this),this.delegate=s,this.matchesByElement=new w}get started(){return this.elementObserver.started}get selector(){return this._selector}set selector(e){this._selector=e,this.refresh()}start(){this.elementObserver.start()}pause(e){this.elementObserver.pause(e)}stop(){this.elementObserver.stop()}refresh(){this.elementObserver.refresh()}get element(){return this.elementObserver.element}matchElement(e){const{selector:t}=this;if(t){const s=e.matches(t);return this.delegate.selectorMatchElement?s&&this.delegate.selectorMatchElement(e,this.details):s}return!1}matchElementsInTree(e){const{selector:t}=this;if(t){const s=this.matchElement(e)?[e]:[],r=Array.from(e.querySelectorAll(t)).filter((e=>this.matchElement(e)));return s.concat(r)}return[]}elementMatched(e){const{selector:t}=this;t&&this.selectorMatched(e,t)}elementUnmatched(e){const t=this.matchesByElement.getKeysForValue(e);for(const s of t)this.selectorUnmatched(e,s)}elementAttributeChanged(e,t){const{selector:s}=this;if(s){const t=this.matchElement(e),r=this.matchesByElement.has(s,e);t&&!r?this.selectorMatched(e,s):!t&&r&&this.selectorUnmatched(e,s)}}selectorMatched(e,t){this.delegate.selectorMatched(e,t,this.details),this.matchesByElement.add(t,e)}selectorUnmatched(e,t){this.delegate.selectorUnmatched(e,t,this.details),this.matchesByElement.delete(t,e)}}class N{constructor(e,t){this.element=e,this.delegate=t,this.started=!1,this.stringMap=new Map,this.mutationObserver=new MutationObserver((e=>this.processMutations(e)))}start(){this.started||(this.started=!0,this.mutationObserver.observe(this.element,{attributes:!0,attributeOldValue:!0}),this.refresh())}stop(){this.started&&(this.mutationObserver.takeRecords(),this.mutationObserver.disconnect(),this.started=!1)}refresh(){if(this.started)for(const e of this.knownAttributeNames)this.refreshAttribute(e,null)}processMutations(e){if(this.started)for(const t of e)this.processMutation(t)}processMutation(e){const t=e.attributeName;t&&this.refreshAttribute(t,e.oldValue)}refreshAttribute(e,t){const s=this.delegate.getStringMapKeyForAttribute(e);if(null!=s){this.stringMap.has(e)||this.stringMapKeyAdded(s,e);const r=this.element.getAttribute(e);if(this.stringMap.get(e)!=r&&this.stringMapValueChanged(r,s,t),null==r){const t=this.stringMap.get(e);this.stringMap.delete(e),t&&this.stringMapKeyRemoved(s,e,t)}else this.stringMap.set(e,r)}}stringMapKeyAdded(e,t){this.delegate.stringMapKeyAdded&&this.delegate.stringMapKeyAdded(e,t)}stringMapValueChanged(e,t,s){this.delegate.stringMapValueChanged&&this.delegate.stringMapValueChanged(e,t,s)}stringMapKeyRemoved(e,t,s){this.delegate.stringMapKeyRemoved&&this.delegate.stringMapKeyRemoved(e,t,s)}get knownAttributeNames(){return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)))}get currentAttributeNames(){return Array.from(this.element.attributes).map((e=>e.name))}get recordedAttributeNames(){return Array.from(this.stringMap.keys())}}class F{constructor(e,t,s){this.attributeObserver=new v(e,t,this),this.delegate=s,this.tokensByElement=new w}get started(){return this.attributeObserver.started}start(){this.attributeObserver.start()}pause(e){this.attributeObserver.pause(e)}stop(){this.attributeObserver.stop()}refresh(){this.attributeObserver.refresh()}get element(){return this.attributeObserver.element}get attributeName(){return this.attributeObserver.attributeName}elementMatchedAttribute(e){this.tokensMatched(this.readTokensForElement(e))}elementAttributeValueChanged(e){const[t,s]=this.refreshTokensForElement(e);this.tokensUnmatched(t),this.tokensMatched(s)}elementUnmatchedAttribute(e){this.tokensUnmatched(this.tokensByElement.getValuesForKey(e))}tokensMatched(e){e.forEach((e=>this.tokenMatched(e)))}tokensUnmatched(e){e.forEach((e=>this.tokenUnmatched(e)))}tokenMatched(e){this.delegate.tokenMatched(e),this.tokensByElement.add(e.element,e)}tokenUnmatched(e){this.delegate.tokenUnmatched(e),this.tokensByElement.delete(e.element,e)}refreshTokensForElement(e){const t=this.tokensByElement.getValuesForKey(e),s=this.readTokensForElement(e),r=function(e,t){const s=Math.max(e.length,t.length);return Array.from({length:s},((s,r)=>[e[r],t[r]]))}(t,s).findIndex((([e,t])=>{return r=t,!((s=e)&&r&&s.index==r.index&&s.content==r.content);var s,r}));return-1==r?[[],[]]:[t.slice(r),s.slice(r)]}readTokensForElement(e){const t=this.attributeName;return function(e,t,s){return e.trim().split(/\s+/).filter((e=>e.length)).map(((e,r)=>({element:t,attributeName:s,content:e,index:r})))}(e.getAttribute(t)||"",e,t)}}class B{constructor(e,t,s){this.tokenListObserver=new F(e,t,this),this.delegate=s,this.parseResultsByToken=new WeakMap,this.valuesByTokenByElement=new WeakMap}get started(){return this.tokenListObserver.started}start(){this.tokenListObserver.start()}stop(){this.tokenListObserver.stop()}refresh(){this.tokenListObserver.refresh()}get element(){return this.tokenListObserver.element}get attributeName(){return this.tokenListObserver.attributeName}tokenMatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).set(e,s),this.delegate.elementMatchedValue(t,s))}tokenUnmatched(e){const{element:t}=e,{value:s}=this.fetchParseResultForToken(e);s&&(this.fetchValuesByTokenForElement(t).delete(e),this.delegate.elementUnmatchedValue(t,s))}fetchParseResultForToken(e){let t=this.parseResultsByToken.get(e);return t||(t=this.parseToken(e),this.parseResultsByToken.set(e,t)),t}fetchValuesByTokenForElement(e){let t=this.valuesByTokenByElement.get(e);return t||(t=new Map,this.valuesByTokenByElement.set(e,t)),t}parseToken(e){try{return{value:this.delegate.parseValueForToken(e)}}catch(e){return{error:e}}}}class C{constructor(e,t){this.context=e,this.delegate=t,this.bindingsByAction=new Map}start(){this.valueListObserver||(this.valueListObserver=new B(this.element,this.actionAttribute,this),this.valueListObserver.start())}stop(){this.valueListObserver&&(this.valueListObserver.stop(),delete this.valueListObserver,this.disconnectAllActions())}get element(){return this.context.element}get identifier(){return this.context.identifier}get actionAttribute(){return this.schema.actionAttribute}get schema(){return this.context.schema}get bindings(){return Array.from(this.bindingsByAction.values())}connectAction(e){const t=new f(this.context,e);this.bindingsByAction.set(e,t),this.delegate.bindingConnected(t)}disconnectAction(e){const t=this.bindingsByAction.get(e);t&&(this.bindingsByAction.delete(e),this.delegate.bindingDisconnected(t))}disconnectAllActions(){this.bindings.forEach((e=>this.delegate.bindingDisconnected(e,!0))),this.bindingsByAction.clear()}parseValueForToken(e){const t=d.forToken(e,this.schema);if(t.identifier==this.identifier)return t}elementMatchedValue(e,t){this.connectAction(t)}elementUnmatchedValue(e,t){this.disconnectAction(t)}}class ${constructor(e,t){this.context=e,this.receiver=t,this.stringMapObserver=new N(this.element,this),this.valueDescriptorMap=this.controller.valueDescriptorMap}start(){this.stringMapObserver.start(),this.invokeChangedCallbacksForDefaultValues()}stop(){this.stringMapObserver.stop()}get element(){return this.context.element}get controller(){return this.context.controller}getStringMapKeyForAttribute(e){if(e in this.valueDescriptorMap)return this.valueDescriptorMap[e].name}stringMapKeyAdded(e,t){const s=this.valueDescriptorMap[t];this.hasValue(e)||this.invokeChangedCallback(e,s.writer(this.receiver[e]),s.writer(s.defaultValue))}stringMapValueChanged(e,t,s){const r=this.valueDescriptorNameMap[t];null!==e&&(null===s&&(s=r.writer(r.defaultValue)),this.invokeChangedCallback(t,e,s))}stringMapKeyRemoved(e,t,s){const r=this.valueDescriptorNameMap[e];this.hasValue(e)?this.invokeChangedCallback(e,r.writer(this.receiver[e]),s):this.invokeChangedCallback(e,r.writer(r.defaultValue),s)}invokeChangedCallbacksForDefaultValues(){for(const{key:e,name:t,defaultValue:s,writer:r}of this.valueDescriptors)null==s||this.controller.data.has(e)||this.invokeChangedCallback(t,r(s),void 0)}invokeChangedCallback(e,t,s){const r=`${e}Changed`,n=this.receiver[r];if("function"==typeof n){const r=this.valueDescriptorNameMap[e];try{const e=r.reader(t);let i=s;s&&(i=r.reader(s)),n.call(this.receiver,e,i)}catch(e){throw e instanceof TypeError&&(e.message=`Stimulus Value "${this.context.identifier}.${r.name}" - ${e.message}`),e}}}get valueDescriptors(){const{valueDescriptorMap:e}=this;return Object.keys(e).map((t=>e[t]))}get valueDescriptorNameMap(){const e={};return Object.keys(this.valueDescriptorMap).forEach((t=>{const s=this.valueDescriptorMap[t];e[s.name]=s})),e}hasValue(e){const t=`has${a(this.valueDescriptorNameMap[e].name)}`;return this.receiver[t]}}class T{constructor(e,t){this.context=e,this.delegate=t,this.targetsByName=new w}start(){this.tokenListObserver||(this.tokenListObserver=new F(this.element,this.attributeName,this),this.tokenListObserver.start())}stop(){this.tokenListObserver&&(this.disconnectAllTargets(),this.tokenListObserver.stop(),delete this.tokenListObserver)}tokenMatched({element:e,content:t}){this.scope.containsElement(e)&&this.connectTarget(e,t)}tokenUnmatched({element:e,content:t}){this.disconnectTarget(e,t)}connectTarget(e,t){var s;this.targetsByName.has(t,e)||(this.targetsByName.add(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause((()=>this.delegate.targetConnected(e,t))))}disconnectTarget(e,t){var s;this.targetsByName.has(t,e)&&(this.targetsByName.delete(t,e),null===(s=this.tokenListObserver)||void 0===s||s.pause((()=>this.delegate.targetDisconnected(e,t))))}disconnectAllTargets(){for(const e of this.targetsByName.keys)for(const t of this.targetsByName.getValuesForKey(e))this.disconnectTarget(t,e)}get attributeName(){return`data-${this.context.identifier}-target`}get element(){return this.context.element}get scope(){return this.context.scope}}function S(e,t){const s=D(e);return Array.from(s.reduce(((e,s)=>(function(e,t){const s=e[t];return Array.isArray(s)?s:[]}(s,t).forEach((t=>e.add(t))),e)),new Set))}function x(e,t){return D(e).reduce(((e,s)=>(e.push(...function(e,t){const s=e[t];return s?Object.keys(s).map((e=>[e,s[e]])):[]}(s,t)),e)),[])}function D(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}class L{constructor(e,t){this.started=!1,this.context=e,this.delegate=t,this.outletsByName=new w,this.outletElementsByName=new w,this.selectorObserverMap=new Map,this.attributeObserverMap=new Map}start(){this.started||(this.outletDefinitions.forEach((e=>{this.setupSelectorObserverForOutlet(e),this.setupAttributeObserverForOutlet(e)})),this.started=!0,this.dependentContexts.forEach((e=>e.refresh())))}refresh(){this.selectorObserverMap.forEach((e=>e.refresh())),this.attributeObserverMap.forEach((e=>e.refresh()))}stop(){this.started&&(this.started=!1,this.disconnectAllOutlets(),this.stopSelectorObservers(),this.stopAttributeObservers())}stopSelectorObservers(){this.selectorObserverMap.size>0&&(this.selectorObserverMap.forEach((e=>e.stop())),this.selectorObserverMap.clear())}stopAttributeObservers(){this.attributeObserverMap.size>0&&(this.attributeObserverMap.forEach((e=>e.stop())),this.attributeObserverMap.clear())}selectorMatched(e,t,{outletName:s}){const r=this.getOutlet(e,s);r&&this.connectOutlet(r,e,s)}selectorUnmatched(e,t,{outletName:s}){const r=this.getOutletFromMap(e,s);r&&this.disconnectOutlet(r,e,s)}selectorMatchElement(e,{outletName:t}){const s=this.selector(t),r=this.hasOutlet(e,t),n=e.matches(`[${this.schema.controllerAttribute}~=${t}]`);return!!s&&(r&&n&&e.matches(s))}elementMatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementAttributeValueChanged(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}elementUnmatchedAttribute(e,t){const s=this.getOutletNameFromOutletAttributeName(t);s&&this.updateSelectorObserverForOutlet(s)}connectOutlet(e,t,s){var r;this.outletElementsByName.has(s,t)||(this.outletsByName.add(s,e),this.outletElementsByName.add(s,t),null===(r=this.selectorObserverMap.get(s))||void 0===r||r.pause((()=>this.delegate.outletConnected(e,t,s))))}disconnectOutlet(e,t,s){var r;this.outletElementsByName.has(s,t)&&(this.outletsByName.delete(s,e),this.outletElementsByName.delete(s,t),null===(r=this.selectorObserverMap.get(s))||void 0===r||r.pause((()=>this.delegate.outletDisconnected(e,t,s))))}disconnectAllOutlets(){for(const e of this.outletElementsByName.keys)for(const t of this.outletElementsByName.getValuesForKey(e))for(const s of this.outletsByName.getValuesForKey(e))this.disconnectOutlet(s,t,e)}updateSelectorObserverForOutlet(e){const t=this.selectorObserverMap.get(e);t&&(t.selector=this.selector(e))}setupSelectorObserverForOutlet(e){const t=this.selector(e),s=new k(document.body,t,this,{outletName:e});this.selectorObserverMap.set(e,s),s.start()}setupAttributeObserverForOutlet(e){const t=this.attributeNameForOutletName(e),s=new v(this.scope.element,t,this);this.attributeObserverMap.set(e,s),s.start()}selector(e){return this.scope.outlets.getSelectorForOutletName(e)}attributeNameForOutletName(e){return this.scope.schema.outletAttributeForScope(this.identifier,e)}getOutletNameFromOutletAttributeName(e){return this.outletDefinitions.find((t=>this.attributeNameForOutletName(t)===e))}get outletDependencies(){const e=new w;return this.router.modules.forEach((t=>{S(t.definition.controllerConstructor,"outlets").forEach((s=>e.add(s,t.identifier)))})),e}get outletDefinitions(){return this.outletDependencies.getKeysForValue(this.identifier)}get dependentControllerIdentifiers(){return this.outletDependencies.getValuesForKey(this.identifier)}get dependentContexts(){const e=this.dependentControllerIdentifiers;return this.router.contexts.filter((t=>e.includes(t.identifier)))}hasOutlet(e,t){return!!this.getOutlet(e,t)||!!this.getOutletFromMap(e,t)}getOutlet(e,t){return this.application.getControllerForElementAndIdentifier(e,t)}getOutletFromMap(e,t){return this.outletsByName.getValuesForKey(t).find((t=>t.element===e))}get scope(){return this.context.scope}get schema(){return this.context.schema}get identifier(){return this.context.identifier}get application(){return this.context.application}get router(){return this.application.router}}class V{constructor(e,t){this.logDebugActivity=(e,t={})=>{const{identifier:s,controller:r,element:n}=this;t=Object.assign({identifier:s,controller:r,element:n},t),this.application.logDebugActivity(this.identifier,e,t)},this.module=e,this.scope=t,this.controller=new e.controllerConstructor(this),this.bindingObserver=new C(this,this.dispatcher),this.valueObserver=new $(this,this.controller),this.targetObserver=new T(this,this),this.outletObserver=new L(this,this);try{this.controller.initialize(),this.logDebugActivity("initialize")}catch(e){this.handleError(e,"initializing controller")}}connect(){this.bindingObserver.start(),this.valueObserver.start(),this.targetObserver.start(),this.outletObserver.start();try{this.controller.connect(),this.logDebugActivity("connect")}catch(e){this.handleError(e,"connecting controller")}}refresh(){this.outletObserver.refresh()}disconnect(){try{this.controller.disconnect(),this.logDebugActivity("disconnect")}catch(e){this.handleError(e,"disconnecting controller")}this.outletObserver.stop(),this.targetObserver.stop(),this.valueObserver.stop(),this.bindingObserver.stop()}get application(){return this.module.application}get identifier(){return this.module.identifier}get schema(){return this.application.schema}get dispatcher(){return this.application.dispatcher}get element(){return this.scope.element}get parentElement(){return this.element.parentElement}handleError(e,t,s={}){const{identifier:r,controller:n,element:i}=this;s=Object.assign({identifier:r,controller:n,element:i},s),this.application.handleError(e,`Error ${t}`,s)}targetConnected(e,t){this.invokeControllerMethod(`${t}TargetConnected`,e)}targetDisconnected(e,t){this.invokeControllerMethod(`${t}TargetDisconnected`,e)}outletConnected(e,t,s){this.invokeControllerMethod(`${o(s)}OutletConnected`,e,t)}outletDisconnected(e,t,s){this.invokeControllerMethod(`${o(s)}OutletDisconnected`,e,t)}invokeControllerMethod(e,...t){const s=this.controller;"function"==typeof s[e]&&s[e](...t)}}function K(e){return function(e,t){const s=j(e),r=function(e,t){return I(t).reduce(((s,r)=>{const n=function(e,t,s){const r=Object.getOwnPropertyDescriptor(e,s);if(!r||!("value"in r)){const e=Object.getOwnPropertyDescriptor(t,s).value;return r&&(e.get=r.get||e.get,e.set=r.set||e.set),e}}(e,t,r);return n&&Object.assign(s,{[r]:n}),s}),{})}(e.prototype,t);return Object.defineProperties(s.prototype,r),s}(e,function(e){const t=S(e,"blessings");return t.reduce(((t,s)=>{const r=s(e);for(const e in r){const s=t[e]||{};t[e]=Object.assign(s,r[e])}return t}),{})}(e))}const I="function"==typeof Object.getOwnPropertySymbols?e=>[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)]:Object.getOwnPropertyNames,j=(()=>{function e(e){function t(){return Reflect.construct(e,arguments,new.target)}return t.prototype=Object.create(e.prototype,{constructor:{value:t}}),Reflect.setPrototypeOf(t,e),t}try{return function(){const t=e((function(){this.a.call(this)}));t.prototype.a=function(){},new t}(),e}catch(e){return e=>class extends e{}}})();class U{constructor(e,t){this.application=e,this.definition=function(e){return{identifier:e.identifier,controllerConstructor:K(e.controllerConstructor)}}(t),this.contextsByScope=new WeakMap,this.connectedContexts=new Set}get identifier(){return this.definition.identifier}get controllerConstructor(){return this.definition.controllerConstructor}get contexts(){return Array.from(this.connectedContexts)}connectContextForScope(e){const t=this.fetchContextForScope(e);this.connectedContexts.add(t),t.connect()}disconnectContextForScope(e){const t=this.contextsByScope.get(e);t&&(this.connectedContexts.delete(t),t.disconnect())}fetchContextForScope(e){let t=this.contextsByScope.get(e);return t||(t=new V(this,e),this.contextsByScope.set(e,t)),t}}class P{constructor(e){this.scope=e}has(e){return this.data.has(this.getDataKey(e))}get(e){return this.getAll(e)[0]}getAll(e){const t=this.data.get(this.getDataKey(e))||"";return t.match(/[^\s]+/g)||[]}getAttributeName(e){return this.data.getAttributeNameForKey(this.getDataKey(e))}getDataKey(e){return`${e}-class`}get data(){return this.scope.data}}class R{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get(e){const t=this.getAttributeNameForKey(e);return this.element.getAttribute(t)}set(e,t){const s=this.getAttributeNameForKey(e);return this.element.setAttribute(s,t),this.get(e)}has(e){const t=this.getAttributeNameForKey(e);return this.element.hasAttribute(t)}delete(e){if(this.has(e)){const t=this.getAttributeNameForKey(e);return this.element.removeAttribute(t),!0}return!1}getAttributeNameForKey(e){return`data-${this.identifier}-${c(e)}`}}class z{constructor(e){this.warnedKeysByObject=new WeakMap,this.logger=e}warn(e,t,s){let r=this.warnedKeysByObject.get(e);r||(r=new Set,this.warnedKeysByObject.set(e,r)),r.has(t)||(r.add(t),this.logger.warn(s,e))}}function _(e,t){return`[${e}~="${t}"]`}class q{constructor(e){this.scope=e}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findTarget(t)||this.findLegacyTarget(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllTargets(t),...this.findAllLegacyTargets(t)]),[])}findTarget(e){const t=this.getSelectorForTargetName(e);return this.scope.findElement(t)}findAllTargets(e){const t=this.getSelectorForTargetName(e);return this.scope.findAllElements(t)}getSelectorForTargetName(e){return _(this.schema.targetAttributeForScope(this.identifier),e)}findLegacyTarget(e){const t=this.getLegacySelectorForTargetName(e);return this.deprecate(this.scope.findElement(t),e)}findAllLegacyTargets(e){const t=this.getLegacySelectorForTargetName(e);return this.scope.findAllElements(t).map((t=>this.deprecate(t,e)))}getLegacySelectorForTargetName(e){const t=`${this.identifier}.${e}`;return _(this.schema.targetAttribute,t)}deprecate(e,t){if(e){const{identifier:s}=this,r=this.schema.targetAttribute,n=this.schema.targetAttributeForScope(s);this.guide.warn(e,`target:${t}`,`Please replace ${r}="${s}.${t}" with ${n}="${t}". The ${r} attribute is deprecated and will be removed in a future version of Stimulus.`)}return e}get guide(){return this.scope.guide}}class W{constructor(e,t){this.scope=e,this.controllerElement=t}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get schema(){return this.scope.schema}has(e){return null!=this.find(e)}find(...e){return e.reduce(((e,t)=>e||this.findOutlet(t)),void 0)}findAll(...e){return e.reduce(((e,t)=>[...e,...this.findAllOutlets(t)]),[])}getSelectorForOutletName(e){const t=this.schema.outletAttributeForScope(this.identifier,e);return this.controllerElement.getAttribute(t)}findOutlet(e){const t=this.getSelectorForOutletName(e);if(t)return this.findElement(t,e)}findAllOutlets(e){const t=this.getSelectorForOutletName(e);return t?this.findAllElements(t,e):[]}findElement(e,t){return this.scope.queryElements(e).filter((s=>this.matchesElement(s,e,t)))[0]}findAllElements(e,t){return this.scope.queryElements(e).filter((s=>this.matchesElement(s,e,t)))}matchesElement(e,t,s){const r=e.getAttribute(this.scope.schema.controllerAttribute)||"";return e.matches(t)&&r.split(" ").includes(s)}}class J{constructor(e,t,s,r){this.targets=new q(this),this.classes=new P(this),this.data=new R(this),this.containsElement=e=>e.closest(this.controllerSelector)===this.element,this.schema=e,this.element=t,this.identifier=s,this.guide=new z(r),this.outlets=new W(this.documentScope,t)}findElement(e){return this.element.matches(e)?this.element:this.queryElements(e).find(this.containsElement)}findAllElements(e){return[...this.element.matches(e)?[this.element]:[],...this.queryElements(e).filter(this.containsElement)]}queryElements(e){return Array.from(this.element.querySelectorAll(e))}get controllerSelector(){return _(this.schema.controllerAttribute,this.identifier)}get isDocumentScope(){return this.element===document.documentElement}get documentScope(){return this.isDocumentScope?this:new J(this.schema,document.documentElement,this.identifier,this.guide.logger)}}class H{constructor(e,t,s){this.element=e,this.schema=t,this.delegate=s,this.valueListObserver=new B(this.element,this.controllerAttribute,this),this.scopesByIdentifierByElement=new WeakMap,this.scopeReferenceCounts=new WeakMap}start(){this.valueListObserver.start()}stop(){this.valueListObserver.stop()}get controllerAttribute(){return this.schema.controllerAttribute}parseValueForToken(e){const{element:t,content:s}=e;return this.parseValueForElementAndIdentifier(t,s)}parseValueForElementAndIdentifier(e,t){const s=this.fetchScopesByIdentifierForElement(e);let r=s.get(t);return r||(r=this.delegate.createScopeForElementAndIdentifier(e,t),s.set(t,r)),r}elementMatchedValue(e,t){const s=(this.scopeReferenceCounts.get(t)||0)+1;this.scopeReferenceCounts.set(t,s),1==s&&this.delegate.scopeConnected(t)}elementUnmatchedValue(e,t){const s=this.scopeReferenceCounts.get(t);s&&(this.scopeReferenceCounts.set(t,s-1),1==s&&this.delegate.scopeDisconnected(t))}fetchScopesByIdentifierForElement(e){let t=this.scopesByIdentifierByElement.get(e);return t||(t=new Map,this.scopesByIdentifierByElement.set(e,t)),t}}class Z{constructor(e){this.application=e,this.scopeObserver=new H(this.element,this.schema,this),this.scopesByIdentifier=new w,this.modulesByIdentifier=new Map}get element(){return this.application.element}get schema(){return this.application.schema}get logger(){return this.application.logger}get controllerAttribute(){return this.schema.controllerAttribute}get modules(){return Array.from(this.modulesByIdentifier.values())}get contexts(){return this.modules.reduce(((e,t)=>e.concat(t.contexts)),[])}start(){this.scopeObserver.start()}stop(){this.scopeObserver.stop()}loadDefinition(e){this.unloadIdentifier(e.identifier);const t=new U(this.application,e);this.connectModule(t);const s=e.controllerConstructor.afterLoad;s&&s.call(e.controllerConstructor,e.identifier,this.application)}unloadIdentifier(e){const t=this.modulesByIdentifier.get(e);t&&this.disconnectModule(t)}getContextForElementAndIdentifier(e,t){const s=this.modulesByIdentifier.get(t);if(s)return s.contexts.find((t=>t.element==e))}proposeToConnectScopeForElementAndIdentifier(e,t){const s=this.scopeObserver.parseValueForElementAndIdentifier(e,t);s?this.scopeObserver.elementMatchedValue(s.element,s):console.error(`Couldn't find or create scope for identifier: "${t}" and element:`,e)}handleError(e,t,s){this.application.handleError(e,t,s)}createScopeForElementAndIdentifier(e,t){return new J(this.schema,e,t,this.logger)}scopeConnected(e){this.scopesByIdentifier.add(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.connectContextForScope(e)}scopeDisconnected(e){this.scopesByIdentifier.delete(e.identifier,e);const t=this.modulesByIdentifier.get(e.identifier);t&&t.disconnectContextForScope(e)}connectModule(e){this.modulesByIdentifier.set(e.identifier,e);this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.connectContextForScope(t)))}disconnectModule(e){this.modulesByIdentifier.delete(e.identifier);this.scopesByIdentifier.getValuesForKey(e.identifier).forEach((t=>e.disconnectContextForScope(t)))}}const G={controllerAttribute:"data-controller",actionAttribute:"data-action",targetAttribute:"data-target",targetAttributeForScope:e=>`data-${e}-target`,outletAttributeForScope:(e,t)=>`data-${e}-${t}-outlet`,keyMappings:Object.assign(Object.assign({enter:"Enter",tab:"Tab",esc:"Escape",space:" ",up:"ArrowUp",down:"ArrowDown",left:"ArrowLeft",right:"ArrowRight",home:"Home",end:"End",page_up:"PageUp",page_down:"PageDown"},Q("abcdefghijklmnopqrstuvwxyz".split("").map((e=>[e,e])))),Q("0123456789".split("").map((e=>[e,e]))))};function Q(e){return e.reduce(((e,[t,s])=>Object.assign(Object.assign({},e),{[t]:s})),{})}class X{constructor(e=document.documentElement,r=G){this.logger=console,this.debug=!1,this.logDebugActivity=(e,t,s={})=>{this.debug&&this.logFormattedMessage(e,t,s)},this.element=e,this.schema=r,this.dispatcher=new t(this),this.router=new Z(this),this.actionDescriptorFilters=Object.assign({},s)}static start(e,t){const s=new this(e,t);return s.start(),s}async start(){await new Promise((e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",(()=>e())):e()})),this.logDebugActivity("application","starting"),this.dispatcher.start(),this.router.start(),this.logDebugActivity("application","start")}stop(){this.logDebugActivity("application","stopping"),this.dispatcher.stop(),this.router.stop(),this.logDebugActivity("application","stop")}register(e,t){this.load({identifier:e,controllerConstructor:t})}registerActionOption(e,t){this.actionDescriptorFilters[e]=t}load(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>{e.controllerConstructor.shouldLoad&&this.router.loadDefinition(e)}))}unload(e,...t){(Array.isArray(e)?e:[e,...t]).forEach((e=>this.router.unloadIdentifier(e)))}get controllers(){return this.router.contexts.map((e=>e.controller))}getControllerForElementAndIdentifier(e,t){const s=this.router.getContextForElementAndIdentifier(e,t);return s?s.controller:null}handleError(e,t,s){var r;this.logger.error("%s\n\n%o\n\n%o",t,e,s),null===(r=window.onerror)||void 0===r||r.call(window,t,"",0,0,e)}logFormattedMessage(e,t,s={}){s=Object.assign({application:this},s),this.logger.groupCollapsed(`${e} #${t}`),this.logger.log("details:",Object.assign({},s)),this.logger.groupEnd()}}function Y(e,t,s){return e.application.getControllerForElementAndIdentifier(t,s)}function ee(e,t,s){let r=Y(e,t,s);return r||(e.application.router.proposeToConnectScopeForElementAndIdentifier(t,s),r=Y(e,t,s),r||void 0)}function te([e,t],s){return function(e){const{token:t,typeDefinition:s}=e,r=`${c(t)}-value`,n=function(e){const{controller:t,token:s,typeDefinition:r}=e,n={controller:t,token:s,typeObject:r},i=function(e){const{controller:t,token:s,typeObject:r}=e,n=l(r.type),i=l(r.default),o=n&&i,a=n&&!i,c=!n&&i,h=se(r.type),u=re(e.typeObject.default);if(a)return h;if(c)return u;if(h!==u){throw new Error(`The specified default value for the Stimulus Value "${t?`${t}.${s}`:s}" must match the defined type "${h}". The provided default value of "${r.default}" is of type "${u}".`)}if(o)return h}(n),o=re(r),a=se(r),c=i||o||a;if(c)return c;const h=t?`${t}.${r}`:s;throw new Error(`Unknown value type "${h}" for "${s}" value`)}(e);return{type:n,key:r,name:i(r),get defaultValue(){return function(e){const t=se(e);if(t)return ne[t];const s=h(e,"default"),r=h(e,"type"),n=e;if(s)return n.default;if(r){const{type:e}=n,t=se(e);if(t)return ne[t]}return e}(s)},get hasCustomDefaultValue(){return void 0!==re(s)},reader:ie[n],writer:oe[n]||oe.default}}({controller:s,token:e,typeDefinition:t})}function se(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function re(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}return Array.isArray(e)?"array":"[object Object]"===Object.prototype.toString.call(e)?"object":void 0}const ne={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},ie={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${re(t)}"`);return t},boolean:e=>!("0"==e||"false"==String(e).toLowerCase()),number:e=>Number(e.replace(/_/g,"")),object(e){const t=JSON.parse(e);if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${re(t)}"`);return t},string:e=>e},oe={default:function(e){return`${e}`},array:ae,object:ae};function ae(e){return JSON.stringify(e)}class ce{constructor(e){this.context=e}static get shouldLoad(){return!0}static afterLoad(e,t){}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get outlets(){return this.scope.outlets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(e,{target:t=this.element,detail:s={},prefix:r=this.identifier,bubbles:n=!0,cancelable:i=!0}={}){const o=new CustomEvent(r?`${r}:${e}`:e,{detail:s,bubbles:n,cancelable:i});return t.dispatchEvent(o),o}}ce.blessings=[function(e){return S(e,"classes").reduce(((e,t)=>{return Object.assign(e,{[`${s=t}Class`]:{get(){const{classes:e}=this;if(e.has(s))return e.get(s);{const t=e.getAttributeName(s);throw new Error(`Missing attribute "${t}"`)}}},[`${s}Classes`]:{get(){return this.classes.getAll(s)}},[`has${a(s)}Class`]:{get(){return this.classes.has(s)}}});var s}),{})},function(e){return S(e,"targets").reduce(((e,t)=>{return Object.assign(e,{[`${s=t}Target`]:{get(){const e=this.targets.find(s);if(e)return e;throw new Error(`Missing target element "${s}" for "${this.identifier}" controller`)}},[`${s}Targets`]:{get(){return this.targets.findAll(s)}},[`has${a(s)}Target`]:{get(){return this.targets.has(s)}}});var s}),{})},function(e){const t=x(e,"values"),s={valueDescriptorMap:{get(){return t.reduce(((e,t)=>{const s=te(t,this.identifier),r=this.data.getAttributeNameForKey(s.key);return Object.assign(e,{[r]:s})}),{})}}};return t.reduce(((e,t)=>Object.assign(e,function(e,t){const s=te(e,t),{key:r,name:n,reader:i,writer:o}=s;return{[n]:{get(){const e=this.data.get(r);return null!==e?i(e):s.defaultValue},set(e){void 0===e?this.data.delete(r):this.data.set(r,o(e))}},[`has${a(n)}`]:{get(){return this.data.has(r)||s.hasCustomDefaultValue}}}}(t))),s)},function(e){return S(e,"outlets").reduce(((e,t)=>Object.assign(e,function(e){const t=o(e);return{[`${t}Outlet`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t){const s=ee(this,t,e);if(s)return s;throw new Error(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`)}throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}Outlets`]:{get(){const t=this.outlets.findAll(e);return t.length>0?t.map((t=>{const s=ee(this,t,e);if(s)return s;console.warn(`The provided outlet element is missing an outlet controller "${e}" instance for host controller "${this.identifier}"`,t)})).filter((e=>e)):[]}},[`${t}OutletElement`]:{get(){const t=this.outlets.find(e),s=this.outlets.getSelectorForOutletName(e);if(t)return t;throw new Error(`Missing outlet element "${e}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${s}".`)}},[`${t}OutletElements`]:{get(){return this.outlets.findAll(e)}},[`has${a(t)}Outlet`]:{get(){return this.outlets.has(e)}}}}(t))),{})}],ce.targets=[],ce.outlets=[],ce.values={};export{X as Application,v as AttributeObserver,V as Context,ce as Controller,b as ElementObserver,M as IndexedMultimap,w as Multimap,k as SelectorObserver,N as StringMapObserver,F as TokenListObserver,B as ValueListObserver,y as add,G as defaultSchema,O as del,A as fetch,E as prune};export default null; 8 | -------------------------------------------------------------------------------- /assets/vendor/@hotwired/turbo/turbo.index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2. 3 | * Original file: /npm/@hotwired/turbo@7.3.0/dist/turbo.es2017-esm.js 4 | * 5 | * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files 6 | */ 7 | !function(){if(void 0===window.Reflect||void 0===window.customElements||window.customElements.polyfillWrapFlushCallback)return;const e=HTMLElement,t=function(){return Reflect.construct(e,[],this.constructor)};window.HTMLElement=t,HTMLElement.prototype=e.prototype,HTMLElement.prototype.constructor=HTMLElement,Object.setPrototypeOf(HTMLElement,e)}(),function(e){function t(e,t,s){throw new e("Failed to execute 'requestSubmit' on 'HTMLFormElement': "+t+".",s)}"function"!=typeof e.requestSubmit&&(e.requestSubmit=function(e){e?(!function(e,s){e instanceof HTMLElement||t(TypeError,"parameter 1 is not of type 'HTMLElement'"),"submit"==e.type||t(TypeError,"The specified element is not a submit button"),e.form==s||t(DOMException,"The specified element is not owned by this form element","NotFoundError")}(e,this),e.click()):((e=document.createElement("input")).type="submit",e.hidden=!0,this.appendChild(e),e.click(),this.removeChild(e))})}(HTMLFormElement.prototype);const e=new WeakMap;function t(t){const s=function(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null,s=t?t.closest("input, button"):null;return"submit"==(null==s?void 0:s.type)?s:null}(t.target);s&&s.form&&e.set(s.form,s)}var s,i,r,n,o,a;!function(){if("submitter"in Event.prototype)return;let s=window.Event.prototype;if("SubmitEvent"in window&&/Apple Computer/.test(navigator.vendor))s=window.SubmitEvent.prototype;else if("SubmitEvent"in window)return;addEventListener("click",t,!0),Object.defineProperty(s,"submitter",{get(){if("submit"==this.type&&this.target instanceof HTMLFormElement)return e.get(this.target)}})}(),function(e){e.eager="eager",e.lazy="lazy"}(s||(s={}));class l extends HTMLElement{static get observedAttributes(){return["disabled","complete","loading","src"]}constructor(){super(),this.loaded=Promise.resolve(),this.delegate=new l.delegateConstructor(this)}connectedCallback(){this.delegate.connect()}disconnectedCallback(){this.delegate.disconnect()}reload(){return this.delegate.sourceURLReloaded()}attributeChangedCallback(e){"loading"==e?this.delegate.loadingStyleChanged():"complete"==e?this.delegate.completeChanged():"src"==e?this.delegate.sourceURLChanged():this.delegate.disabledChanged()}get src(){return this.getAttribute("src")}set src(e){e?this.setAttribute("src",e):this.removeAttribute("src")}get loading(){return function(e){if("lazy"===e.toLowerCase())return s.lazy;return s.eager}(this.getAttribute("loading")||"")}set loading(e){e?this.setAttribute("loading",e):this.removeAttribute("loading")}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get autoscroll(){return this.hasAttribute("autoscroll")}set autoscroll(e){e?this.setAttribute("autoscroll",""):this.removeAttribute("autoscroll")}get complete(){return!this.delegate.isLoading}get isActive(){return this.ownerDocument===document&&!this.isPreview}get isPreview(){var e,t;return null===(t=null===(e=this.ownerDocument)||void 0===e?void 0:e.documentElement)||void 0===t?void 0:t.hasAttribute("data-turbo-preview")}}function h(e){return new URL(e.toString(),document.baseURI)}function c(e){let t;return e.hash?e.hash.slice(1):(t=e.href.match(/#(.*)$/))?t[1]:void 0}function d(e,t){return h((null==t?void 0:t.getAttribute("formaction"))||e.getAttribute("action")||e.action)}function u(e){return(function(e){return function(e){return e.pathname.split("/").slice(1)}(e).slice(-1)[0]}(e).match(/\.[^.]*$/)||[])[0]||""}function m(e,t){const s=function(e){return t=e.origin+e.pathname,t.endsWith("/")?t:t+"/";var t}(t);return e.href===h(s).href||e.href.startsWith(s)}function p(e,t){return m(e,t)&&!!u(e).match(/^(?:|\.(?:htm|html|xhtml|php))$/)}function g(e){const t=c(e);return null!=t?e.href.slice(0,-(t.length+1)):e.href}function f(e){return g(e)}class v{constructor(e){this.response=e}get succeeded(){return this.response.ok}get failed(){return!this.succeeded}get clientError(){return this.statusCode>=400&&this.statusCode<=499}get serverError(){return this.statusCode>=500&&this.statusCode<=599}get redirected(){return this.response.redirected}get location(){return h(this.response.url)}get isHTML(){return this.contentType&&this.contentType.match(/^(?:text\/([^\s;,]+\b)?html|application\/xhtml\+xml)\b/)}get statusCode(){return this.response.status}get contentType(){return this.header("Content-Type")}get responseText(){return this.response.clone().text()}get responseHTML(){return this.isHTML?this.response.clone().text():Promise.resolve(void 0)}header(e){return this.response.headers.get(e)}}function b(e){if("false"==e.getAttribute("data-turbo-eval"))return e;{const t=document.createElement("script"),s=M("csp-nonce");return s&&(t.nonce=s),t.textContent=e.textContent,t.async=!1,function(e,t){for(const{name:s,value:i}of t.attributes)e.setAttribute(s,i)}(t,e),t}}function w(e,{target:t,cancelable:s,detail:i}={}){const r=new CustomEvent(e,{cancelable:s,bubbles:!0,composed:!0,detail:i});return t&&t.isConnected?t.dispatchEvent(r):document.documentElement.dispatchEvent(r),r}function S(){return new Promise((e=>requestAnimationFrame((()=>e()))))}function E(e=""){return(new DOMParser).parseFromString(e,"text/html")}function y(e,...t){const s=function(e,t){return e.reduce(((e,s,i)=>e+s+(null==t[i]?"":t[i])),"")}(e,t).replace(/^\n/,"").split("\n"),i=s[0].match(/^\s+/),r=i?i[0].length:0;return s.map((e=>e.slice(r))).join("\n")}function L(){return Array.from({length:36}).map(((e,t)=>8==t||13==t||18==t||23==t?"-":14==t?"4":19==t?(Math.floor(4*Math.random())+8).toString(16):Math.floor(15*Math.random()).toString(16))).join("")}function R(e,...t){for(const s of t.map((t=>null==t?void 0:t.getAttribute(e))))if("string"==typeof s)return s;return null}function C(...e){for(const t of e)"turbo-frame"==t.localName&&t.setAttribute("busy",""),t.setAttribute("aria-busy","true")}function T(...e){for(const t of e)"turbo-frame"==t.localName&&t.removeAttribute("busy"),t.removeAttribute("aria-busy")}function A(e,t=2e3){return new Promise((s=>{const i=()=>{e.removeEventListener("error",i),e.removeEventListener("load",i),s()};e.addEventListener("load",i,{once:!0}),e.addEventListener("error",i,{once:!0}),setTimeout(s,t)}))}function P(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}function F(...e){const t=R("data-turbo-action",...e);return function(e){return"advance"==e||"replace"==e||"restore"==e}(t)?t:null}function k(e){return document.querySelector(`meta[name="${e}"]`)}function M(e){const t=k(e);return t&&t.content}function I(e,t){var s;if(e instanceof Element)return e.closest(t)||I(e.assignedSlot||(null===(s=e.getRootNode())||void 0===s?void 0:s.host),t)}!function(e){e[e.get=0]="get",e[e.post=1]="post",e[e.put=2]="put",e[e.patch=3]="patch",e[e.delete=4]="delete"}(i||(i={}));class H{constructor(e,t,s,i=new URLSearchParams,r=null){this.abortController=new AbortController,this.resolveRequestPromise=e=>{},this.delegate=e,this.method=t,this.headers=this.defaultHeaders,this.body=i,this.url=s,this.target=r}get location(){return this.url}get params(){return this.url.searchParams}get entries(){return this.body?Array.from(this.body.entries()):[]}cancel(){this.abortController.abort()}async perform(){const{fetchOptions:e}=this;this.delegate.prepareRequest(this),await this.allowRequestToBeIntercepted(e);try{this.delegate.requestStarted(this);const t=await fetch(this.url.href,e);return await this.receive(t)}catch(e){if("AbortError"!==e.name)throw this.willDelegateErrorHandling(e)&&this.delegate.requestErrored(this,e),e}finally{this.delegate.requestFinished(this)}}async receive(e){const t=new v(e);return w("turbo:before-fetch-response",{cancelable:!0,detail:{fetchResponse:t},target:this.target}).defaultPrevented?this.delegate.requestPreventedHandlingResponse(this,t):t.succeeded?this.delegate.requestSucceededWithResponse(this,t):this.delegate.requestFailedWithResponse(this,t),t}get fetchOptions(){var e;return{method:i[this.method].toUpperCase(),credentials:"same-origin",headers:this.headers,redirect:"follow",body:this.isSafe?null:this.body,signal:this.abortSignal,referrer:null===(e=this.delegate.referrer)||void 0===e?void 0:e.href}}get defaultHeaders(){return{Accept:"text/html, application/xhtml+xml"}}get isSafe(){return this.method===i.get}get abortSignal(){return this.abortController.signal}acceptResponseType(e){this.headers.Accept=[e,this.headers.Accept].join(", ")}async allowRequestToBeIntercepted(e){const t=new Promise((e=>this.resolveRequestPromise=e));w("turbo:before-fetch-request",{cancelable:!0,detail:{fetchOptions:e,url:this.url,resume:this.resolveRequestPromise},target:this.target}).defaultPrevented&&await t}willDelegateErrorHandling(e){return!w("turbo:fetch-request-error",{target:this.target,cancelable:!0,detail:{request:this,error:e}}).defaultPrevented}}class q{constructor(e,t){this.started=!1,this.intersect=e=>{const t=e.slice(-1)[0];(null==t?void 0:t.isIntersecting)&&this.delegate.elementAppearedInViewport(this.element)},this.delegate=e,this.element=t,this.intersectionObserver=new IntersectionObserver(this.intersect)}start(){this.started||(this.started=!0,this.intersectionObserver.observe(this.element))}stop(){this.started&&(this.started=!1,this.intersectionObserver.unobserve(this.element))}}class B{static wrap(e){return"string"==typeof e?new this(function(e){const t=document.createElement("template");return t.innerHTML=e,t.content}(e)):e}constructor(e){this.fragment=function(e){for(const t of e.querySelectorAll("turbo-stream")){const e=document.importNode(t,!0);for(const t of e.templateElement.content.querySelectorAll("script"))t.replaceWith(b(t));t.replaceWith(e)}return e}(e)}}B.contentType="text/vnd.turbo-stream.html",function(e){e[e.initialized=0]="initialized",e[e.requesting=1]="requesting",e[e.waiting=2]="waiting",e[e.receiving=3]="receiving",e[e.stopping=4]="stopping",e[e.stopped=5]="stopped"}(r||(r={})),function(e){e.urlEncoded="application/x-www-form-urlencoded",e.multipart="multipart/form-data",e.plain="text/plain"}(n||(n={}));class O{static confirmMethod(e,t,s){return Promise.resolve(confirm(e))}constructor(e,t,s,n=!1){this.state=r.initialized,this.delegate=e,this.formElement=t,this.submitter=s,this.formData=function(e,t){const s=new FormData(e),i=null==t?void 0:t.getAttribute("name"),r=null==t?void 0:t.getAttribute("value");i&&s.append(i,r||"");return s}(t,s),this.location=h(this.action),this.method==i.get&&function(e,t){const s=new URLSearchParams;for(const[e,i]of t)i instanceof File||s.append(e,i);e.search=s.toString()}(this.location,[...this.body.entries()]),this.fetchRequest=new H(this,this.method,this.location,this.body,this.formElement),this.mustRedirect=n}get method(){var e;return function(e){switch(e.toLowerCase()){case"get":return i.get;case"post":return i.post;case"put":return i.put;case"patch":return i.patch;case"delete":return i.delete}}(((null===(e=this.submitter)||void 0===e?void 0:e.getAttribute("formmethod"))||this.formElement.getAttribute("method")||"").toLowerCase())||i.get}get action(){var e;const t="string"==typeof this.formElement.action?this.formElement.action:null;return(null===(e=this.submitter)||void 0===e?void 0:e.hasAttribute("formaction"))?this.submitter.getAttribute("formaction")||"":this.formElement.getAttribute("action")||t||""}get body(){return this.enctype==n.urlEncoded||this.method==i.get?new URLSearchParams(this.stringFormData):this.formData}get enctype(){var e;return function(e){switch(e.toLowerCase()){case n.multipart:return n.multipart;case n.plain:return n.plain;default:return n.urlEncoded}}((null===(e=this.submitter)||void 0===e?void 0:e.getAttribute("formenctype"))||this.formElement.enctype)}get isSafe(){return this.fetchRequest.isSafe}get stringFormData(){return[...this.formData].reduce(((e,[t,s])=>e.concat("string"==typeof s?[[t,s]]:[])),[])}async start(){const{initialized:e,requesting:t}=r,s=R("data-turbo-confirm",this.submitter,this.formElement);if("string"==typeof s){if(!await O.confirmMethod(s,this.formElement,this.submitter))return}if(this.state==e)return this.state=t,this.fetchRequest.perform()}stop(){const{stopping:e,stopped:t}=r;if(this.state!=e&&this.state!=t)return this.state=e,this.fetchRequest.cancel(),!0}prepareRequest(e){if(!e.isSafe){const t=function(e){if(null!=e){const t=(document.cookie?document.cookie.split("; "):[]).find((t=>t.startsWith(e)));if(t){const e=t.split("=").slice(1).join("=");return e?decodeURIComponent(e):void 0}}}(M("csrf-param"))||M("csrf-token");t&&(e.headers["X-CSRF-Token"]=t)}this.requestAcceptsTurboStreamResponse(e)&&e.acceptResponseType(B.contentType)}requestStarted(e){var t;this.state=r.waiting,null===(t=this.submitter)||void 0===t||t.setAttribute("disabled",""),this.setSubmitsWith(),w("turbo:submit-start",{target:this.formElement,detail:{formSubmission:this}}),this.delegate.formSubmissionStarted(this)}requestPreventedHandlingResponse(e,t){this.result={success:t.succeeded,fetchResponse:t}}requestSucceededWithResponse(e,t){if(t.clientError||t.serverError)this.delegate.formSubmissionFailedWithResponse(this,t);else if(this.requestMustRedirect(e)&&function(e){return 200==e.statusCode&&!e.redirected}(t)){const e=new Error("Form responses must redirect to another location");this.delegate.formSubmissionErrored(this,e)}else this.state=r.receiving,this.result={success:!0,fetchResponse:t},this.delegate.formSubmissionSucceededWithResponse(this,t)}requestFailedWithResponse(e,t){this.result={success:!1,fetchResponse:t},this.delegate.formSubmissionFailedWithResponse(this,t)}requestErrored(e,t){this.result={success:!1,error:t},this.delegate.formSubmissionErrored(this,t)}requestFinished(e){var t;this.state=r.stopped,null===(t=this.submitter)||void 0===t||t.removeAttribute("disabled"),this.resetSubmitterText(),w("turbo:submit-end",{target:this.formElement,detail:Object.assign({formSubmission:this},this.result)}),this.delegate.formSubmissionFinished(this)}setSubmitsWith(){if(this.submitter&&this.submitsWith)if(this.submitter.matches("button"))this.originalSubmitText=this.submitter.innerHTML,this.submitter.innerHTML=this.submitsWith;else if(this.submitter.matches("input")){const e=this.submitter;this.originalSubmitText=e.value,e.value=this.submitsWith}}resetSubmitterText(){if(this.submitter&&this.originalSubmitText)if(this.submitter.matches("button"))this.submitter.innerHTML=this.originalSubmitText;else if(this.submitter.matches("input")){this.submitter.value=this.originalSubmitText}}requestMustRedirect(e){return!e.isSafe&&this.mustRedirect}requestAcceptsTurboStreamResponse(e){return!e.isSafe||function(e,...t){return t.some((t=>t&&t.hasAttribute(e)))}("data-turbo-stream",this.submitter,this.formElement)}get submitsWith(){var e;return null===(e=this.submitter)||void 0===e?void 0:e.getAttribute("data-turbo-submits-with")}}class N{constructor(e){this.element=e}get activeElement(){return this.element.ownerDocument.activeElement}get children(){return[...this.element.children]}hasAnchor(e){return null!=this.getElementForAnchor(e)}getElementForAnchor(e){return e?this.element.querySelector(`[id='${e}'], a[name='${e}']`):null}get isConnected(){return this.element.isConnected}get firstAutofocusableElement(){for(const e of this.element.querySelectorAll("[autofocus]"))if(null==e.closest("[inert], :disabled, [hidden], details:not([open]), dialog:not([open])"))return e;return null}get permanentElements(){return W(this.element)}getPermanentElementById(e){return V(this.element,e)}getPermanentElementMapForSnapshot(e){const t={};for(const s of this.permanentElements){const{id:i}=s,r=e.getPermanentElementById(i);r&&(t[i]=[s,r])}return t}}function V(e,t){return e.querySelector(`#${t}[data-turbo-permanent]`)}function W(e){return e.querySelectorAll("[id][data-turbo-permanent]")}class D{constructor(e,t){this.started=!1,this.submitCaptured=()=>{this.eventTarget.removeEventListener("submit",this.submitBubbled,!1),this.eventTarget.addEventListener("submit",this.submitBubbled,!1)},this.submitBubbled=e=>{if(!e.defaultPrevented){const t=e.target instanceof HTMLFormElement?e.target:void 0,s=e.submitter||void 0;t&&function(e,t){const s=(null==t?void 0:t.getAttribute("formmethod"))||e.getAttribute("method");return"dialog"!=s}(t,s)&&function(e,t){if((null==t?void 0:t.hasAttribute("formtarget"))||e.hasAttribute("target")){const s=(null==t?void 0:t.getAttribute("formtarget"))||e.target;for(const e of document.getElementsByName(s))if(e instanceof HTMLIFrameElement)return!1;return!0}return!0}(t,s)&&this.delegate.willSubmitForm(t,s)&&(e.preventDefault(),e.stopImmediatePropagation(),this.delegate.formSubmitted(t,s))}},this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("submit",this.submitCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("submit",this.submitCaptured,!0),this.started=!1)}}class x{constructor(e,t){this.resolveRenderPromise=e=>{},this.resolveInterceptionPromise=e=>{},this.delegate=e,this.element=t}scrollToAnchor(e){const t=this.snapshot.getElementForAnchor(e);t?(this.scrollToElement(t),this.focusElement(t)):this.scrollToPosition({x:0,y:0})}scrollToAnchorFromLocation(e){this.scrollToAnchor(c(e))}scrollToElement(e){e.scrollIntoView()}focusElement(e){e instanceof HTMLElement&&(e.hasAttribute("tabindex")?e.focus():(e.setAttribute("tabindex","-1"),e.focus(),e.removeAttribute("tabindex")))}scrollToPosition({x:e,y:t}){this.scrollRoot.scrollTo(e,t)}scrollToTop(){this.scrollToPosition({x:0,y:0})}get scrollRoot(){return window}async render(e){const{isPreview:t,shouldRender:s,newSnapshot:i}=e;if(s)try{this.renderPromise=new Promise((e=>this.resolveRenderPromise=e)),this.renderer=e,await this.prepareToRenderSnapshot(e);const s=new Promise((e=>this.resolveInterceptionPromise=e)),r={resume:this.resolveInterceptionPromise,render:this.renderer.renderElement};this.delegate.allowsImmediateRender(i,r)||await s,await this.renderSnapshot(e),this.delegate.viewRenderedSnapshot(i,t),this.delegate.preloadOnLoadLinksForView(this.element),this.finishRenderingSnapshot(e)}finally{delete this.renderer,this.resolveRenderPromise(void 0),delete this.renderPromise}else this.invalidate(e.reloadReason)}invalidate(e){this.delegate.viewInvalidated(e)}async prepareToRenderSnapshot(e){this.markAsPreview(e.isPreview),await e.prepareToRender()}markAsPreview(e){e?this.element.setAttribute("data-turbo-preview",""):this.element.removeAttribute("data-turbo-preview")}async renderSnapshot(e){await e.render()}finishRenderingSnapshot(e){e.finishRendering()}}class U extends x{missing(){this.element.innerHTML='Content missing'}get snapshot(){return new N(this.element)}}class j{constructor(e,t){this.clickBubbled=e=>{this.respondsToEventTarget(e.target)?this.clickEvent=e:delete this.clickEvent},this.linkClicked=e=>{this.clickEvent&&this.respondsToEventTarget(e.target)&&e.target instanceof Element&&this.delegate.shouldInterceptLinkClick(e.target,e.detail.url,e.detail.originalEvent)&&(this.clickEvent.preventDefault(),e.preventDefault(),this.delegate.linkClickIntercepted(e.target,e.detail.url,e.detail.originalEvent)),delete this.clickEvent},this.willVisit=e=>{delete this.clickEvent},this.delegate=e,this.element=t}start(){this.element.addEventListener("click",this.clickBubbled),document.addEventListener("turbo:click",this.linkClicked),document.addEventListener("turbo:before-visit",this.willVisit)}stop(){this.element.removeEventListener("click",this.clickBubbled),document.removeEventListener("turbo:click",this.linkClicked),document.removeEventListener("turbo:before-visit",this.willVisit)}respondsToEventTarget(e){const t=e instanceof Element?e:e instanceof Node?e.parentElement:null;return t&&t.closest("turbo-frame, html")==this.element}}class ${constructor(e,t){this.started=!1,this.clickCaptured=()=>{this.eventTarget.removeEventListener("click",this.clickBubbled,!1),this.eventTarget.addEventListener("click",this.clickBubbled,!1)},this.clickBubbled=e=>{if(e instanceof MouseEvent&&this.clickEventIsSignificant(e)){const t=e.composedPath&&e.composedPath()[0]||e.target,s=this.findLinkFromClickTarget(t);if(s&&function(e){if(e.hasAttribute("target")){for(const t of document.getElementsByName(e.target))if(t instanceof HTMLIFrameElement)return!1;return!0}return!0}(s)){const t=this.getLocationForLink(s);this.delegate.willFollowLinkToLocation(s,t,e)&&(e.preventDefault(),this.delegate.followedLinkToLocation(s,t))}}},this.delegate=e,this.eventTarget=t}start(){this.started||(this.eventTarget.addEventListener("click",this.clickCaptured,!0),this.started=!0)}stop(){this.started&&(this.eventTarget.removeEventListener("click",this.clickCaptured,!0),this.started=!1)}clickEventIsSignificant(e){return!(e.target&&e.target.isContentEditable||e.defaultPrevented||e.which>1||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}findLinkFromClickTarget(e){return I(e,"a[href]:not([target^=_]):not([download])")}getLocationForLink(e){return h(e.getAttribute("href")||"")}}class z{constructor(e,t){this.delegate=e,this.linkInterceptor=new $(this,t)}start(){this.linkInterceptor.start()}stop(){this.linkInterceptor.stop()}willFollowLinkToLocation(e,t,s){return this.delegate.willSubmitFormLinkToLocation(e,t,s)&&e.hasAttribute("data-turbo-method")}followedLinkToLocation(e,t){const s=document.createElement("form");for(const[e,i]of t.searchParams)s.append(Object.assign(document.createElement("input"),{type:"hidden",name:e,value:i}));const i=Object.assign(t,{search:""});s.setAttribute("data-turbo","true"),s.setAttribute("action",i.href),s.setAttribute("hidden","");const r=e.getAttribute("data-turbo-method");r&&s.setAttribute("method",r);const n=e.getAttribute("data-turbo-frame");n&&s.setAttribute("data-turbo-frame",n);const o=F(e);o&&s.setAttribute("data-turbo-action",o);const a=e.getAttribute("data-turbo-confirm");a&&s.setAttribute("data-turbo-confirm",a);e.hasAttribute("data-turbo-stream")&&s.setAttribute("data-turbo-stream",""),this.delegate.submittedFormLinkToLocation(e,t,s),document.body.appendChild(s),s.addEventListener("turbo:submit-end",(()=>s.remove()),{once:!0}),requestAnimationFrame((()=>s.requestSubmit()))}}class _{static async preservingPermanentElements(e,t,s){const i=new this(e,t);i.enter(),await s(),i.leave()}constructor(e,t){this.delegate=e,this.permanentElementMap=t}enter(){for(const e in this.permanentElementMap){const[t,s]=this.permanentElementMap[e];this.delegate.enteringBardo(t,s),this.replaceNewPermanentElementWithPlaceholder(s)}}leave(){for(const e in this.permanentElementMap){const[t]=this.permanentElementMap[e];this.replaceCurrentPermanentElementWithClone(t),this.replacePlaceholderWithPermanentElement(t),this.delegate.leavingBardo(t)}}replaceNewPermanentElementWithPlaceholder(e){const t=function(e){const t=document.createElement("meta");return t.setAttribute("name","turbo-permanent-placeholder"),t.setAttribute("content",e.id),t}(e);e.replaceWith(t)}replaceCurrentPermanentElementWithClone(e){const t=e.cloneNode(!0);e.replaceWith(t)}replacePlaceholderWithPermanentElement(e){const t=this.getPlaceholderById(e.id);null==t||t.replaceWith(e)}getPlaceholderById(e){return this.placeholders.find((t=>t.content==e))}get placeholders(){return[...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]}}class K{constructor(e,t,s,i,r=!0){this.activeElement=null,this.currentSnapshot=e,this.newSnapshot=t,this.isPreview=i,this.willRender=r,this.renderElement=s,this.promise=new Promise(((e,t)=>this.resolvingFunctions={resolve:e,reject:t}))}get shouldRender(){return!0}get reloadReason(){}prepareToRender(){}finishRendering(){this.resolvingFunctions&&(this.resolvingFunctions.resolve(),delete this.resolvingFunctions)}async preservingPermanentElements(e){await _.preservingPermanentElements(this,this.permanentElementMap,e)}focusFirstAutofocusableElement(){const e=this.connectedSnapshot.firstAutofocusableElement;(function(e){return e&&"function"==typeof e.focus})(e)&&e.focus()}enteringBardo(e){this.activeElement||e.contains(this.currentSnapshot.activeElement)&&(this.activeElement=this.currentSnapshot.activeElement)}leavingBardo(e){e.contains(this.activeElement)&&this.activeElement instanceof HTMLElement&&(this.activeElement.focus(),this.activeElement=null)}get connectedSnapshot(){return this.newSnapshot.isConnected?this.newSnapshot:this.currentSnapshot}get currentElement(){return this.currentSnapshot.element}get newElement(){return this.newSnapshot.element}get permanentElementMap(){return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)}}class Q extends K{static renderElement(e,t){var s;const i=document.createRange();i.selectNodeContents(e),i.deleteContents();const r=t,n=null===(s=r.ownerDocument)||void 0===s?void 0:s.createRange();n&&(n.selectNodeContents(r),e.appendChild(n.extractContents()))}constructor(e,t,s,i,r,n=!0){super(t,s,i,r,n),this.delegate=e}get shouldRender(){return!0}async render(){await S(),this.preservingPermanentElements((()=>{this.loadFrameElement()})),this.scrollFrameIntoView(),await S(),this.focusFirstAutofocusableElement(),await S(),this.activateScriptElements()}loadFrameElement(){this.delegate.willRenderFrame(this.currentElement,this.newElement),this.renderElement(this.currentElement,this.newElement)}scrollFrameIntoView(){if(this.currentElement.autoscroll||this.newElement.autoscroll){const s=this.currentElement.firstElementChild,i=(e=this.currentElement.getAttribute("data-autoscroll-block"),t="end","end"==e||"start"==e||"center"==e||"nearest"==e?e:t),r=function(e,t){return"auto"==e||"smooth"==e?e:t}(this.currentElement.getAttribute("data-autoscroll-behavior"),"auto");if(s)return s.scrollIntoView({block:i,behavior:r}),!0}var e,t;return!1}activateScriptElements(){for(const e of this.newScriptElements){const t=b(e);e.replaceWith(t)}}get newScriptElements(){return this.currentElement.querySelectorAll("script")}}class X{static get defaultCSS(){return y` 8 | .turbo-progress-bar { 9 | position: fixed; 10 | display: block; 11 | top: 0; 12 | left: 0; 13 | height: 3px; 14 | background: #0076ff; 15 | z-index: 2147483647; 16 | transition: 17 | width ${X.animationDuration}ms ease-out, 18 | opacity ${X.animationDuration/2}ms ${X.animationDuration/2}ms ease-in; 19 | transform: translate3d(0, 0, 0); 20 | } 21 | `}constructor(){this.hiding=!1,this.value=0,this.visible=!1,this.trickle=()=>{this.setValue(this.value+Math.random()/100)},this.stylesheetElement=this.createStylesheetElement(),this.progressElement=this.createProgressElement(),this.installStylesheetElement(),this.setValue(0)}show(){this.visible||(this.visible=!0,this.installProgressElement(),this.startTrickling())}hide(){this.visible&&!this.hiding&&(this.hiding=!0,this.fadeProgressElement((()=>{this.uninstallProgressElement(),this.stopTrickling(),this.visible=!1,this.hiding=!1})))}setValue(e){this.value=e,this.refresh()}installStylesheetElement(){document.head.insertBefore(this.stylesheetElement,document.head.firstChild)}installProgressElement(){this.progressElement.style.width="0",this.progressElement.style.opacity="1",document.documentElement.insertBefore(this.progressElement,document.body),this.refresh()}fadeProgressElement(e){this.progressElement.style.opacity="0",setTimeout(e,1.5*X.animationDuration)}uninstallProgressElement(){this.progressElement.parentNode&&document.documentElement.removeChild(this.progressElement)}startTrickling(){this.trickleInterval||(this.trickleInterval=window.setInterval(this.trickle,X.animationDuration))}stopTrickling(){window.clearInterval(this.trickleInterval),delete this.trickleInterval}refresh(){requestAnimationFrame((()=>{this.progressElement.style.width=10+90*this.value+"%"}))}createStylesheetElement(){const e=document.createElement("style");return e.type="text/css",e.textContent=X.defaultCSS,this.cspNonce&&(e.nonce=this.cspNonce),e}createProgressElement(){const e=document.createElement("div");return e.className="turbo-progress-bar",e}get cspNonce(){return M("csp-nonce")}}X.animationDuration=300;class Y extends N{constructor(){super(...arguments),this.detailsByOuterHTML=this.children.filter((e=>!function(e){const t=e.localName;return"noscript"==t}(e))).map((e=>function(e){e.hasAttribute("nonce")&&e.setAttribute("nonce","");return e}(e))).reduce(((e,t)=>{const{outerHTML:s}=t,i=s in e?e[s]:{type:J(t),tracked:G(t),elements:[]};return Object.assign(Object.assign({},e),{[s]:Object.assign(Object.assign({},i),{elements:[...i.elements,t]})})}),{})}get trackedElementSignature(){return Object.keys(this.detailsByOuterHTML).filter((e=>this.detailsByOuterHTML[e].tracked)).join("")}getScriptElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("script",e)}getStylesheetElementsNotInSnapshot(e){return this.getElementsMatchingTypeNotInSnapshot("stylesheet",e)}getElementsMatchingTypeNotInSnapshot(e,t){return Object.keys(this.detailsByOuterHTML).filter((e=>!(e in t.detailsByOuterHTML))).map((e=>this.detailsByOuterHTML[e])).filter((({type:t})=>t==e)).map((({elements:[e]})=>e))}get provisionalElements(){return Object.keys(this.detailsByOuterHTML).reduce(((e,t)=>{const{type:s,tracked:i,elements:r}=this.detailsByOuterHTML[t];return null!=s||i?r.length>1?[...e,...r.slice(1)]:e:[...e,...r]}),[])}getMetaValue(e){const t=this.findMetaElementByName(e);return t?t.getAttribute("content"):null}findMetaElementByName(e){return Object.keys(this.detailsByOuterHTML).reduce(((t,s)=>{const{elements:[i]}=this.detailsByOuterHTML[s];return function(e,t){const s=e.localName;return"meta"==s&&e.getAttribute("name")==t}(i,e)?i:t}),void 0)}}function J(e){return function(e){const t=e.localName;return"script"==t}(e)?"script":function(e){const t=e.localName;return"style"==t||"link"==t&&"stylesheet"==e.getAttribute("rel")}(e)?"stylesheet":void 0}function G(e){return"reload"==e.getAttribute("data-turbo-track")}class Z extends N{static fromHTMLString(e=""){return this.fromDocument(E(e))}static fromElement(e){return this.fromDocument(e.ownerDocument)}static fromDocument({head:e,body:t}){return new this(t,new Y(e))}constructor(e,t){super(e),this.headSnapshot=t}clone(){const e=this.element.cloneNode(!0),t=this.element.querySelectorAll("select"),s=e.querySelectorAll("select");for(const[e,i]of t.entries()){const t=s[e];for(const e of t.selectedOptions)e.selected=!1;for(const e of i.selectedOptions)t.options[e.index].selected=!0}for(const t of e.querySelectorAll('input[type="password"]'))t.value="";return new Z(e,this.headSnapshot)}get headElement(){return this.headSnapshot.element}get rootLocation(){var e;return h(null!==(e=this.getSetting("root"))&&void 0!==e?e:"/")}get cacheControlValue(){return this.getSetting("cache-control")}get isPreviewable(){return"no-preview"!=this.cacheControlValue}get isCacheable(){return"no-cache"!=this.cacheControlValue}get isVisitable(){return"reload"!=this.getSetting("visit-control")}getSetting(e){return this.headSnapshot.getMetaValue(`turbo-${e}`)}}!function(e){e.visitStart="visitStart",e.requestStart="requestStart",e.requestEnd="requestEnd",e.visitEnd="visitEnd"}(o||(o={})),function(e){e.initialized="initialized",e.started="started",e.canceled="canceled",e.failed="failed",e.completed="completed"}(a||(a={}));const ee={action:"advance",historyChanged:!1,visitCachedSnapshot:()=>{},willRender:!0,updateHistory:!0,shouldCacheSnapshot:!0,acceptsStreamResponse:!1};var te,se;!function(e){e[e.networkFailure=0]="networkFailure",e[e.timeoutFailure=-1]="timeoutFailure",e[e.contentTypeMismatch=-2]="contentTypeMismatch"}(te||(te={}));class ie{constructor(e,t,s,i={}){this.identifier=L(),this.timingMetrics={},this.followedRedirect=!1,this.historyChanged=!1,this.scrolled=!1,this.shouldCacheSnapshot=!0,this.acceptsStreamResponse=!1,this.snapshotCached=!1,this.state=a.initialized,this.delegate=e,this.location=t,this.restorationIdentifier=s||L();const{action:r,historyChanged:n,referrer:o,snapshot:l,snapshotHTML:h,response:c,visitCachedSnapshot:d,willRender:u,updateHistory:m,shouldCacheSnapshot:p,acceptsStreamResponse:g}=Object.assign(Object.assign({},ee),i);this.action=r,this.historyChanged=n,this.referrer=o,this.snapshot=l,this.snapshotHTML=h,this.response=c,this.isSamePage=this.delegate.locationWithActionIsSamePage(this.location,this.action),this.visitCachedSnapshot=d,this.willRender=u,this.updateHistory=m,this.scrolled=!u,this.shouldCacheSnapshot=p,this.acceptsStreamResponse=g}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get history(){return this.delegate.history}get restorationData(){return this.history.getRestorationDataForIdentifier(this.restorationIdentifier)}get silent(){return this.isSamePage}start(){this.state==a.initialized&&(this.recordTimingMetric(o.visitStart),this.state=a.started,this.adapter.visitStarted(this),this.delegate.visitStarted(this))}cancel(){this.state==a.started&&(this.request&&this.request.cancel(),this.cancelRender(),this.state=a.canceled)}complete(){this.state==a.started&&(this.recordTimingMetric(o.visitEnd),this.state=a.completed,this.followRedirect(),this.followedRedirect||(this.adapter.visitCompleted(this),this.delegate.visitCompleted(this)))}fail(){this.state==a.started&&(this.state=a.failed,this.adapter.visitFailed(this))}changeHistory(){var e;if(!this.historyChanged&&this.updateHistory){const t=P(this.location.href===(null===(e=this.referrer)||void 0===e?void 0:e.href)?"replace":this.action);this.history.update(t,this.location,this.restorationIdentifier),this.historyChanged=!0}}issueRequest(){this.hasPreloadedResponse()?this.simulateRequest():this.shouldIssueRequest()&&!this.request&&(this.request=new H(this,i.get,this.location),this.request.perform())}simulateRequest(){this.response&&(this.startRequest(),this.recordResponse(),this.finishRequest())}startRequest(){this.recordTimingMetric(o.requestStart),this.adapter.visitRequestStarted(this)}recordResponse(e=this.response){if(this.response=e,e){const{statusCode:t}=e;re(t)?this.adapter.visitRequestCompleted(this):this.adapter.visitRequestFailedWithStatusCode(this,t)}}finishRequest(){this.recordTimingMetric(o.requestEnd),this.adapter.visitRequestFinished(this)}loadResponse(){if(this.response){const{statusCode:e,responseHTML:t}=this.response;this.render((async()=>{this.shouldCacheSnapshot&&this.cacheSnapshot(),this.view.renderPromise&&await this.view.renderPromise,re(e)&&null!=t?(await this.view.renderPage(Z.fromHTMLString(t),!1,this.willRender,this),this.performScroll(),this.adapter.visitRendered(this),this.complete()):(await this.view.renderError(Z.fromHTMLString(t),this),this.adapter.visitRendered(this),this.fail())}))}}getCachedSnapshot(){const e=this.view.getCachedSnapshotForLocation(this.location)||this.getPreloadedSnapshot();if(e&&(!c(this.location)||e.hasAnchor(c(this.location)))&&("restore"==this.action||e.isPreviewable))return e}getPreloadedSnapshot(){if(this.snapshotHTML)return Z.fromHTMLString(this.snapshotHTML)}hasCachedSnapshot(){return null!=this.getCachedSnapshot()}loadCachedSnapshot(){const e=this.getCachedSnapshot();if(e){const t=this.shouldIssueRequest();this.render((async()=>{this.cacheSnapshot(),this.isSamePage?this.adapter.visitRendered(this):(this.view.renderPromise&&await this.view.renderPromise,await this.view.renderPage(e,t,this.willRender,this),this.performScroll(),this.adapter.visitRendered(this),t||this.complete())}))}}followRedirect(){var e;this.redirectedToLocation&&!this.followedRedirect&&(null===(e=this.response)||void 0===e?void 0:e.redirected)&&(this.adapter.visitProposedToLocation(this.redirectedToLocation,{action:"replace",response:this.response,shouldCacheSnapshot:!1,willRender:!1}),this.followedRedirect=!0)}goToSamePageAnchor(){this.isSamePage&&this.render((async()=>{this.cacheSnapshot(),this.performScroll(),this.changeHistory(),this.adapter.visitRendered(this)}))}prepareRequest(e){this.acceptsStreamResponse&&e.acceptResponseType(B.contentType)}requestStarted(){this.startRequest()}requestPreventedHandlingResponse(e,t){}async requestSucceededWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:te.contentTypeMismatch,redirected:i}):(this.redirectedToLocation=t.redirected?t.location:void 0,this.recordResponse({statusCode:r,responseHTML:s,redirected:i}))}async requestFailedWithResponse(e,t){const s=await t.responseHTML,{redirected:i,statusCode:r}=t;null==s?this.recordResponse({statusCode:te.contentTypeMismatch,redirected:i}):this.recordResponse({statusCode:r,responseHTML:s,redirected:i})}requestErrored(e,t){this.recordResponse({statusCode:te.networkFailure,redirected:!1})}requestFinished(){this.finishRequest()}performScroll(){this.scrolled||this.view.forceReloaded||("restore"==this.action?this.scrollToRestoredPosition()||this.scrollToAnchor()||this.view.scrollToTop():this.scrollToAnchor()||this.view.scrollToTop(),this.isSamePage&&this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation,this.location),this.scrolled=!0)}scrollToRestoredPosition(){const{scrollPosition:e}=this.restorationData;if(e)return this.view.scrollToPosition(e),!0}scrollToAnchor(){const e=c(this.location);if(null!=e)return this.view.scrollToAnchor(e),!0}recordTimingMetric(e){this.timingMetrics[e]=(new Date).getTime()}getTimingMetrics(){return Object.assign({},this.timingMetrics)}getHistoryMethodForAction(e){switch(e){case"replace":return history.replaceState;case"advance":case"restore":return history.pushState}}hasPreloadedResponse(){return"object"==typeof this.response}shouldIssueRequest(){return!this.isSamePage&&("restore"==this.action?!this.hasCachedSnapshot():this.willRender)}cacheSnapshot(){this.snapshotCached||(this.view.cacheSnapshot(this.snapshot).then((e=>e&&this.visitCachedSnapshot(e))),this.snapshotCached=!0)}async render(e){this.cancelRender(),await new Promise((e=>{this.frame=requestAnimationFrame((()=>e()))})),await e(),delete this.frame}cancelRender(){this.frame&&(cancelAnimationFrame(this.frame),delete this.frame)}}function re(e){return e>=200&&e<300}class ne{constructor(e){this.progressBar=new X,this.showProgressBar=()=>{this.progressBar.show()},this.session=e}visitProposedToLocation(e,t){this.navigator.startVisit(e,(null==t?void 0:t.restorationIdentifier)||L(),t)}visitStarted(e){this.location=e.location,e.loadCachedSnapshot(),e.issueRequest(),e.goToSamePageAnchor()}visitRequestStarted(e){this.progressBar.setValue(0),e.hasCachedSnapshot()||"restore"!=e.action?this.showVisitProgressBarAfterDelay():this.showProgressBar()}visitRequestCompleted(e){e.loadResponse()}visitRequestFailedWithStatusCode(e,t){switch(t){case te.networkFailure:case te.timeoutFailure:case te.contentTypeMismatch:return this.reload({reason:"request_failed",context:{statusCode:t}});default:return e.loadResponse()}}visitRequestFinished(e){this.progressBar.setValue(1),this.hideVisitProgressBar()}visitCompleted(e){}pageInvalidated(e){this.reload(e)}visitFailed(e){}visitRendered(e){}formSubmissionStarted(e){this.progressBar.setValue(0),this.showFormProgressBarAfterDelay()}formSubmissionFinished(e){this.progressBar.setValue(1),this.hideFormProgressBar()}showVisitProgressBarAfterDelay(){this.visitProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay)}hideVisitProgressBar(){this.progressBar.hide(),null!=this.visitProgressBarTimeout&&(window.clearTimeout(this.visitProgressBarTimeout),delete this.visitProgressBarTimeout)}showFormProgressBarAfterDelay(){null==this.formProgressBarTimeout&&(this.formProgressBarTimeout=window.setTimeout(this.showProgressBar,this.session.progressBarDelay))}hideFormProgressBar(){this.progressBar.hide(),null!=this.formProgressBarTimeout&&(window.clearTimeout(this.formProgressBarTimeout),delete this.formProgressBarTimeout)}reload(e){var t;w("turbo:reload",{detail:e}),window.location.href=(null===(t=this.location)||void 0===t?void 0:t.toString())||window.location.href}get navigator(){return this.session.navigator}}class oe{constructor(){this.selector="[data-turbo-temporary]",this.deprecatedSelector="[data-turbo-cache=false]",this.started=!1,this.removeTemporaryElements=e=>{for(const e of this.temporaryElements)e.remove()}}start(){this.started||(this.started=!0,addEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}stop(){this.started&&(this.started=!1,removeEventListener("turbo:before-cache",this.removeTemporaryElements,!1))}get temporaryElements(){return[...document.querySelectorAll(this.selector),...this.temporaryElementsWithDeprecation]}get temporaryElementsWithDeprecation(){const e=document.querySelectorAll(this.deprecatedSelector);return e.length&&console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`),[...e]}}class ae{constructor(e,t){this.session=e,this.element=t,this.linkInterceptor=new j(this,t),this.formSubmitObserver=new D(this,t)}start(){this.linkInterceptor.start(),this.formSubmitObserver.start()}stop(){this.linkInterceptor.stop(),this.formSubmitObserver.stop()}shouldInterceptLinkClick(e,t,s){return this.shouldRedirect(e)}linkClickIntercepted(e,t,s){const i=this.findFrameElement(e);i&&i.delegate.linkClickIntercepted(e,t,s)}willSubmitForm(e,t){return null==e.closest("turbo-frame")&&this.shouldSubmit(e,t)&&this.shouldRedirect(e,t)}formSubmitted(e,t){const s=this.findFrameElement(e,t);s&&s.delegate.formSubmitted(e,t)}shouldSubmit(e,t){var s;const i=d(e,t),r=this.element.ownerDocument.querySelector('meta[name="turbo-root"]'),n=h(null!==(s=null==r?void 0:r.content)&&void 0!==s?s:"/");return this.shouldRedirect(e,t)&&p(i,n)}shouldRedirect(e,t){if(e instanceof HTMLFormElement?this.session.submissionIsNavigatable(e,t):this.session.elementIsNavigatable(e)){const s=this.findFrameElement(e,t);return!!s&&s!=e.closest("turbo-frame")}return!1}findFrameElement(e,t){const s=(null==t?void 0:t.getAttribute("data-turbo-frame"))||e.getAttribute("data-turbo-frame");if(s&&"_top"!=s){const e=this.element.querySelector(`#${s}:not([disabled])`);if(e instanceof l)return e}}}class le{constructor(e){this.restorationIdentifier=L(),this.restorationData={},this.started=!1,this.pageLoaded=!1,this.onPopState=e=>{if(this.shouldHandlePopState()){const{turbo:t}=e.state||{};if(t){this.location=new URL(window.location.href);const{restorationIdentifier:e}=t;this.restorationIdentifier=e,this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location,e)}}},this.onPageLoad=async e=>{await Promise.resolve(),this.pageLoaded=!0},this.delegate=e}start(){this.started||(addEventListener("popstate",this.onPopState,!1),addEventListener("load",this.onPageLoad,!1),this.started=!0,this.replace(new URL(window.location.href)))}stop(){this.started&&(removeEventListener("popstate",this.onPopState,!1),removeEventListener("load",this.onPageLoad,!1),this.started=!1)}push(e,t){this.update(history.pushState,e,t)}replace(e,t){this.update(history.replaceState,e,t)}update(e,t,s=L()){const i={turbo:{restorationIdentifier:s}};e.call(history,i,"",t.href),this.location=t,this.restorationIdentifier=s}getRestorationDataForIdentifier(e){return this.restorationData[e]||{}}updateRestorationData(e){const{restorationIdentifier:t}=this,s=this.restorationData[t];this.restorationData[t]=Object.assign(Object.assign({},s),e)}assumeControlOfScrollRestoration(){var e;this.previousScrollRestoration||(this.previousScrollRestoration=null!==(e=history.scrollRestoration)&&void 0!==e?e:"auto",history.scrollRestoration="manual")}relinquishControlOfScrollRestoration(){this.previousScrollRestoration&&(history.scrollRestoration=this.previousScrollRestoration,delete this.previousScrollRestoration)}shouldHandlePopState(){return this.pageIsLoaded()}pageIsLoaded(){return this.pageLoaded||"complete"==document.readyState}}class he{constructor(e){this.delegate=e}proposeVisit(e,t={}){this.delegate.allowsVisitingLocationWithAction(e,t.action)&&(p(e,this.view.snapshot.rootLocation)?this.delegate.visitProposedToLocation(e,t):window.location.href=e.toString())}startVisit(e,t,s={}){this.stop(),this.currentVisit=new ie(this,h(e),t,Object.assign({referrer:this.location},s)),this.currentVisit.start()}submitForm(e,t){this.stop(),this.formSubmission=new O(this,e,t,!0),this.formSubmission.start()}stop(){this.formSubmission&&(this.formSubmission.stop(),delete this.formSubmission),this.currentVisit&&(this.currentVisit.cancel(),delete this.currentVisit)}get adapter(){return this.delegate.adapter}get view(){return this.delegate.view}get history(){return this.delegate.history}formSubmissionStarted(e){"function"==typeof this.adapter.formSubmissionStarted&&this.adapter.formSubmissionStarted(e)}async formSubmissionSucceededWithResponse(e,t){if(e==this.formSubmission){const s=await t.responseHTML;if(s){const i=e.isSafe;i||this.view.clearSnapshotCache();const{statusCode:r,redirected:n}=t,o={action:this.getActionForFormSubmission(e),shouldCacheSnapshot:i,response:{statusCode:r,responseHTML:s,redirected:n}};this.proposeVisit(t.location,o)}}}async formSubmissionFailedWithResponse(e,t){const s=await t.responseHTML;if(s){const e=Z.fromHTMLString(s);t.serverError?await this.view.renderError(e,this.currentVisit):await this.view.renderPage(e,!1,!0,this.currentVisit),this.view.scrollToTop(),this.view.clearSnapshotCache()}}formSubmissionErrored(e,t){console.error(t)}formSubmissionFinished(e){"function"==typeof this.adapter.formSubmissionFinished&&this.adapter.formSubmissionFinished(e)}visitStarted(e){this.delegate.visitStarted(e)}visitCompleted(e){this.delegate.visitCompleted(e)}locationWithActionIsSamePage(e,t){const s=c(e),i=c(this.view.lastRenderedLocation),r="restore"===t&&void 0===s;return"replace"!==t&&g(e)===g(this.view.lastRenderedLocation)&&(r||null!=s&&s!==i)}visitScrolledToSamePageLocation(e,t){this.delegate.visitScrolledToSamePageLocation(e,t)}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}getActionForFormSubmission({submitter:e,formElement:t}){return F(e,t)||"advance"}}!function(e){e[e.initial=0]="initial",e[e.loading=1]="loading",e[e.interactive=2]="interactive",e[e.complete=3]="complete"}(se||(se={}));class ce{constructor(e){this.stage=se.initial,this.started=!1,this.interpretReadyState=()=>{const{readyState:e}=this;"interactive"==e?this.pageIsInteractive():"complete"==e&&this.pageIsComplete()},this.pageWillUnload=()=>{this.delegate.pageWillUnload()},this.delegate=e}start(){this.started||(this.stage==se.initial&&(this.stage=se.loading),document.addEventListener("readystatechange",this.interpretReadyState,!1),addEventListener("pagehide",this.pageWillUnload,!1),this.started=!0)}stop(){this.started&&(document.removeEventListener("readystatechange",this.interpretReadyState,!1),removeEventListener("pagehide",this.pageWillUnload,!1),this.started=!1)}pageIsInteractive(){this.stage==se.loading&&(this.stage=se.interactive,this.delegate.pageBecameInteractive())}pageIsComplete(){this.pageIsInteractive(),this.stage==se.interactive&&(this.stage=se.complete,this.delegate.pageLoaded())}get readyState(){return document.readyState}}class de{constructor(e){this.started=!1,this.onScroll=()=>{this.updatePosition({x:window.pageXOffset,y:window.pageYOffset})},this.delegate=e}start(){this.started||(addEventListener("scroll",this.onScroll,!1),this.onScroll(),this.started=!0)}stop(){this.started&&(removeEventListener("scroll",this.onScroll,!1),this.started=!1)}updatePosition(e){this.delegate.scrollPositionChanged(e)}}class ue{render({fragment:e}){_.preservingPermanentElements(this,function(e){const t=W(document.documentElement),s={};for(const i of t){const{id:t}=i;for(const r of e.querySelectorAll("turbo-stream")){const e=V(r.templateElement.content,t);e&&(s[t]=[i,e])}}return s}(e),(()=>document.documentElement.appendChild(e)))}enteringBardo(e,t){t.replaceWith(e.cloneNode(!0))}leavingBardo(){}}class me{constructor(e){this.sources=new Set,this.started=!1,this.inspectFetchResponse=e=>{const t=function(e){var t;const s=null===(t=e.detail)||void 0===t?void 0:t.fetchResponse;if(s instanceof v)return s}(e);t&&function(e){var t;const s=null!==(t=e.contentType)&&void 0!==t?t:"";return s.startsWith(B.contentType)}(t)&&(e.preventDefault(),this.receiveMessageResponse(t))},this.receiveMessageEvent=e=>{this.started&&"string"==typeof e.data&&this.receiveMessageHTML(e.data)},this.delegate=e}start(){this.started||(this.started=!0,addEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}stop(){this.started&&(this.started=!1,removeEventListener("turbo:before-fetch-response",this.inspectFetchResponse,!1))}connectStreamSource(e){this.streamSourceIsConnected(e)||(this.sources.add(e),e.addEventListener("message",this.receiveMessageEvent,!1))}disconnectStreamSource(e){this.streamSourceIsConnected(e)&&(this.sources.delete(e),e.removeEventListener("message",this.receiveMessageEvent,!1))}streamSourceIsConnected(e){return this.sources.has(e)}async receiveMessageResponse(e){const t=await e.responseHTML;t&&this.receiveMessageHTML(t)}receiveMessageHTML(e){this.delegate.receivedMessageFromStream(B.wrap(e))}}class pe extends K{static renderElement(e,t){const{documentElement:s,body:i}=document;s.replaceChild(t,i)}async render(){this.replaceHeadAndBody(),this.activateScriptElements()}replaceHeadAndBody(){const{documentElement:e,head:t}=document;e.replaceChild(this.newHead,t),this.renderElement(this.currentElement,this.newElement)}activateScriptElements(){for(const e of this.scriptElements){const t=e.parentNode;if(t){const s=b(e);t.replaceChild(s,e)}}}get newHead(){return this.newSnapshot.headSnapshot.element}get scriptElements(){return document.documentElement.querySelectorAll("script")}}class ge extends K{static renderElement(e,t){document.body&&t instanceof HTMLBodyElement?document.body.replaceWith(t):document.documentElement.appendChild(t)}get shouldRender(){return this.newSnapshot.isVisitable&&this.trackedElementsAreIdentical}get reloadReason(){return this.newSnapshot.isVisitable?this.trackedElementsAreIdentical?void 0:{reason:"tracked_element_mismatch"}:{reason:"turbo_visit_control_is_reload"}}async prepareToRender(){await this.mergeHead()}async render(){this.willRender&&await this.replaceBody()}finishRendering(){super.finishRendering(),this.isPreview||this.focusFirstAutofocusableElement()}get currentHeadSnapshot(){return this.currentSnapshot.headSnapshot}get newHeadSnapshot(){return this.newSnapshot.headSnapshot}get newElement(){return this.newSnapshot.element}async mergeHead(){const e=this.mergeProvisionalElements(),t=this.copyNewHeadStylesheetElements();this.copyNewHeadScriptElements(),await e,await t}async replaceBody(){await this.preservingPermanentElements((async()=>{this.activateNewBody(),await this.assignNewBody()}))}get trackedElementsAreIdentical(){return this.currentHeadSnapshot.trackedElementSignature==this.newHeadSnapshot.trackedElementSignature}async copyNewHeadStylesheetElements(){const e=[];for(const t of this.newHeadStylesheetElements)e.push(A(t)),document.head.appendChild(t);await Promise.all(e)}copyNewHeadScriptElements(){for(const e of this.newHeadScriptElements)document.head.appendChild(b(e))}async mergeProvisionalElements(){const e=[...this.newHeadProvisionalElements];for(const t of this.currentHeadProvisionalElements)this.isCurrentElementInElementList(t,e)||document.head.removeChild(t);for(const t of e)document.head.appendChild(t)}isCurrentElementInElementList(e,t){for(const[s,i]of t.entries()){if("TITLE"==e.tagName){if("TITLE"!=i.tagName)continue;if(e.innerHTML==i.innerHTML)return t.splice(s,1),!0}if(i.isEqualNode(e))return t.splice(s,1),!0}return!1}removeCurrentHeadProvisionalElements(){for(const e of this.currentHeadProvisionalElements)document.head.removeChild(e)}copyNewHeadProvisionalElements(){for(const e of this.newHeadProvisionalElements)document.head.appendChild(e)}activateNewBody(){document.adoptNode(this.newElement),this.activateNewBodyScriptElements()}activateNewBodyScriptElements(){for(const e of this.newBodyScriptElements){const t=b(e);e.replaceWith(t)}}async assignNewBody(){await this.renderElement(this.currentElement,this.newElement)}get newHeadStylesheetElements(){return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot)}get newHeadScriptElements(){return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot)}get currentHeadProvisionalElements(){return this.currentHeadSnapshot.provisionalElements}get newHeadProvisionalElements(){return this.newHeadSnapshot.provisionalElements}get newBodyScriptElements(){return this.newElement.querySelectorAll("script")}}class fe{constructor(e){this.keys=[],this.snapshots={},this.size=e}has(e){return f(e)in this.snapshots}get(e){if(this.has(e)){const t=this.read(e);return this.touch(e),t}}put(e,t){return this.write(e,t),this.touch(e),t}clear(){this.snapshots={}}read(e){return this.snapshots[f(e)]}write(e,t){this.snapshots[f(e)]=t}touch(e){const t=f(e),s=this.keys.indexOf(t);s>-1&&this.keys.splice(s,1),this.keys.unshift(t),this.trim()}trim(){for(const e of this.keys.splice(this.size))delete this.snapshots[e]}}class ve extends x{constructor(){super(...arguments),this.snapshotCache=new fe(10),this.lastRenderedLocation=new URL(location.href),this.forceReloaded=!1}renderPage(e,t=!1,s=!0,i){const r=new ge(this.snapshot,e,ge.renderElement,t,s);return r.shouldRender?null==i||i.changeHistory():this.forceReloaded=!0,this.render(r)}renderError(e,t){null==t||t.changeHistory();const s=new pe(this.snapshot,e,pe.renderElement,!1);return this.render(s)}clearSnapshotCache(){this.snapshotCache.clear()}async cacheSnapshot(e=this.snapshot){if(e.isCacheable){this.delegate.viewWillCacheSnapshot();const{lastRenderedLocation:t}=this;await new Promise((e=>setTimeout((()=>e()),0)));const s=e.clone();return this.snapshotCache.put(t,s),s}}getCachedSnapshotForLocation(e){return this.snapshotCache.get(e)}get snapshot(){return Z.fromElement(this.element)}}class be{constructor(e){this.selector="a[data-turbo-preload]",this.delegate=e}get snapshotCache(){return this.delegate.navigator.view.snapshotCache}start(){if("loading"===document.readyState)return document.addEventListener("DOMContentLoaded",(()=>{this.preloadOnLoadLinksForView(document.body)}));this.preloadOnLoadLinksForView(document.body)}preloadOnLoadLinksForView(e){for(const t of e.querySelectorAll(this.selector))this.preloadURL(t)}async preloadURL(e){const t=new URL(e.href);if(!this.snapshotCache.has(t))try{const e=await fetch(t.toString(),{headers:{"VND.PREFETCH":"true",Accept:"text/html"}}),s=await e.text(),i=Z.fromHTMLString(s);this.snapshotCache.put(t,i)}catch(e){}}}function we(e){Object.defineProperties(e,Se)}const Se={absoluteURL:{get(){return this.toString()}}};const Ee={after(){this.targetElements.forEach((e=>{var t;return null===(t=e.parentElement)||void 0===t?void 0:t.insertBefore(this.templateContent,e.nextSibling)}))},append(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.append(this.templateContent)))},before(){this.targetElements.forEach((e=>{var t;return null===(t=e.parentElement)||void 0===t?void 0:t.insertBefore(this.templateContent,e)}))},prepend(){this.removeDuplicateTargetChildren(),this.targetElements.forEach((e=>e.prepend(this.templateContent)))},remove(){this.targetElements.forEach((e=>e.remove()))},replace(){this.targetElements.forEach((e=>e.replaceWith(this.templateContent)))},update(){this.targetElements.forEach((e=>{e.innerHTML="",e.append(this.templateContent)}))}},ye=new class{constructor(){this.navigator=new he(this),this.history=new le(this),this.preloader=new be(this),this.view=new ve(this,document.documentElement),this.adapter=new ne(this),this.pageObserver=new ce(this),this.cacheObserver=new oe,this.linkClickObserver=new $(this,window),this.formSubmitObserver=new D(this,document),this.scrollObserver=new de(this),this.streamObserver=new me(this),this.formLinkClickObserver=new z(this,document.documentElement),this.frameRedirector=new ae(this,document.documentElement),this.streamMessageRenderer=new ue,this.drive=!0,this.enabled=!0,this.progressBarDelay=500,this.started=!1,this.formMode="on"}start(){this.started||(this.pageObserver.start(),this.cacheObserver.start(),this.formLinkClickObserver.start(),this.linkClickObserver.start(),this.formSubmitObserver.start(),this.scrollObserver.start(),this.streamObserver.start(),this.frameRedirector.start(),this.history.start(),this.preloader.start(),this.started=!0,this.enabled=!0)}disable(){this.enabled=!1}stop(){this.started&&(this.pageObserver.stop(),this.cacheObserver.stop(),this.formLinkClickObserver.stop(),this.linkClickObserver.stop(),this.formSubmitObserver.stop(),this.scrollObserver.stop(),this.streamObserver.stop(),this.frameRedirector.stop(),this.history.stop(),this.started=!1)}registerAdapter(e){this.adapter=e}visit(e,t={}){const s=t.frame?document.getElementById(t.frame):null;s instanceof l?(s.src=e.toString(),s.loaded):this.navigator.proposeVisit(h(e),t)}connectStreamSource(e){this.streamObserver.connectStreamSource(e)}disconnectStreamSource(e){this.streamObserver.disconnectStreamSource(e)}renderStreamMessage(e){this.streamMessageRenderer.render(B.wrap(e))}clearCache(){this.view.clearSnapshotCache()}setProgressBarDelay(e){this.progressBarDelay=e}setFormMode(e){this.formMode=e}get location(){return this.history.location}get restorationIdentifier(){return this.history.restorationIdentifier}historyPoppedToLocationWithRestorationIdentifier(e,t){this.enabled?this.navigator.startVisit(e,t,{action:"restore",historyChanged:!0}):this.adapter.pageInvalidated({reason:"turbo_disabled"})}scrollPositionChanged(e){this.history.updateRestorationData({scrollPosition:e})}willSubmitFormLinkToLocation(e,t){return this.elementIsNavigatable(e)&&p(t,this.snapshot.rootLocation)}submittedFormLinkToLocation(){}willFollowLinkToLocation(e,t,s){return this.elementIsNavigatable(e)&&p(t,this.snapshot.rootLocation)&&this.applicationAllowsFollowingLinkToLocation(e,t,s)}followedLinkToLocation(e,t){const s=this.getActionForLink(e),i=e.hasAttribute("data-turbo-stream");this.visit(t.href,{action:s,acceptsStreamResponse:i})}allowsVisitingLocationWithAction(e,t){return this.locationWithActionIsSamePage(e,t)||this.applicationAllowsVisitingLocation(e)}visitProposedToLocation(e,t){we(e),this.adapter.visitProposedToLocation(e,t)}visitStarted(e){e.acceptsStreamResponse||C(document.documentElement),we(e.location),e.silent||this.notifyApplicationAfterVisitingLocation(e.location,e.action)}visitCompleted(e){T(document.documentElement),this.notifyApplicationAfterPageLoad(e.getTimingMetrics())}locationWithActionIsSamePage(e,t){return this.navigator.locationWithActionIsSamePage(e,t)}visitScrolledToSamePageLocation(e,t){this.notifyApplicationAfterVisitingSamePageLocation(e,t)}willSubmitForm(e,t){const s=d(e,t);return this.submissionIsNavigatable(e,t)&&p(h(s),this.snapshot.rootLocation)}formSubmitted(e,t){this.navigator.submitForm(e,t)}pageBecameInteractive(){this.view.lastRenderedLocation=this.location,this.notifyApplicationAfterPageLoad()}pageLoaded(){this.history.assumeControlOfScrollRestoration()}pageWillUnload(){this.history.relinquishControlOfScrollRestoration()}receivedMessageFromStream(e){this.renderStreamMessage(e)}viewWillCacheSnapshot(){var e;(null===(e=this.navigator.currentVisit)||void 0===e?void 0:e.silent)||this.notifyApplicationBeforeCachingSnapshot()}allowsImmediateRender({element:e},t){const s=this.notifyApplicationBeforeRender(e,t),{defaultPrevented:i,detail:{render:r}}=s;return this.view.renderer&&r&&(this.view.renderer.renderElement=r),!i}viewRenderedSnapshot(e,t){this.view.lastRenderedLocation=this.history.location,this.notifyApplicationAfterRender()}preloadOnLoadLinksForView(e){this.preloader.preloadOnLoadLinksForView(e)}viewInvalidated(e){this.adapter.pageInvalidated(e)}frameLoaded(e){this.notifyApplicationAfterFrameLoad(e)}frameRendered(e,t){this.notifyApplicationAfterFrameRender(e,t)}applicationAllowsFollowingLinkToLocation(e,t,s){return!this.notifyApplicationAfterClickingLinkToLocation(e,t,s).defaultPrevented}applicationAllowsVisitingLocation(e){return!this.notifyApplicationBeforeVisitingLocation(e).defaultPrevented}notifyApplicationAfterClickingLinkToLocation(e,t,s){return w("turbo:click",{target:e,detail:{url:t.href,originalEvent:s},cancelable:!0})}notifyApplicationBeforeVisitingLocation(e){return w("turbo:before-visit",{detail:{url:e.href},cancelable:!0})}notifyApplicationAfterVisitingLocation(e,t){return w("turbo:visit",{detail:{url:e.href,action:t}})}notifyApplicationBeforeCachingSnapshot(){return w("turbo:before-cache")}notifyApplicationBeforeRender(e,t){return w("turbo:before-render",{detail:Object.assign({newBody:e},t),cancelable:!0})}notifyApplicationAfterRender(){return w("turbo:render")}notifyApplicationAfterPageLoad(e={}){return w("turbo:load",{detail:{url:this.location.href,timing:e}})}notifyApplicationAfterVisitingSamePageLocation(e,t){dispatchEvent(new HashChangeEvent("hashchange",{oldURL:e.toString(),newURL:t.toString()}))}notifyApplicationAfterFrameLoad(e){return w("turbo:frame-load",{target:e})}notifyApplicationAfterFrameRender(e,t){return w("turbo:frame-render",{detail:{fetchResponse:e},target:t,cancelable:!0})}submissionIsNavigatable(e,t){if("off"==this.formMode)return!1;{const s=!t||this.elementIsNavigatable(t);return"optin"==this.formMode?s&&null!=e.closest('[data-turbo="true"]'):s&&this.elementIsNavigatable(e)}}elementIsNavigatable(e){const t=I(e,"[data-turbo]"),s=I(e,"turbo-frame");return this.drive||s?!t||"false"!=t.getAttribute("data-turbo"):!!t&&"true"==t.getAttribute("data-turbo")}getActionForLink(e){return F(e)||"advance"}get snapshot(){return this.view.snapshot}},Le=new class{constructor(e){this.session=e}clear(){this.session.clearCache()}resetCacheControl(){this.setCacheControl("")}exemptPageFromCache(){this.setCacheControl("no-cache")}exemptPageFromPreview(){this.setCacheControl("no-preview")}setCacheControl(e){!function(e,t){let s=k(e);s||(s=document.createElement("meta"),s.setAttribute("name",e),document.head.appendChild(s)),s.setAttribute("content",t)}("turbo-cache-control",e)}}(ye),{navigator:Re}=ye;function Ce(){ye.start()}function Te(e){ye.registerAdapter(e)}function Ae(e,t){ye.visit(e,t)}function Pe(e){ye.connectStreamSource(e)}function Fe(e){ye.disconnectStreamSource(e)}function ke(e){ye.renderStreamMessage(e)}function Me(){console.warn("Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`"),ye.clearCache()}function Ie(e){ye.setProgressBarDelay(e)}function He(e){O.confirmMethod=e}function qe(e){ye.setFormMode(e)}var Be=Object.freeze({__proto__:null,navigator:Re,session:ye,cache:Le,PageRenderer:ge,PageSnapshot:Z,FrameRenderer:Q,start:Ce,registerAdapter:Te,visit:Ae,connectStreamSource:Pe,disconnectStreamSource:Fe,renderStreamMessage:ke,clearCache:Me,setProgressBarDelay:Ie,setConfirmMethod:He,setFormMode:qe,StreamActions:Ee});class Oe extends Error{}function Ne(e){if(null!=e){const t=document.getElementById(e);if(t instanceof l)return t}}function Ve(e,t){if(e){const i=e.getAttribute("src");if(null!=i&&null!=t&&(s=t,h(i).href==h(s).href))throw new Error(`Matching element has a source URL which references itself`);if(e.ownerDocument!==document&&(e=document.importNode(e,!0)),e instanceof l)return e.connectedCallback(),e.disconnectedCallback(),e}var s}class We extends HTMLElement{static async renderElement(e){await e.performAction()}async connectedCallback(){try{await this.render()}catch(e){console.error(e)}finally{this.disconnect()}}async render(){var e;return null!==(e=this.renderPromise)&&void 0!==e?e:this.renderPromise=(async()=>{const e=this.beforeRenderEvent;this.dispatchEvent(e)&&(await S(),await e.detail.render(this))})()}disconnect(){try{this.remove()}catch(e){}}removeDuplicateTargetChildren(){this.duplicateChildren.forEach((e=>e.remove()))}get duplicateChildren(){var e;const t=this.targetElements.flatMap((e=>[...e.children])).filter((e=>!!e.id)),s=[...(null===(e=this.templateContent)||void 0===e?void 0:e.children)||[]].filter((e=>!!e.id)).map((e=>e.id));return t.filter((e=>s.includes(e.id)))}get performAction(){if(this.action){const e=Ee[this.action];if(e)return e;this.raise("unknown action")}this.raise("action attribute is missing")}get targetElements(){return this.target?this.targetElementsById:this.targets?this.targetElementsByQuery:void this.raise("target or targets attribute is missing")}get templateContent(){return this.templateElement.content.cloneNode(!0)}get templateElement(){if(null===this.firstElementChild){const e=this.ownerDocument.createElement("template");return this.appendChild(e),e}if(this.firstElementChild instanceof HTMLTemplateElement)return this.firstElementChild;this.raise("first child element must be a