hyrax 5.2.0 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.dassie/.env +5 -1
- data/.dassie/Gemfile +4 -2
- data/.dassie/app/assets/images/bulkrax/removed.png +0 -0
- data/.dassie/app/assets/javascripts/application.js +2 -0
- data/.dassie/app/assets/stylesheets/application.css +1 -0
- data/.dassie/app/controllers/catalog_controller.rb +1 -0
- data/.dassie/app/forms/admin_set_resource_form.rb +6 -0
- data/.dassie/app/forms/collection_resource_form.rb +5 -2
- data/.dassie/app/forms/generic_work_resource_form.rb +5 -2
- data/.dassie/app/forms/monograph_form.rb +5 -3
- data/.dassie/app/indexers/admin_set_resource_indexer.rb +5 -0
- data/.dassie/app/indexers/collection_resource_indexer.rb +3 -3
- data/.dassie/app/indexers/generic_work_resource_indexer.rb +6 -3
- data/.dassie/app/indexers/monograph_indexer.rb +6 -2
- data/.dassie/app/models/ability.rb +8 -0
- data/.dassie/app/models/collection_resource.rb +4 -2
- data/.dassie/app/models/concerns/bulkrax/has_local_processing.rb +8 -0
- data/.dassie/app/models/generic_work_resource.rb +5 -2
- data/.dassie/app/models/monograph.rb +5 -2
- data/.dassie/app/views/blacklight_dynamic_sitemap/sitemap/show.xml.builder +22 -0
- data/.dassie/bin/importer +142 -0
- data/.dassie/bin/web +4 -0
- data/.dassie/config/browse_everything_providers.yml +1 -1
- data/.dassie/config/bulkrax_api.yml +86 -0
- data/.dassie/config/initializers/bulkrax.rb +92 -0
- data/.dassie/config/initializers/clamav.rb +2 -0
- data/.dassie/config/initializers/hyrax.rb +7 -1
- data/.dassie/config/initializers/riiif.rb +4 -80
- data/.dassie/config/initializers/wings.rb +1 -1
- data/.dassie/config/metadata_profiles/m3_profile.yaml +929 -0
- data/.dassie/config/puma.rb +4 -2
- data/.dassie/config/routes.rb +7 -0
- data/.dassie/config/sidekiq.yml +17 -0
- data/.dassie/config/uv/uv.html +63 -81
- data/.dassie/db/migrate/20240606205215_create_hyrax_flexible_schemas.rb +9 -0
- data/.dassie/db/migrate/20240606205216_add_contexts_to_hyrax_flexible_schemas.rb +5 -0
- data/.dassie/db/migrate/20250826142438_create_bulkrax_importers.bulkrax.rb +19 -0
- data/.dassie/db/migrate/20250826142439_create_bulkrax_importer_runs.bulkrax.rb +17 -0
- data/.dassie/db/migrate/20250826142440_create_bulkrax_entries.bulkrax.rb +17 -0
- data/.dassie/db/migrate/20250826142441_add_status_to_entry.bulkrax.rb +10 -0
- data/.dassie/db/migrate/20250826142442_add_collections_to_importer_runs.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142443_change_collection_ids_on_entries.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142444_create_bulkrax_exporters.bulkrax.rb +20 -0
- data/.dassie/db/migrate/20250826142445_create_bulkrax_exporter_runs.bulkrax.rb +15 -0
- data/.dassie/db/migrate/20250826142446_change_importer_and_exporter_to_polymorphic.bulkrax.rb +19 -0
- data/.dassie/db/migrate/20250826142447_add_total_collection_records_to_importer_runs.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142448_add_children_to_importer_runs.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142449_change_total_records_to_total_work_entries.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142450_change_entry_last_error.bulkrax.rb +20 -0
- data/.dassie/db/migrate/20250826142451_add_validate_only_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142452_add_status_to_importers.bulkrax.rb +10 -0
- data/.dassie/db/migrate/20250826142453_remove_foreign_key_from_bulkrax_entries.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142454_add_status_to_exporters.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142455_add_invalid_record_to_importer_run.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142456_create_bulkrax_statuses.bulkrax.rb +19 -0
- data/.dassie/db/migrate/20250826142457_move_to_statuses.bulkrax.rb +31 -0
- data/.dassie/db/migrate/20250826142458_add_date_filter_and_status_to_bulkrax_exporters.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142459_add_workflow_status_to_bulkrax_exporter.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142460_remove_unused_last_error.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142461_increase_text_sizes.bulkrax.rb +13 -0
- data/.dassie/db/migrate/20250826142462_change_bulkrax_statuses_error_message_column_type_to_text.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142463_rename_children_counters_to_relationships.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142464_add_file_set_counters_to_importer_runs.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142465_add_import_attempts_to_entries.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142466_add_work_counters_to_importer_runs.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142467_create_bulkrax_pending_relationships.bulkrax.rb +14 -0
- data/.dassie/db/migrate/20250826142468_add_order_to_bulkrax_pending_relationships.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142469_add_include_thumbnails_to_bulkrax_exporters.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142470_add_generated_metadata_to_bulkrax_exporters.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142471_rename_bulkrax_importer_run_to_importer_run.bulkrax.rb +18 -0
- data/.dassie/db/migrate/20250826142472_add_indices_to_bulkrax.bulkrax.rb +26 -0
- data/.dassie/db/migrate/20250826142473_denormalize_status_message.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142474_update_identifier_index.bulkrax.rb +7 -0
- data/.dassie/db/migrate/20250826142475_add_index_to_metadata_bulkrax_identifier.bulkrax.rb +19 -0
- data/.dassie/db/migrate/20250826142476_add_file_name_to_uploaded_files.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142477_add_error_tracking_to_pending_relationships.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142478_add_last_imported_at_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142479_add_next_import_at_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.dassie/db/migrate/20250826142480_entry_error_denormalization.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20250826142481_faster_first_entry.bulkrax.rb +8 -0
- data/.dassie/db/migrate/20260430000001_create_hyrax_redirect_paths.hyrax.rb +13 -0
- data/.dassie/db/migrate/20260521003627_add_additional_redirect_info.hyrax.rb +32 -0
- data/.dassie/db/schema.rb +154 -1
- data/.dassie/package.json +1 -1
- data/.dassie/rspec_split_configuration.json +835 -0
- data/.dassie/solr/conf/solrconfig.xml +21 -5
- data/.github/{ISSUE_TEMPLATE.md → ISSUE_TEMPLATE/issue_template.md} +5 -0
- data/.github/workflows/lint-build-test.yml +5 -1
- data/.github/workflows/release-charts.yml +48 -0
- data/.gitignore +6 -0
- data/.koppie/.env +5 -1
- data/.koppie/Gemfile +3 -1
- data/.koppie/app/assets/images/bulkrax/removed.png +0 -0
- data/.koppie/app/assets/javascripts/application.js +2 -0
- data/.koppie/app/assets/stylesheets/application.css +1 -0
- data/.koppie/app/controllers/catalog_controller.rb +1 -1
- data/.koppie/app/forms/collection_resource_form.rb +5 -2
- data/.koppie/app/forms/file_set_form.rb +5 -0
- data/.koppie/app/forms/generic_work_form.rb +5 -3
- data/.koppie/app/forms/monograph_form.rb +5 -3
- data/.koppie/app/indexers/collection_resource_indexer.rb +5 -2
- data/.koppie/app/indexers/file_set_indexer.rb +7 -0
- data/.koppie/app/indexers/generic_work_indexer.rb +6 -3
- data/.koppie/app/indexers/monograph_indexer.rb +6 -2
- data/.koppie/app/models/ability.rb +8 -0
- data/.koppie/app/models/collection_resource.rb +4 -2
- data/.koppie/app/models/concerns/bulkrax/has_local_processing.rb +8 -0
- data/.koppie/app/models/generic_work.rb +5 -2
- data/.koppie/app/models/monograph.rb +5 -2
- data/.koppie/app/views/blacklight_dynamic_sitemap/sitemap/show.xml.builder +22 -0
- data/.koppie/bin/importer +142 -0
- data/.koppie/bin/web +4 -0
- data/.koppie/config/browse_everything_providers.yml +2 -0
- data/.koppie/config/bulkrax_api.yml +86 -0
- data/.koppie/config/initializers/bulkrax.rb +92 -0
- data/.koppie/config/initializers/clamav.rb +2 -0
- data/.koppie/config/initializers/hyrax.rb +11 -3
- data/.koppie/config/initializers/riiif.rb +4 -82
- data/.koppie/config/metadata_profiles/m3_profile.yaml +930 -0
- data/.koppie/config/routes.rb +7 -0
- data/.koppie/config/sidekiq.yml +2 -0
- data/.koppie/config/uv/uv.html +63 -81
- data/.koppie/db/migrate/20240606205215_create_hyrax_flexible_schemas.rb +9 -0
- data/.koppie/db/migrate/20240606205216_add_contexts_to_hyrax_flexible_schemas.rb +5 -0
- data/.koppie/db/migrate/20250826142438_create_bulkrax_importers.bulkrax.rb +19 -0
- data/.koppie/db/migrate/20250826142439_create_bulkrax_importer_runs.bulkrax.rb +17 -0
- data/.koppie/db/migrate/20250826142440_create_bulkrax_entries.bulkrax.rb +17 -0
- data/.koppie/db/migrate/20250826142441_add_status_to_entry.bulkrax.rb +10 -0
- data/.koppie/db/migrate/20250826142442_add_collections_to_importer_runs.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142443_change_collection_ids_on_entries.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142444_create_bulkrax_exporters.bulkrax.rb +20 -0
- data/.koppie/db/migrate/20250826142445_create_bulkrax_exporter_runs.bulkrax.rb +15 -0
- data/.koppie/db/migrate/20250826142446_change_importer_and_exporter_to_polymorphic.bulkrax.rb +19 -0
- data/.koppie/db/migrate/20250826142447_add_total_collection_records_to_importer_runs.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142448_add_children_to_importer_runs.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142449_change_total_records_to_total_work_entries.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142450_change_entry_last_error.bulkrax.rb +20 -0
- data/.koppie/db/migrate/20250826142451_add_validate_only_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142452_add_status_to_importers.bulkrax.rb +10 -0
- data/.koppie/db/migrate/20250826142453_remove_foreign_key_from_bulkrax_entries.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142454_add_status_to_exporters.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142455_add_invalid_record_to_importer_run.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142456_create_bulkrax_statuses.bulkrax.rb +19 -0
- data/.koppie/db/migrate/20250826142457_move_to_statuses.bulkrax.rb +31 -0
- data/.koppie/db/migrate/20250826142458_add_date_filter_and_status_to_bulkrax_exporters.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142459_add_workflow_status_to_bulkrax_exporter.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142460_remove_unused_last_error.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142461_increase_text_sizes.bulkrax.rb +13 -0
- data/.koppie/db/migrate/20250826142462_change_bulkrax_statuses_error_message_column_type_to_text.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142463_rename_children_counters_to_relationships.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142464_add_file_set_counters_to_importer_runs.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142465_add_import_attempts_to_entries.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142466_add_work_counters_to_importer_runs.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142467_create_bulkrax_pending_relationships.bulkrax.rb +14 -0
- data/.koppie/db/migrate/20250826142468_add_order_to_bulkrax_pending_relationships.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142469_add_include_thumbnails_to_bulkrax_exporters.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142470_add_generated_metadata_to_bulkrax_exporters.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142471_rename_bulkrax_importer_run_to_importer_run.bulkrax.rb +18 -0
- data/.koppie/db/migrate/20250826142472_add_indices_to_bulkrax.bulkrax.rb +26 -0
- data/.koppie/db/migrate/20250826142473_denormalize_status_message.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142474_update_identifier_index.bulkrax.rb +7 -0
- data/.koppie/db/migrate/20250826142475_add_index_to_metadata_bulkrax_identifier.bulkrax.rb +19 -0
- data/.koppie/db/migrate/20250826142476_add_file_name_to_uploaded_files.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142477_add_error_tracking_to_pending_relationships.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142478_add_last_imported_at_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142479_add_next_import_at_to_bulkrax_importers.bulkrax.rb +6 -0
- data/.koppie/db/migrate/20250826142480_entry_error_denormalization.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20250826142481_faster_first_entry.bulkrax.rb +8 -0
- data/.koppie/db/migrate/20260430000001_create_hyrax_redirect_paths.hyrax.rb +13 -0
- data/.koppie/db/migrate/20260521003627_add_additional_redirect_info.hyrax.rb +32 -0
- data/.koppie/db/schema.rb +154 -1
- data/.koppie/package.json +1 -1
- data/.koppie/rspec_split_configuration.json +835 -0
- data/.koppie/solr/conf/solrconfig.xml +0 -5
- data/.koppie/yarn.lock +5587 -752
- data/.rubocop.yml +1 -0
- data/CONTAINERS.md +2 -0
- data/Dockerfile +9 -22
- data/Gemfile +0 -1
- data/Gemfile.allinson +2 -0
- data/README.md +1 -2
- data/app/actors/hyrax/actors/file_actor.rb +2 -0
- data/app/actors/hyrax/actors/file_set_actor.rb +1 -1
- data/app/assets/javascripts/hyrax/app.js.erb +143 -10
- data/app/assets/javascripts/hyrax/collection_select.js +68 -0
- data/app/assets/javascripts/hyrax/copy_permalink_button.js +28 -0
- data/app/assets/javascripts/hyrax/redirects.js +45 -0
- data/app/assets/javascripts/hyrax/relationships/control.es6 +21 -1
- data/app/assets/javascripts/hyrax/select_work_type.es6 +7 -2
- data/app/assets/javascripts/hyrax.js +3 -1
- data/app/assets/stylesheets/hyrax/_file-show.scss +1 -0
- data/app/assets/stylesheets/hyrax/_viewer.scss +8 -0
- data/app/assets/stylesheets/hyrax/dashboard.scss +22 -1
- data/app/assets/stylesheets/hyrax/sidebar.scss +98 -3
- data/app/authorities/qa/authorities/collections.rb +9 -9
- data/app/controllers/concerns/hyrax/analytics_error_handling.rb +97 -0
- data/app/controllers/concerns/hyrax/collections_controller_behavior.rb +3 -1
- data/app/controllers/concerns/hyrax/ensure_migrated_behavior.rb +50 -0
- data/app/controllers/concerns/hyrax/flexible_catalog_behavior.rb +206 -0
- data/app/controllers/concerns/hyrax/flexible_schema_behavior.rb +17 -0
- data/app/controllers/concerns/hyrax/redirect_to_display_url.rb +54 -0
- data/app/controllers/concerns/hyrax/works_controller_behavior.rb +52 -10
- data/app/controllers/hyrax/admin/admin_sets_controller.rb +21 -13
- data/app/controllers/hyrax/admin/analytics/collection_reports_controller.rb +2 -0
- data/app/controllers/hyrax/admin/analytics/work_reports_controller.rb +1 -0
- data/app/controllers/hyrax/admin/metadata_profiles_controller.rb +66 -0
- data/app/controllers/hyrax/batch_uploads_controller.rb +2 -0
- data/app/controllers/hyrax/dashboard/collections_controller.rb +27 -6
- data/app/controllers/hyrax/dashboard/nest_collections_controller.rb +2 -1
- data/app/controllers/hyrax/dashboard_controller.rb +2 -1
- data/app/controllers/hyrax/file_sets_controller.rb +19 -1
- data/app/controllers/hyrax/homepage_controller.rb +7 -0
- data/app/controllers/hyrax/my/works_controller.rb +2 -21
- data/app/controllers/hyrax/permissions_controller.rb +4 -2
- data/app/controllers/hyrax/redirects_controller.rb +56 -0
- data/app/controllers/hyrax/single_use_links_viewer_controller.rb +2 -1
- data/app/controllers/hyrax/transcripts_controller.rb +31 -0
- data/app/controllers/hyrax/uploads_controller.rb +18 -9
- data/app/forms/concerns/hyrax/based_near_field_behavior.rb +77 -0
- data/app/forms/concerns/hyrax/flexible_form_behavior.rb +37 -0
- data/app/forms/concerns/hyrax/redirects_field_behavior.rb +95 -0
- data/app/forms/concerns/hyrax/transcripts_behavior.rb +40 -0
- data/app/forms/hyrax/forms/admin_set_form.rb +1 -1
- data/app/forms/hyrax/forms/administrative_set_form.rb +3 -0
- data/app/forms/hyrax/forms/batch_edit_form.rb +1 -3
- data/app/forms/hyrax/forms/batch_upload_form.rb +14 -0
- data/app/forms/hyrax/forms/file_set_edit_form.rb +1 -1
- data/app/forms/hyrax/forms/file_set_form.rb +6 -7
- data/app/forms/hyrax/forms/pcdm_collection_form.rb +17 -5
- data/app/forms/hyrax/forms/pcdm_object_form.rb +11 -3
- data/app/forms/hyrax/forms/resource_batch_edit_form.rb +8 -22
- data/app/forms/hyrax/forms/resource_form.rb +110 -10
- data/app/forms/hyrax/forms.rb +1 -0
- data/app/helpers/hyrax/attributes_helper.rb +109 -0
- data/app/helpers/hyrax/blacklight_override.rb +26 -0
- data/app/helpers/hyrax/collections_helper.rb +2 -0
- data/app/helpers/hyrax/file_set_form_helper.rb +24 -0
- data/app/helpers/hyrax/hyrax_helper_behavior.rb +51 -2
- data/app/helpers/hyrax/iiif_helper.rb +11 -1
- data/app/helpers/hyrax/permalink_helper.rb +37 -0
- data/app/helpers/hyrax/redirects_tab_helper.rb +29 -0
- data/app/helpers/hyrax/work_form_helper.rb +9 -5
- data/app/helpers/hyrax/works_helper.rb +14 -0
- data/app/indexers/concerns/hyrax/workflow_indexer.rb +30 -0
- data/app/indexers/hyrax/file_set_indexer.rb +1 -0
- data/app/indexers/hyrax/indexers/administrative_set_indexer.rb +2 -1
- data/app/indexers/hyrax/indexers/file_set_indexer.rb +6 -2
- data/app/indexers/hyrax/indexers/pcdm_collection_indexer.rb +11 -1
- data/app/indexers/hyrax/indexers/pcdm_object_indexer.rb +25 -4
- data/app/indexers/hyrax/indexers/redirects_indexer.rb +29 -0
- data/app/indexers/hyrax/indexers/resource_indexer.rb +4 -0
- data/app/indexers/hyrax/indexers.rb +2 -0
- data/app/inputs/controlled_vocabulary_input.rb +7 -1
- data/app/jobs/content_deposit_error_event_job.rb +14 -0
- data/app/jobs/create_work_job.rb +2 -0
- data/app/jobs/migrate_files_to_valkyrie_job.rb +7 -1
- data/app/models/batch_upload_item.rb +4 -0
- data/app/models/concerns/hyrax/ability/flexible_metadata_ability.rb +10 -0
- data/app/models/concerns/hyrax/ability.rb +3 -1
- data/app/models/concerns/hyrax/collection_behavior.rb +4 -0
- data/app/models/concerns/hyrax/file_set/transcripts.rb +16 -0
- data/app/models/concerns/hyrax/file_set_behavior.rb +9 -0
- data/app/models/concerns/hyrax/flexibility.rb +107 -0
- data/app/models/concerns/hyrax/redirects_normalization.rb +38 -0
- data/app/models/concerns/hyrax/solr_document/characterization.rb +1 -1
- data/app/models/concerns/hyrax/solr_document/metadata.rb +9 -0
- data/app/models/concerns/hyrax/solr_document/ordered_members.rb +4 -0
- data/app/models/concerns/hyrax/solr_document_behavior.rb +28 -6
- data/app/models/concerns/hyrax/suppressible.rb +1 -1
- data/app/models/concerns/hyrax/valkyrie_lazy_migration.rb +1 -1
- data/app/models/concerns/hyrax/with_embargoes_and_leases.rb +30 -0
- data/app/models/concerns/hyrax/work_behavior.rb +8 -0
- data/app/models/hyrax/administrative_set.rb +1 -1
- data/app/models/hyrax/change_set.rb +3 -1
- data/app/models/hyrax/embargo.rb +3 -1
- data/app/models/hyrax/file_set.rb +4 -2
- data/app/models/hyrax/flexible_schema.rb +219 -0
- data/app/models/hyrax/lease.rb +3 -1
- data/app/models/hyrax/pcdm_collection.rb +4 -1
- data/app/models/hyrax/redirect.rb +64 -0
- data/app/models/hyrax/redirect_path.rb +14 -0
- data/app/models/hyrax/resource.rb +22 -25
- data/app/models/hyrax/riiif/file.rb +43 -0
- data/app/models/hyrax/riiif/file_resolver.rb +65 -0
- data/app/models/hyrax/uploaded_file.rb +9 -0
- data/app/models/hyrax/virus_scanner.rb +16 -3
- data/app/models/hyrax/work.rb +4 -1
- data/app/models/job_io_wrapper.rb +12 -3
- data/app/models/user_mailbox.rb +3 -1
- data/app/presenters/hyrax/admin_set_presenter.rb +11 -0
- data/app/presenters/hyrax/annotates_content.rb +35 -0
- data/app/presenters/hyrax/collection_presenter.rb +5 -1
- data/app/presenters/hyrax/displays_content.rb +133 -0
- data/app/presenters/hyrax/displays_image.rb +11 -4
- data/app/presenters/hyrax/displays_transcripts.rb +59 -0
- data/app/presenters/hyrax/file_set_presenter.rb +8 -18
- data/app/presenters/hyrax/google_scholar_presenter.rb +39 -0
- data/app/presenters/hyrax/iiif_manifest_presenter.rb +22 -4
- data/app/presenters/hyrax/missing_method_behavior.rb +15 -0
- data/app/presenters/hyrax/pcdm_member_presenter_factory.rb +2 -4
- data/app/presenters/hyrax/work_show_presenter.rb +56 -14
- data/app/renderers/hyrax/renderers/attribute_renderer.rb +6 -2
- data/app/renderers/hyrax/renderers/license_attribute_renderer.rb +10 -10
- data/app/renderers/hyrax/renderers/redirects_label_attribute_renderer.rb +25 -0
- data/app/renderers/hyrax/renderers/rights_statement_attribute_renderer.rb +10 -11
- data/app/search_builders/hyrax/dashboard/nested_collections_search_builder.rb +1 -5
- data/app/search_builders/hyrax/filter_by_type.rb +1 -1
- data/app/services/hyrax/action/create_valkyrie_work.rb +3 -2
- data/app/services/hyrax/authority_rendering_helper.rb +28 -0
- data/app/services/hyrax/authority_service.rb +107 -0
- data/app/services/hyrax/callbacks.rb +2 -2
- data/app/services/hyrax/collections/nested_collection_query_service.rb +9 -3
- data/app/services/hyrax/collections_service.rb +17 -0
- data/app/services/hyrax/custom_queries/find_by_property_value.rb +89 -0
- data/app/services/hyrax/edit_permissions_service.rb +4 -4
- data/app/services/hyrax/file_set_type_service.rb +12 -4
- data/app/services/hyrax/flexible_schema_validator_service.rb +153 -0
- data/app/services/hyrax/flexible_schema_validators/class_validator.rb +123 -0
- data/app/services/hyrax/flexible_schema_validators/core_metadata_validator.rb +211 -0
- data/app/services/hyrax/flexible_schema_validators/existing_records_validator.rb +83 -0
- data/app/services/hyrax/flexible_schema_validators/redirects_validator.rb +116 -0
- data/app/services/hyrax/flexible_schema_validators/schema_validator.rb +34 -0
- data/app/services/hyrax/flexible_schema_validators/sort_properties_validator.rb +54 -0
- data/app/services/hyrax/license_service.rb +1 -1
- data/app/services/hyrax/listeners/metadata_index_listener.rb +11 -0
- data/app/services/hyrax/m3_profile_editor.rb +32 -0
- data/app/services/hyrax/m3_schema_loader.rb +119 -0
- data/app/services/hyrax/manifest_builder_service.rb +18 -24
- data/app/services/hyrax/permalink_path.rb +25 -0
- data/app/services/hyrax/qa_select_service.rb +9 -5
- data/app/services/hyrax/redirect_path_normalizer.rb +58 -0
- data/app/services/hyrax/redirects_lookup.rb +59 -0
- data/app/services/hyrax/resource_permissions_visibility_propagator.rb +54 -0
- data/app/services/hyrax/resource_types_service.rb +3 -20
- data/app/services/hyrax/rights_statement_service.rb +1 -1
- data/app/services/hyrax/schema_loader.rb +205 -0
- data/app/services/hyrax/search_service.rb +1 -1
- data/app/services/hyrax/simple_schema_loader.rb +28 -127
- data/app/services/hyrax/solr_service.rb +39 -2
- data/app/services/hyrax/tolerant_select_service.rb +5 -3
- data/app/services/hyrax/valkyrie_upload.rb +2 -2
- data/app/services/hyrax/visibility_propagator.rb +4 -1
- data/app/services/hyrax/work_uploads_handler.rb +17 -9
- data/app/services/hyrax/workflow/workflow_factory.rb +5 -4
- data/app/services/migrate_resource_service.rb +7 -1
- data/app/uploaders/hyrax/uploaded_file_uploader.rb +2 -2
- data/app/utils/hyrax/data_destroyers/collection_branding_destroyer.rb +1 -1
- data/app/utils/hyrax/required_data_seeder.rb +1 -0
- data/app/utils/hyrax/required_data_seeders/collection_type_seeder.rb +1 -1
- data/app/utils/hyrax/required_data_seeders/flexible_profile_seeder.rb +28 -0
- data/app/validators/hyrax/controlled_vocabulary_validator.rb +64 -0
- data/app/validators/hyrax/redirect_validator.rb +128 -0
- data/app/views/catalog/_thumbnail_list_default.html.erb +2 -2
- data/app/views/collections/edit_fields/_schema_version.html.erb +1 -0
- data/app/views/hyrax/admin/admin_sets/_form_metadata.html.erb +24 -2
- data/app/views/hyrax/admin/admin_sets/_show_document_list_row.html.erb +1 -1
- data/app/views/hyrax/admin/admin_sets/show.html.erb +1 -1
- data/app/views/hyrax/admin/analytics/_analytics_error.html.erb +42 -0
- data/app/views/hyrax/admin/analytics/collection_reports/index.html.erb +11 -9
- data/app/views/hyrax/admin/analytics/work_reports/index.html.erb +60 -57
- data/app/views/hyrax/admin/features/index.html.erb +1 -1
- data/app/views/hyrax/admin/metadata_profiles/_import_modal.html.erb +20 -0
- data/app/views/hyrax/admin/metadata_profiles/index.html.erb +54 -0
- data/app/views/hyrax/base/_attribute_rows.html.erb +4 -21
- data/app/views/hyrax/base/_citations.html.erb +1 -0
- data/app/views/hyrax/base/_currently_shared.html.erb +2 -1
- data/app/views/hyrax/base/_file_manager_thumbnail.html.erb +1 -1
- data/app/views/hyrax/base/_form_member_of_collections.html.erb +6 -6
- data/app/views/hyrax/base/_form_redirects.html.erb +125 -0
- data/app/views/hyrax/base/_form_share.html.erb +7 -2
- data/app/views/hyrax/base/_member.html.erb +1 -1
- data/app/views/hyrax/base/_social_media.html.erb +1 -1
- data/app/views/hyrax/base/iiif_viewers/_universal_viewer.html.erb +1 -1
- data/app/views/hyrax/base/show.html.erb +3 -0
- data/app/views/hyrax/collections/_default_group.html.erb +3 -0
- data/app/views/hyrax/collections/_list_collections.html.erb +3 -0
- data/app/views/hyrax/collections/_list_works.html.erb +1 -1
- data/app/views/hyrax/collections/_show_document_list_row.html.erb +1 -1
- data/app/views/hyrax/collections/show.html.erb +4 -0
- data/app/views/hyrax/dashboard/_sidebar.html.erb +4 -2
- data/app/views/hyrax/dashboard/collections/_button_for_update_collection.html.erb +2 -1
- data/app/views/hyrax/dashboard/collections/_default_group.html.erb +3 -0
- data/app/views/hyrax/dashboard/collections/_form.html.erb +17 -0
- data/app/views/hyrax/dashboard/collections/_form_for_select_collection.html.erb +7 -10
- data/app/views/hyrax/dashboard/collections/_list_collections.html.erb +3 -0
- data/app/views/hyrax/dashboard/collections/_list_works.html.erb +1 -1
- data/app/views/hyrax/dashboard/collections/_show_document_list_row.html.erb +1 -1
- data/app/views/hyrax/dashboard/profiles/_edit_primary.html.erb +1 -8
- data/app/views/hyrax/dashboard/profiles/_trophy_edit.html.erb +1 -1
- data/app/views/hyrax/dashboard/profiles/show.html.erb +5 -5
- data/app/views/hyrax/dashboard/sidebar/_metadata.html.erb +11 -0
- data/app/views/hyrax/dashboard/sidebar/_repository_content.html.erb +1 -0
- data/app/views/hyrax/dashboard/works/_default_group.html.erb +3 -0
- data/app/views/hyrax/dashboard/works/_list_works.html.erb +4 -2
- data/app/views/hyrax/file_sets/_form.html.erb +16 -3
- data/app/views/hyrax/file_sets/_metadata.html.erb +35 -0
- data/app/views/hyrax/file_sets/_valkyrie_form.html.erb +37 -0
- data/app/views/hyrax/file_sets/edit.html.erb +14 -8
- data/app/views/hyrax/file_sets/media_display/_audio.html.erb +4 -0
- data/app/views/hyrax/file_sets/media_display/_image.html.erb +2 -2
- data/app/views/hyrax/file_sets/media_display/_video.html.erb +4 -0
- data/app/views/hyrax/homepage/_explore_collections.html.erb +1 -1
- data/app/views/hyrax/homepage/_featured_fields.html.erb +1 -1
- data/app/views/hyrax/homepage/_recent_document.html.erb +1 -1
- data/app/views/hyrax/homepage/robots.text.erb +17 -0
- data/app/views/hyrax/my/collections/_default_group.html.erb +3 -0
- data/app/views/hyrax/my/collections/_list_collections.html.erb +3 -0
- data/app/views/hyrax/my/collections/_modal_add_subcollection.html.erb +2 -2
- data/app/views/hyrax/my/collections/_modal_add_to_collection.html.erb +2 -2
- data/app/views/hyrax/my/works/_default_group.html.erb +3 -0
- data/app/views/hyrax/my/works/_list_works.html.erb +5 -2
- data/app/views/hyrax/shared/_copy_permalink.html.erb +10 -0
- data/app/views/hyrax/users/_user_info.html.erb +1 -6
- data/app/views/layouts/_head_tag_content.html.erb +2 -0
- data/app/views/layouts/hyrax/dashboard.html.erb +2 -1
- data/app/views/records/edit_fields/_contexts.html.erb +1 -0
- data/app/views/records/edit_fields/_license.html.erb +17 -5
- data/app/views/records/edit_fields/_resource_type.html.erb +16 -2
- data/app/views/records/edit_fields/_rights_statement.html.erb +17 -5
- data/app/views/records/edit_fields/_schema_version.html.erb +1 -0
- data/app/views/records/edit_fields/_transcript_ids.html.erb +18 -0
- data/app/views/records/show_fields/_rights.html.erb +1 -1
- data/app/views/shared/_citations.html.erb +46 -31
- data/app/views/shared/_schema_version.html.erb +38 -0
- data/bin/dev-entrypoint.sh +14 -4
- data/chart/hyrax/Chart.yaml +4 -4
- data/chart/hyrax/templates/ingress.yaml +3 -0
- data/chart/hyrax/values.yaml +10 -8
- data/config/features.rb +27 -0
- data/config/initializers/blacklight_dynamic_sitemap.rb +43 -0
- data/config/initializers/deprecation_patch.rb +27 -0
- data/config/initializers/hydra_works.rb +3 -0
- data/config/initializers/i18n_extensions.rb +197 -0
- data/config/initializers/storage_adapter_initializer.rb +15 -9
- data/config/locales/hyrax.de.yml +172 -54
- data/config/locales/hyrax.en.yml +183 -66
- data/config/locales/hyrax.es.yml +174 -49
- data/config/locales/hyrax.fr.yml +169 -45
- data/config/locales/hyrax.it.yml +172 -48
- data/config/locales/hyrax.pt-BR.yml +172 -54
- data/config/locales/hyrax.zh.yml +145 -21
- data/config/metadata/basic_metadata.yaml +66 -0
- data/config/metadata/batch_edit_metadata.yaml +119 -0
- data/config/metadata/file_set_metadata.yaml +19 -0
- data/config/metadata/redirects.yaml +15 -0
- data/config/metadata_profiles/m3_json_schema.json +487 -0
- data/config/metadata_profiles/m3_profile.yaml +954 -0
- data/config/routes.rb +9 -0
- data/docker-compose-allinson.yml +176 -0
- data/docker-compose-dassie.yml +14 -6
- data/docker-compose-koppie.yml +18 -10
- data/docker-compose-sirenia.yml +20 -10
- data/documentation/copy_permalink.md +29 -0
- data/documentation/developing-your-hyrax-based-app.md +2 -2
- data/documentation/file-ingest-characterization.md +763 -0
- data/documentation/flexible_metadata.md +113 -0
- data/documentation/forms/field_behaviors.md +297 -0
- data/documentation/redirects.md +428 -0
- data/hyrax.gemspec +7 -2
- data/lib/freyja/metadata_adapter.rb +1 -1
- data/lib/freyja/persister.rb +25 -1
- data/lib/generators/hyrax/collection_resource/collection_resource_generator.rb +2 -2
- data/lib/generators/hyrax/collection_resource/templates/collection.rb.erb +5 -1
- data/lib/generators/hyrax/collection_resource/templates/collection_form.rb.erb +5 -1
- data/lib/generators/hyrax/collection_resource/templates/collection_indexer.rb.erb +6 -1
- data/lib/generators/hyrax/iiif_viewer/USAGE +22 -0
- data/lib/generators/hyrax/iiif_viewer/iiif_viewer_generator.rb +49 -0
- data/lib/generators/hyrax/iiif_viewer/templates/_clover.html.erb +7 -0
- data/lib/generators/hyrax/iiif_viewer/templates/clover/clover.css +3328 -0
- data/lib/generators/hyrax/iiif_viewer/templates/clover/clover.html +16 -0
- data/lib/generators/hyrax/iiif_viewer/templates/clover/clover.js +237 -0
- data/lib/generators/hyrax/install_generator.rb +25 -1
- data/lib/generators/hyrax/riiif_generator.rb +1 -1
- data/lib/generators/hyrax/templates/app/views/blacklight_dynamic_sitemap/sitemap/show.xml.builder +22 -0
- data/lib/generators/hyrax/templates/config/clamav.rb +2 -0
- data/lib/generators/hyrax/templates/config/initializers/riiif.rb +4 -80
- data/lib/generators/hyrax/templates/db/migrate/20240606205215_create_hyrax_flexible_schemas.rb.erb +9 -0
- data/lib/generators/hyrax/templates/db/migrate/20240606205216_add_contexts_to_hyrax_flexible_schemas.rb.erb +5 -0
- data/lib/generators/hyrax/templates/db/migrate/20260430000001_create_hyrax_redirect_paths.rb.erb +22 -0
- data/lib/generators/hyrax/templates/db/migrate/20260521003627_add_additional_redirect_info.rb.erb +39 -0
- data/lib/generators/hyrax/templates/package.json +1 -1
- data/lib/generators/hyrax/templates/uv.html +60 -82
- data/lib/generators/hyrax/work/templates/indexer.rb.erb +1 -1
- data/lib/generators/hyrax/work/templates/model.rb.erb +5 -1
- data/lib/generators/hyrax/work_resource/templates/form.rb.erb +5 -2
- data/lib/generators/hyrax/work_resource/templates/indexer.rb.erb +6 -2
- data/lib/generators/hyrax/work_resource/templates/work.rb.erb +5 -2
- data/lib/generators/hyrax/work_resource/work_resource_generator.rb +1 -0
- data/lib/hyrax/active_fedora_dummy_model.rb +6 -0
- data/lib/hyrax/configuration.rb +197 -3
- data/lib/hyrax/deprecation.rb +31 -0
- data/lib/hyrax/engine.rb +2 -0
- data/lib/hyrax/form_fields.rb +17 -5
- data/lib/hyrax/indexer.rb +31 -2
- data/lib/hyrax/resource_sync/resource_list_writer.rb +3 -0
- data/lib/hyrax/schema.rb +15 -4
- data/lib/hyrax/specs/shared_specs/factories/administrative_sets.rb +12 -0
- data/lib/hyrax/specs/shared_specs/factories/hyrax_embargo.rb +1 -1
- data/lib/hyrax/specs/shared_specs/factories/hyrax_file_set.rb +13 -0
- data/lib/hyrax/specs/shared_specs/factories/hyrax_lease.rb +5 -1
- data/lib/hyrax/specs/shared_specs/factories/hyrax_work.rb +14 -0
- data/lib/hyrax/specs/shared_specs/simple_work.rb +41 -0
- data/lib/hyrax/specs/shared_specs.rb +1 -0
- data/lib/hyrax/transactions/collection_create.rb +2 -1
- data/lib/hyrax/transactions/collection_destroy.rb +1 -0
- data/lib/hyrax/transactions/collection_update.rb +2 -1
- data/lib/hyrax/transactions/container.rb +28 -0
- data/lib/hyrax/transactions/steps/apply_permission_template_on_update.rb +65 -0
- data/lib/hyrax/transactions/steps/apply_workflow_on_admin_set_change.rb +97 -0
- data/lib/hyrax/transactions/steps/ensure_admin_set.rb +1 -1
- data/lib/hyrax/transactions/steps/remove_redirect_paths.rb +35 -0
- data/lib/hyrax/transactions/steps/save.rb +10 -0
- data/lib/hyrax/transactions/steps/set_default_admin_set.rb +1 -1
- data/lib/hyrax/transactions/steps/sync_redirect_paths.rb +141 -0
- data/lib/hyrax/transactions/work_create.rb +2 -1
- data/lib/hyrax/transactions/work_destroy.rb +1 -0
- data/lib/hyrax/transactions/work_update.rb +4 -1
- data/lib/hyrax/version.rb +1 -1
- data/lib/hyrax.rb +61 -0
- data/lib/tasks/m3_profile_cleanup.rake +35 -0
- data/template.rb +4 -1
- metadata +313 -19
- data/.dassie/public/robots.txt +0 -1
- data/.koppie/public/robots.txt +0 -1
- data/app/forms/concerns/hyrax/basic_metadata_form_fields_behavior.rb +0 -39
- data/app/views/catalog/_thumbnail_list_collection.html.erb +0 -4
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// Clover IIIF Viewer v.3.6.0
|
|
2
|
+
|
|
3
|
+
// Github: https://github.com/samvera-labs/clover-iiif
|
|
4
|
+
// Documentation: https://samvera-labs.github.io/clover-iiif
|
|
5
|
+
// This project is licensed under the MIT License (https://github.com/samvera-labs/clover-iiif/blob/main/LICENSE)
|
|
6
|
+
|
|
7
|
+
// This minified code comes from https://www.unpkg.com/@samvera/clover-iiif@3.6.0/dist/web-components/index.umd.js
|
|
8
|
+
// Some options can be changed in un={annotationOverlays:{backgroundColor:"#6666ff",borderColor:"#000099" ..},
|
|
9
|
+
// but extensive configuration/customization should probably be done with a proper JS framework.
|
|
10
|
+
// See https://samvera-labs.github.io/clover-iiif/docs/viewer#api-reference
|
|
11
|
+
|
|
12
|
+
(function(Si){typeof define=="function"&&define.amd?define(Si):Si()})(function(){"use strict";var m9=Object.defineProperty;var v9=(Si,Oe,Ss)=>Oe in Si?m9(Si,Oe,{enumerable:!0,configurable:!0,writable:!0,value:Ss}):Si[Oe]=Ss;var lt=(Si,Oe,Ss)=>v9(Si,typeof Oe!="symbol"?Oe+"":Oe,Ss);var KP,qP,Ch;var Si,Oe,Ss,xs,O0,M0,F0,N0,Lh,kh,Dh,B0,_a={},U0=[],hL=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Aa=Array.isArray;function Rn(i,e){for(var t in e)i[t]=e[t];return i}function Oh(i){i&&i.parentNode&&i.parentNode.removeChild(i)}function Ve(i,e,t){var n,r,s,o={};for(s in e)s=="key"?n=e[s]:s=="ref"?r=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?Si.call(arguments,2):t),typeof i=="function"&&i.defaultProps!=null)for(s in i.defaultProps)o[s]===void 0&&(o[s]=i.defaultProps[s]);return Ra(i,o,n,r,null)}function Ra(i,e,t,n,r){var s={type:i,props:e,key:t,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++Ss,__i:-1,__u:0};return r==null&&Oe.vnode!=null&&Oe.vnode(s),s}function $0(){return{current:null}}function Ee(i){return i.children}function ji(i,e){this.props=i,this.context=e}function co(i,e){if(e==null)return i.__?co(i.__,i.__i+1):null;for(var t;e<i.__k.length;e++)if((t=i.__k[e])!=null&&t.__e!=null)return t.__e;return typeof i.type=="function"?co(i):null}function H0(i){var e,t;if((i=i.__)!=null&&i.__c!=null){for(i.__e=i.__c.base=null,e=0;e<i.__k.length;e++)if((t=i.__k[e])!=null&&t.__e!=null){i.__e=i.__c.base=t.__e;break}return H0(i)}}function Mh(i){(!i.__d&&(i.__d=!0)&&xs.push(i)&&!fc.__r++||O0!=Oe.debounceRendering)&&((O0=Oe.debounceRendering)||M0)(fc)}function fc(){for(var i,e,t,n,r,s,o,a=1;xs.length;)xs.length>a&&xs.sort(F0),i=xs.shift(),a=xs.length,i.__d&&(t=void 0,n=void 0,r=(n=(e=i).__v).__e,s=[],o=[],e.__P&&((t=Rn({},n)).__v=n.__v+1,Oe.vnode&&Oe.vnode(t),Fh(e.__P,t,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,s,r??co(n),!!(32&n.__u),o),t.__v=n.__v,t.__.__k[t.__i]=t,j0(s,t,o),n.__e=n.__=null,t.__e!=r&&H0(t)));fc.__r=0}function z0(i,e,t,n,r,s,o,a,l,c,u){var d,h,f,p,g,m,v,y=n&&n.__k||U0,S=e.length;for(l=fL(t,e,y,l,S),d=0;d<S;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?_a:y[f.__i]||_a,f.__i=d,m=Fh(i,f,h,r,s,o,a,l,c,u),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Bh(h.ref,null,f),u.push(f.ref,f.__c||p,f)),g==null&&p!=null&&(g=p),(v=!!(4&f.__u))||h.__k===f.__k?l=V0(f,l,i,v):typeof f.type=="function"&&m!==void 0?l=m:p&&(l=p.nextSibling),f.__u&=-7);return t.__e=g,l}function fL(i,e,t,n,r){var s,o,a,l,c,u=t.length,d=u,h=0;for(i.__k=new Array(r),s=0;s<r;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(l=s+h,(o=i.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Ra(null,o,null,null,null):Aa(o)?Ra(Ee,{children:o},null,null,null):o.constructor==null&&o.__b>0?Ra(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=i,o.__b=i.__b+1,a=null,(c=o.__i=pL(o,t,l,d))!=-1&&(d--,(a=t[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(r>u?h--:r<u&&h++),typeof o.type!="function"&&(o.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,o.__u|=4))):i.__k[s]=null;if(d)for(s=0;s<u;s++)(a=t[s])!=null&&!(2&a.__u)&&(a.__e==n&&(n=co(a)),q0(a,a));return n}function V0(i,e,t,n){var r,s;if(typeof i.type=="function"){for(r=i.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=i,e=V0(r[s],e,t,n));return e}i.__e!=e&&(n&&(e&&i.type&&!e.parentNode&&(e=co(i)),t.insertBefore(i.__e,e||null)),e=i.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Jn(i,e){return e=e||[],i==null||typeof i=="boolean"||(Aa(i)?i.some(function(t){Jn(t,e)}):e.push(i)),e}function pL(i,e,t,n){var r,s,o,a=i.key,l=i.type,c=e[t],u=c!=null&&(2&c.__u)==0;if(c===null&&i.key==null||u&&a==c.key&&l==c.type)return t;if(n>(u?1:0)){for(r=t-1,s=t+1;r>=0||s<e.length;)if((c=e[o=r>=0?r--:s++])!=null&&!(2&c.__u)&&a==c.key&&l==c.type)return o}return-1}function G0(i,e,t){e[0]=="-"?i.setProperty(e,t??""):i[e]=t==null?"":typeof t!="number"||hL.test(e)?t:t+"px"}function pc(i,e,t,n,r){var s,o;e:if(e=="style")if(typeof t=="string")i.style.cssText=t;else{if(typeof n=="string"&&(i.style.cssText=n=""),n)for(e in n)t&&e in t||G0(i.style,e,"");if(t)for(e in t)n&&t[e]==n[e]||G0(i.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(N0,"$1")),o=e.toLowerCase(),e=o in i||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),i.l||(i.l={}),i.l[e+s]=t,t?n?t.u=n.u:(t.u=Lh,i.addEventListener(e,s?Dh:kh,s)):i.removeEventListener(e,s?Dh:kh,s);else{if(r=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in i)try{i[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?i.removeAttribute(e):i.setAttribute(e,e=="popover"&&t==1?"":t))}}function W0(i){return function(e){if(this.l){var t=this.l[e.type+i];if(e.t==null)e.t=Lh++;else if(e.t<t.u)return;return t(Oe.event?Oe.event(e):e)}}}function Fh(i,e,t,n,r,s,o,a,l,c){var u,d,h,f,p,g,m,v,y,S,x,E,C,b,I,D,P,k=e.type;if(e.constructor!=null)return null;128&t.__u&&(l=!!(32&t.__u),s=[a=e.__e=t.__e]),(u=Oe.__b)&&u(e);e:if(typeof k=="function")try{if(v=e.props,y="prototype"in k&&k.prototype.render,S=(u=k.contextType)&&n[u.__c],x=u?S?S.props.value:u.__:n,t.__c?m=(d=e.__c=t.__c).__=d.__E:(y?e.__c=d=new k(v,x):(e.__c=d=new ji(v,x),d.constructor=k,d.render=mL),S&&S.sub(d),d.props=v,d.state||(d.state={}),d.context=x,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),y&&d.__s==null&&(d.__s=d.state),y&&k.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Rn({},d.__s)),Rn(d.__s,k.getDerivedStateFromProps(v,d.__s))),f=d.props,p=d.state,d.__v=e,h)y&&k.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),y&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(y&&k.getDerivedStateFromProps==null&&v!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(v,x),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(v,d.__s,x)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(d.props=v,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(N){N&&(N.__=e)}),E=0;E<d._sb.length;E++)d.__h.push(d._sb[E]);d._sb=[],d.__h.length&&o.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(v,d.__s,x),y&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,p,g)})}if(d.context=x,d.props=v,d.__P=i,d.__e=!1,C=Oe.__r,b=0,y){for(d.state=d.__s,d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),I=0;I<d._sb.length;I++)d.__h.push(d._sb[I]);d._sb=[]}else do d.__d=!1,C&&C(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++b<25);d.state=d.__s,d.getChildContext!=null&&(n=Rn(Rn({},n),d.getChildContext())),y&&!h&&d.getSnapshotBeforeUpdate!=null&&(g=d.getSnapshotBeforeUpdate(f,p)),D=u,u!=null&&u.type===Ee&&u.key==null&&(D=K0(u.props.children)),a=z0(i,Aa(D)?D:[D],e,t,n,r,s,o,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),m&&(d.__E=d.__=null)}catch(N){if(e.__v=null,l||s!=null)if(N.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(P=s.length;P--;)Oh(s[P]);Nh(e)}else e.__e=t.__e,e.__k=t.__k,N.then||Nh(e);Oe.__e(N,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):a=e.__e=gL(t.__e,e,t,n,r,s,o,l,c);return(u=Oe.diffed)&&u(e),128&e.__u?void 0:a}function Nh(i){i&&i.__c&&(i.__c.__e=!0),i&&i.__k&&i.__k.forEach(Nh)}function j0(i,e,t){for(var n=0;n<t.length;n++)Bh(t[n],t[++n],t[++n]);Oe.__c&&Oe.__c(e,i),i.some(function(r){try{i=r.__h,r.__h=[],i.some(function(s){s.call(r)})}catch(s){Oe.__e(s,r.__v)}})}function K0(i){return typeof i!="object"||i==null||i.__b&&i.__b>0?i:Aa(i)?i.map(K0):Rn({},i)}function gL(i,e,t,n,r,s,o,a,l){var c,u,d,h,f,p,g,m=t.props,v=e.props,y=e.type;if(y=="svg"?r="http://www.w3.org/2000/svg":y=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((f=s[c])&&"setAttribute"in f==!!y&&(y?f.localName==y:f.nodeType==3)){i=f,s[c]=null;break}}if(i==null){if(y==null)return document.createTextNode(v);i=document.createElementNS(r,y,v.is&&v),a&&(Oe.__m&&Oe.__m(e,s),a=!1),s=null}if(y==null)m===v||a&&i.data==v||(i.data=v);else{if(s=s&&Si.call(i.childNodes),m=t.props||_a,!a&&s!=null)for(m={},c=0;c<i.attributes.length;c++)m[(f=i.attributes[c]).name]=f.value;for(c in m)if(f=m[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=f;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;pc(i,c,null,f,r)}}for(c in v)f=v[c],c=="children"?h=f:c=="dangerouslySetInnerHTML"?u=f:c=="value"?p=f:c=="checked"?g=f:a&&typeof f!="function"||m[c]===f||pc(i,c,f,m[c],r);if(u)a||d&&(u.__html==d.__html||u.__html==i.innerHTML)||(i.innerHTML=u.__html),e.__k=[];else if(d&&(i.innerHTML=""),z0(e.type=="template"?i.content:i,Aa(h)?h:[h],e,t,n,y=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,o,s?s[0]:t.__k&&co(t,0),a,l),s!=null)for(c=s.length;c--;)Oh(s[c]);a||(c="value",y=="progress"&&p==null?i.removeAttribute("value"):p!=null&&(p!==i[c]||y=="progress"&&!p||y=="option"&&p!=m[c])&&pc(i,c,p,m[c],r),c="checked",g!=null&&g!=i[c]&&pc(i,c,g,m[c],r))}return i}function Bh(i,e,t){try{if(typeof i=="function"){var n=typeof i.__u=="function";n&&i.__u(),n&&e==null||(i.__u=i(e))}else i.current=e}catch(r){Oe.__e(r,t)}}function q0(i,e,t){var n,r;if(Oe.unmount&&Oe.unmount(i),(n=i.ref)&&(n.current&&n.current!=i.__e||Bh(n,null,e)),(n=i.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){Oe.__e(s,e)}n.base=n.__P=null}if(n=i.__k)for(r=0;r<n.length;r++)n[r]&&q0(n[r],e,t||typeof i.type!="function");t||Oh(i.__e),i.__c=i.__=i.__e=void 0}function mL(i,e,t){return this.constructor(i,t)}function Pr(i,e,t){var n,r,s,o;e==document&&(e=document.documentElement),Oe.__&&Oe.__(i,e),r=(n=typeof t=="function")?null:t&&t.__k||e.__k,s=[],o=[],Fh(e,i=(!n&&t||e).__k=Ve(Ee,null,[i]),r||_a,_a,e.namespaceURI,!n&&t?[t]:r?null:e.firstChild?Si.call(e.childNodes):null,s,!n&&t?t:r?r.__e:e.firstChild,n,o),j0(s,i,o)}function Uh(i,e){Pr(i,e,Uh)}function $h(i,e,t){var n,r,s,o,a=Rn({},i.props);for(s in i.type&&i.type.defaultProps&&(o=i.type.defaultProps),e)s=="key"?n=e[s]:s=="ref"?r=e[s]:a[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(a.children=arguments.length>3?Si.call(arguments,2):t),Ra(i.type,a,n||i.key,r||i.ref,null)}function ln(i){function e(t){var n,r;return this.getChildContext||(n=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&n.forEach(function(o){o.__e=!0,Mh(o)})},this.sub=function(s){n.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){n&&n.delete(s),o&&o.call(s)}}),t.children}return e.__c="__cC"+B0++,e.__=i,e.Provider=e.__l=(e.Consumer=function(t,n){return t.children(n)}).contextType=e,e}Si=U0.slice,Oe={__e:function(i,e,t,n){for(var r,s,o;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(i)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(i,n||{}),o=r.__d),o)return r.__E=r}catch(a){i=a}throw i}},Ss=0,ji.prototype.setState=function(i,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Rn({},this.state),typeof i=="function"&&(i=i(Rn({},t),this.props)),i&&Rn(t,i),i!=null&&this.__v&&(e&&this._sb.push(e),Mh(this))},ji.prototype.forceUpdate=function(i){this.__v&&(this.__e=!0,i&&this.__h.push(i),Mh(this))},ji.prototype.render=Ee,xs=[],M0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,F0=function(i,e){return i.__v.__b-e.__v.__b},fc.__r=0,N0=/(PointerCapture)$|Capture$/i,Lh=0,kh=W0(!1),Dh=W0(!0),B0=0;var vL=0;function T(i,e,t,n,r,s){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?o=e[a]:l[a]=e[a];var c={type:i,props:l,key:t,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vL,__i:-1,__u:0,__source:r,__self:s};if(typeof i=="function"&&(o=i.defaultProps))for(a in o)l[a]===void 0&&(l[a]=o[a]);return Oe.vnode&&Oe.vnode(c),c}var er,ct,Hh,Y0,uo=0,X0=[],wt=Oe,Z0=wt.__b,Q0=wt.__r,J0=wt.diffed,ey=wt.__c,ty=wt.unmount,iy=wt.__;function Ts(i,e){wt.__h&&wt.__h(ct,i,uo||e),uo=0;var t=ct.__H||(ct.__H={__:[],__h:[]});return i>=t.__.length&&t.__.push({}),t.__[i]}function se(i){return uo=1,ho(ry,i)}function ho(i,e,t){var n=Ts(er++,2);if(n.t=i,!n.__c&&(n.__=[t?t(e):ry(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=ct,!ct.__f)){var r=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!s||s.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),s&&s.call(this,a,l,c)||d};ct.__f=!0;var s=ct.shouldComponentUpdate,o=ct.componentWillUpdate;ct.componentWillUpdate=function(a,l,c){if(this.__e){var u=s;s=void 0,r(a,l,c),s=u}o&&o.call(this,a,l,c)},ct.shouldComponentUpdate=r}return n.__N||n.__}function ne(i,e){var t=Ts(er++,3);!wt.__s&&jh(t.__H,e)&&(t.__=i,t.u=e,ct.__H.__h.push(t))}function Ki(i,e){var t=Ts(er++,4);!wt.__s&&jh(t.__H,e)&&(t.__=i,t.u=e,ct.__h.push(t))}function ge(i){return uo=5,Ct(function(){return{current:i}},[])}function zh(i,e,t){uo=6,Ki(function(){if(typeof i=="function"){var n=i(e());return function(){i(null),n&&typeof n=="function"&&n()}}if(i)return i.current=e(),function(){return i.current=null}},t==null?t:t.concat(i))}function Ct(i,e){var t=Ts(er++,7);return jh(t.__H,e)&&(t.__=i(),t.__H=e,t.__h=i),t.__}function Ce(i,e){return uo=8,Ct(function(){return i},e)}function Cn(i){var e=ct.context[i.__c],t=Ts(er++,9);return t.c=i,e?(t.__==null&&(t.__=!0,e.sub(ct)),e.props.value):i.__}function Vh(i,e){wt.useDebugValue&&wt.useDebugValue(e?e(i):i)}function yL(i){var e=Ts(er++,10),t=se();return e.__=i,ct.componentDidCatch||(ct.componentDidCatch=function(n,r){e.__&&e.__(n,r),t[1](n)}),[t[0],function(){t[1](void 0)}]}function Gh(){var i=Ts(er++,11);if(!i.__){for(var e=ct.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var t=e.__m||(e.__m=[0,0]);i.__="P"+t[0]+"-"+t[1]++}return i.__}function SL(){for(var i;i=X0.shift();)if(i.__P&&i.__H)try{i.__H.__h.forEach(gc),i.__H.__h.forEach(Wh),i.__H.__h=[]}catch(e){i.__H.__h=[],wt.__e(e,i.__v)}}wt.__b=function(i){ct=null,Z0&&Z0(i)},wt.__=function(i,e){i&&e.__k&&e.__k.__m&&(i.__m=e.__k.__m),iy&&iy(i,e)},wt.__r=function(i){Q0&&Q0(i),er=0;var e=(ct=i.__c).__H;e&&(Hh===ct?(e.__h=[],ct.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(gc),e.__h.forEach(Wh),e.__h=[],er=0)),Hh=ct},wt.diffed=function(i){J0&&J0(i);var e=i.__c;e&&e.__H&&(e.__H.__h.length&&(X0.push(e)!==1&&Y0===wt.requestAnimationFrame||((Y0=wt.requestAnimationFrame)||xL)(SL)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Hh=ct=null},wt.__c=function(i,e){e.some(function(t){try{t.__h.forEach(gc),t.__h=t.__h.filter(function(n){return!n.__||Wh(n)})}catch(n){e.some(function(r){r.__h&&(r.__h=[])}),e=[],wt.__e(n,t.__v)}}),ey&&ey(i,e)},wt.unmount=function(i){ty&&ty(i);var e,t=i.__c;t&&t.__H&&(t.__H.__.forEach(function(n){try{gc(n)}catch(r){e=r}}),t.__H=void 0,e&&wt.__e(e,t.__v))};var ny=typeof requestAnimationFrame=="function";function xL(i){var e,t=function(){clearTimeout(n),ny&&cancelAnimationFrame(e),setTimeout(i)},n=setTimeout(t,35);ny&&(e=requestAnimationFrame(t))}function gc(i){var e=ct,t=i.__c;typeof t=="function"&&(i.__c=void 0,t()),ct=e}function Wh(i){var e=ct;i.__c=i.__(),ct=e}function jh(i,e){return!i||i.length!==e.length||e.some(function(t,n){return t!==i[n]})}function ry(i,e){return typeof e=="function"?e(i):e}function sy(i,e){for(var t in e)i[t]=e[t];return i}function Kh(i,e){for(var t in i)if(t!=="__source"&&!(t in e))return!0;for(var n in e)if(n!=="__source"&&i[n]!==e[n])return!0;return!1}function qh(i,e){var t=e(),n=se({t:{__:t,u:e}}),r=n[0].t,s=n[1];return Ki(function(){r.__=t,r.u=e,Yh(r)&&s({t:r})},[i,t,e]),ne(function(){return Yh(r)&&s({t:r}),i(function(){Yh(r)&&s({t:r})})},[i]),t}function Yh(i){var e,t,n=i.u,r=i.__;try{var s=n();return!((e=r)===(t=s)&&(e!==0||1/e==1/t)||e!=e&&t!=t)}catch{return!0}}function Xh(i){i()}function Zh(i){return i}function Qh(){return[!1,Xh]}var Jh=Ki;function mc(i,e){this.props=i,this.context=e}function oy(i,e){function t(r){var s=this.props.ref,o=s==r.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,r)||!o:Kh(this.props,r)}function n(r){return this.shouldComponentUpdate=t,Ve(i,r)}return n.displayName="Memo("+(i.displayName||i.name)+")",n.prototype.isReactComponent=!0,n.__f=!0,n.type=i,n}(mc.prototype=new ji).isPureReactComponent=!0,mc.prototype.shouldComponentUpdate=function(i,e){return Kh(this.props,i)||Kh(this.state,e)};var ay=Oe.__b;Oe.__b=function(i){i.type&&i.type.__f&&i.ref&&(i.props.ref=i.ref,i.ref=null),ay&&ay(i)};var TL=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function me(i){function e(t){var n=sy({},t);return delete n.ref,i(n,t.ref||null)}return e.$$typeof=TL,e.render=i,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(i.displayName||i.name)+")",e}var ly=function(i,e){return i==null?null:Jn(Jn(i).map(e))},xi={map:ly,forEach:ly,count:function(i){return i?Jn(i).length:0},only:function(i){var e=Jn(i);if(e.length!==1)throw"Children.only";return e[0]},toArray:Jn},EL=Oe.__e;Oe.__e=function(i,e,t,n){if(i.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),r.__c(i,e)}EL(i,e,t,n)};var cy=Oe.unmount;function uy(i,e,t){return i&&(i.__c&&i.__c.__H&&(i.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),i.__c.__H=null),(i=sy({},i)).__c!=null&&(i.__c.__P===t&&(i.__c.__P=e),i.__c.__e=!0,i.__c=null),i.__k=i.__k&&i.__k.map(function(n){return uy(n,e,t)})),i}function dy(i,e,t){return i&&t&&(i.__v=null,i.__k=i.__k&&i.__k.map(function(n){return dy(n,e,t)}),i.__c&&i.__c.__P===e&&(i.__e&&t.appendChild(i.__e),i.__c.__e=!0,i.__c.__P=t)),i}function Ca(){this.__u=0,this.o=null,this.__b=null}function hy(i){var e=i.__.__c;return e&&e.__a&&e.__a(i)}function fy(i){var e,t,n;function r(s){if(e||(e=i()).then(function(o){t=o.default||o},function(o){n=o}),n)throw n;if(!t)throw e;return Ve(t,s)}return r.displayName="Lazy",r.__f=!0,r}function fo(){this.i=null,this.l=null}Oe.unmount=function(i){var e=i.__c;e&&e.__R&&e.__R(),e&&32&i.__u&&(i.type=null),cy&&cy(i)},(Ca.prototype=new ji).__c=function(i,e){var t=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(t);var r=hy(n.__v),s=!1,o=function(){s||(s=!0,t.__R=null,r?r(a):a())};t.__R=o;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=dy(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),i.then(o,o)},Ca.prototype.componentWillUnmount=function(){this.o=[]},Ca.prototype.render=function(i,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=uy(this.__b,t,n.__O=n.__P)}this.__b=null}var r=e.__a&&Ve(Ee,null,i.fallback);return r&&(r.__u&=-33),[Ve(Ee,null,e.__a?null:i.children),r]};var py=function(i,e,t){if(++t[1]===t[0]&&i.l.delete(e),i.props.revealOrder&&(i.props.revealOrder[0]!=="t"||!i.l.size))for(t=i.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;i.i=t=t[2]}};function wL(i){return this.getChildContext=function(){return i.context},i.children}function bL(i){var e=this,t=i.h;if(e.componentWillUnmount=function(){Pr(null,e.v),e.v=null,e.h=null},e.h&&e.h!==t&&e.componentWillUnmount(),!e.v){for(var n=e.__v;n!==null&&!n.__m&&n.__!==null;)n=n.__;e.h=t,e.v={nodeType:1,parentNode:t,childNodes:[],__k:{__m:n.__m},contains:function(){return!0},insertBefore:function(r,s){this.childNodes.push(r),e.h.insertBefore(r,s)},removeChild:function(r){this.childNodes.splice(this.childNodes.indexOf(r)>>>1,1),e.h.removeChild(r)}}}Pr(Ve(wL,{context:e.context},i.__v),e.v)}function gy(i,e){var t=Ve(bL,{__v:i,h:e});return t.containerInfo=e,t}(fo.prototype=new ji).__a=function(i){var e=this,t=hy(e.__v),n=e.l.get(i);return n[0]++,function(r){var s=function(){e.props.revealOrder?(n.push(r),py(e,i,n)):r()};t?t(s):s()}},fo.prototype.render=function(i){this.i=null,this.l=new Map;var e=Jn(i.children);i.revealOrder&&i.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return i.children},fo.prototype.componentDidUpdate=fo.prototype.componentDidMount=function(){var i=this;this.l.forEach(function(e,t){py(i,t,e)})};var my=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,_L=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,AL=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,RL=/[A-Z0-9]/g,CL=typeof document<"u",IL=function(i){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(i)};function vy(i,e,t){return e.__k==null&&(e.textContent=""),Pr(i,e),typeof t=="function"&&t(),i?i.__c:null}function yy(i,e,t){return Uh(i,e),typeof t=="function"&&t(),i?i.__c:null}ji.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(i){Object.defineProperty(ji.prototype,i,{configurable:!0,get:function(){return this["UNSAFE_"+i]},set:function(e){Object.defineProperty(this,i,{configurable:!0,writable:!0,value:e})}})});var Sy=Oe.event;function PL(){}function LL(){return this.cancelBubble}function kL(){return this.defaultPrevented}Oe.event=function(i){return Sy&&(i=Sy(i)),i.persist=PL,i.isPropagationStopped=LL,i.isDefaultPrevented=kL,i.nativeEvent=i};var ef,DL={enumerable:!1,configurable:!0,get:function(){return this.class}},xy=Oe.vnode;Oe.vnode=function(i){typeof i.type=="string"&&function(e){var t=e.props,n=e.type,r={},s=n.indexOf("-")===-1;for(var o in t){var a=t[o];if(!(o==="value"&&"defaultValue"in t&&a==null||CL&&o==="children"&&n==="noscript"||o==="class"||o==="className")){var l=o.toLowerCase();o==="defaultValue"&&"value"in t&&t.value==null?o="value":o==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?o="ondblclick":l!=="onchange"||n!=="input"&&n!=="textarea"||IL(t.type)?l==="onfocus"?o="onfocusin":l==="onblur"?o="onfocusout":AL.test(o)&&(o=l):l=o="oninput":s&&_L.test(o)?o=o.replace(RL,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&r[o=l]&&(o="oninputCapture"),r[o]=a}}n=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=Jn(t.children).forEach(function(c){c.props.selected=r.value.indexOf(c.props.value)!=-1})),n=="select"&&r.defaultValue!=null&&(r.value=Jn(t.children).forEach(function(c){c.props.selected=r.multiple?r.defaultValue.indexOf(c.props.value)!=-1:r.defaultValue==c.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",DL)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(i),i.$$typeof=my,xy&&xy(i)};var Ty=Oe.__r;Oe.__r=function(i){Ty&&Ty(i),ef=i.__c};var Ey=Oe.diffed;Oe.diffed=function(i){Ey&&Ey(i);var e=i.props,t=i.__e;t!=null&&i.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value),ef=null};var wy={ReactCurrentDispatcher:{current:{readContext:function(i){return ef.__n[i.__c].props.value},useCallback:Ce,useContext:Cn,useDebugValue:Vh,useDeferredValue:Zh,useEffect:ne,useId:Gh,useImperativeHandle:zh,useInsertionEffect:Jh,useLayoutEffect:Ki,useMemo:Ct,useReducer:ho,useRef:ge,useState:se,useSyncExternalStore:qh,useTransition:Qh}}},OL="18.3.1";function by(i){return Ve.bind(null,i)}function ki(i){return!!i&&i.$$typeof===my}function _y(i){return ki(i)&&i.type===Ee}function Ay(i){return!!i&&!!i.displayName&&(typeof i.displayName=="string"||i.displayName instanceof String)&&i.displayName.startsWith("Memo(")}function tr(i){return ki(i)?$h.apply(null,arguments):i}function Ry(i){return!!i.__k&&(Pr(null,i),!0)}function Cy(i){return i&&(i.base||i.nodeType===1&&i)||null}var Iy=function(i,e){return i(e)},Py=function(i,e){return i(e)},Ly=Ee,ky=ki,et={useState:se,useId:Gh,useReducer:ho,useEffect:ne,useLayoutEffect:Ki,useInsertionEffect:Jh,useTransition:Qh,useDeferredValue:Zh,useSyncExternalStore:qh,startTransition:Xh,useRef:ge,useImperativeHandle:zh,useMemo:Ct,useCallback:Ce,useContext:Cn,useDebugValue:Vh,version:"18.3.1",Children:xi,render:vy,hydrate:yy,unmountComponentAtNode:Ry,createPortal:gy,createElement:Ve,createContext:ln,createFactory:by,cloneElement:tr,createRef:$0,Fragment:Ee,isValidElement:ki,isElement:ky,isFragment:_y,isMemo:Ay,findDOMNode:Cy,Component:ji,PureComponent:mc,memo:oy,forwardRef:me,flushSync:Py,unstable_batchedUpdates:Iy,StrictMode:Ly,Suspense:Ca,SuspenseList:fo,lazy:fy,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:wy};const vc=Object.freeze(Object.defineProperty({__proto__:null,Children:xi,Component:ji,Fragment:Ee,PureComponent:mc,StrictMode:Ly,Suspense:Ca,SuspenseList:fo,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:wy,cloneElement:tr,createContext:ln,createElement:Ve,createFactory:by,createPortal:gy,createRef:$0,default:et,findDOMNode:Cy,flushSync:Py,forwardRef:me,hydrate:yy,isElement:ky,isFragment:_y,isMemo:Ay,isValidElement:ki,lazy:fy,memo:oy,render:vy,startTransition:Xh,unmountComponentAtNode:Ry,unstable_batchedUpdates:Iy,useCallback:Ce,useContext:Cn,useDebugValue:Vh,useDeferredValue:Zh,useEffect:ne,useErrorBoundary:yL,useId:Gh,useImperativeHandle:zh,useInsertionEffect:Jh,useLayoutEffect:Ki,useMemo:Ct,useReducer:ho,useRef:ge,useState:se,useSyncExternalStore:qh,useTransition:Qh,version:OL},Symbol.toStringTag,{value:"Module"}));var ML=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Dy(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function FL(i){if(i.__esModule)return i;var e=i.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(i).forEach(function(n){var r=Object.getOwnPropertyDescriptor(i,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return i[n]}})}),t}var Oy={exports:{}};(function(i){//! openseadragon 4.1.1
|
|
13
|
+
//! Built on 2024-04-01
|
|
14
|
+
//! Git commit: v4.1.1-0-f90d9814
|
|
15
|
+
//! http://openseadragon.github.io
|
|
16
|
+
//! License: http://openseadragon.github.io/license/
|
|
17
|
+
function e(t){return new e.Viewer(t)}(function(t){t.version={versionStr:"4.1.1",major:parseInt("4",10),minor:parseInt("1",10),revision:parseInt("1",10)};var n={"[object Boolean]":"boolean","[object Number]":"number","[object String]":"string","[object Function]":"function","[object AsyncFunction]":"function","[object Promise]":"promise","[object Array]":"array","[object Date]":"date","[object RegExp]":"regexp","[object Object]":"object"},r=Object.prototype.toString,s=Object.prototype.hasOwnProperty;t.isFunction=function(o){return t.type(o)==="function"},t.isArray=Array.isArray||function(o){return t.type(o)==="array"},t.isWindow=function(o){return o&&typeof o=="object"&&"setInterval"in o},t.type=function(o){return o==null?String(o):n[r.call(o)]||"object"},t.isPlainObject=function(o){if(!o||e.type(o)!=="object"||o.nodeType||t.isWindow(o)||o.constructor&&!s.call(o,"constructor")&&!s.call(o.constructor.prototype,"isPrototypeOf"))return!1;var a;for(var l in o)a=l;return a===void 0||s.call(o,a)},t.isEmptyObject=function(o){for(var a in o)return!1;return!0},t.freezeObject=function(o){return Object.freeze?t.freezeObject=Object.freeze:t.freezeObject=function(a){return a},t.freezeObject(o)},t.supportsCanvas=function(){var o=document.createElement("canvas");return!!(t.isFunction(o.getContext)&&o.getContext("2d"))}(),t.isCanvasTainted=function(o){var a=!1;try{o.getContext("2d").getImageData(0,0,1,1)}catch{a=!0}return a},t.supportsAddEventListener=function(){return!!(document.documentElement.addEventListener&&document.addEventListener)}(),t.supportsRemoveEventListener=function(){return!!(document.documentElement.removeEventListener&&document.removeEventListener)}(),t.supportsEventListenerOptions=function(){var o=0;if(t.supportsAddEventListener)try{var a={get capture(){return o++,!1},get once(){return o++,!1},get passive(){return o++,!1}};window.addEventListener("test",null,a),window.removeEventListener("test",null,a)}catch{o=0}return o>=3}(),t.getCurrentPixelDensityRatio=function(){if(t.supportsCanvas){var o=document.createElement("canvas").getContext("2d"),a=window.devicePixelRatio||1,l=o.webkitBackingStorePixelRatio||o.mozBackingStorePixelRatio||o.msBackingStorePixelRatio||o.oBackingStorePixelRatio||o.backingStorePixelRatio||1;return Math.max(a,1)/l}else return 1},t.pixelDensityRatio=t.getCurrentPixelDensityRatio()})(e),function(t){t.extend=function(){var l,c,u,d,h,f,p=arguments[0]||{},g=arguments.length,m=!1,v=1;for(typeof p=="boolean"&&(m=p,p=arguments[1]||{},v=2),typeof p!="object"&&!e.isFunction(p)&&(p={}),g===v&&(p=this,--v);v<g;v++)if(l=arguments[v],l!==null||l!==void 0)for(c in l){var y=Object.getOwnPropertyDescriptor(l,c);if(y!==void 0){if(y.get||y.set){Object.defineProperty(p,c,y);continue}d=y.value}else{t.console.warn('Could not copy inherited property "'+c+'".');continue}p!==d&&(m&&d&&(e.isPlainObject(d)||(h=e.isArray(d)))?(u=p[c],h?(h=!1,f=u&&e.isArray(u)?u:[]):f=u&&e.isPlainObject(u)?u:{},p[c]=e.extend(m,f,d)):d!==void 0&&(p[c]=d))}return p};var n=function(){if(typeof navigator!="object")return!1;var l=navigator.userAgent;return typeof l!="string"?!1:l.indexOf("iPhone")!==-1||l.indexOf("iPad")!==-1||l.indexOf("iPod")!==-1};t.extend(t,{DEFAULT_SETTINGS:{xmlPath:null,tileSources:null,tileHost:null,initialPage:0,crossOriginPolicy:!1,ajaxWithCredentials:!1,loadTilesWithAjax:!1,ajaxHeaders:{},splitHashDataForPost:!1,panHorizontal:!0,panVertical:!0,constrainDuringPan:!1,wrapHorizontal:!1,wrapVertical:!1,visibilityRatio:.5,minPixelRatio:.5,defaultZoomLevel:0,minZoomLevel:null,maxZoomLevel:null,homeFillsViewer:!1,clickTimeThreshold:300,clickDistThreshold:5,dblClickTimeThreshold:300,dblClickDistThreshold:20,springStiffness:6.5,animationTime:1.2,gestureSettingsMouse:{dragToPan:!0,scrollToZoom:!0,clickToZoom:!0,dblClickToZoom:!1,dblClickDragToZoom:!1,pinchToZoom:!1,zoomToRefPoint:!0,flickEnabled:!1,flickMinSpeed:120,flickMomentum:.25,pinchRotate:!1},gestureSettingsTouch:{dragToPan:!0,scrollToZoom:!1,clickToZoom:!1,dblClickToZoom:!0,dblClickDragToZoom:!0,pinchToZoom:!0,zoomToRefPoint:!0,flickEnabled:!0,flickMinSpeed:120,flickMomentum:.25,pinchRotate:!1},gestureSettingsPen:{dragToPan:!0,scrollToZoom:!1,clickToZoom:!0,dblClickToZoom:!1,dblClickDragToZoom:!1,pinchToZoom:!1,zoomToRefPoint:!0,flickEnabled:!1,flickMinSpeed:120,flickMomentum:.25,pinchRotate:!1},gestureSettingsUnknown:{dragToPan:!0,scrollToZoom:!1,clickToZoom:!1,dblClickToZoom:!0,dblClickDragToZoom:!1,pinchToZoom:!0,zoomToRefPoint:!0,flickEnabled:!0,flickMinSpeed:120,flickMomentum:.25,pinchRotate:!1},zoomPerClick:2,zoomPerScroll:1.2,zoomPerDblClickDrag:1.2,zoomPerSecond:1,blendTime:0,alwaysBlend:!1,autoHideControls:!0,immediateRender:!1,minZoomImageRatio:.9,maxZoomPixelRatio:1.1,smoothTileEdgesMinZoom:1.1,iOSDevice:n(),pixelsPerWheelLine:40,pixelsPerArrowPress:40,autoResize:!0,preserveImageSizeOnResize:!1,minScrollDeltaTime:50,rotationIncrement:90,showSequenceControl:!0,sequenceControlAnchor:null,preserveViewport:!1,preserveOverlays:!1,navPrevNextWrap:!1,showNavigationControl:!0,navigationControlAnchor:null,showZoomControl:!0,showHomeControl:!0,showFullPageControl:!0,showRotationControl:!1,showFlipControl:!1,controlsFadeDelay:2e3,controlsFadeLength:1500,mouseNavEnabled:!0,showNavigator:!1,navigatorElement:null,navigatorId:null,navigatorPosition:null,navigatorSizeRatio:.2,navigatorMaintainSizeRatio:!1,navigatorTop:null,navigatorLeft:null,navigatorHeight:null,navigatorWidth:null,navigatorAutoResize:!0,navigatorAutoFade:!0,navigatorRotate:!0,navigatorBackground:"#000",navigatorOpacity:.8,navigatorBorderColor:"#555",navigatorDisplayRegionColor:"#900",degrees:0,flipped:!1,opacity:1,preload:!1,compositeOperation:null,imageSmoothingEnabled:!0,placeholderFillStyle:null,subPixelRoundingForTransparency:null,showReferenceStrip:!1,referenceStripScroll:"horizontal",referenceStripElement:null,referenceStripHeight:null,referenceStripWidth:null,referenceStripPosition:"BOTTOM_LEFT",referenceStripSizeRatio:.2,collectionRows:3,collectionColumns:0,collectionLayout:"horizontal",collectionMode:!1,collectionTileSize:800,collectionTileMargin:80,imageLoaderLimit:0,maxImageCacheCount:200,timeout:3e4,useCanvas:!0,tileRetryMax:0,tileRetryDelay:2500,prefixUrl:"/images/",navImages:{zoomIn:{REST:"zoomin_rest.png",GROUP:"zoomin_grouphover.png",HOVER:"zoomin_hover.png",DOWN:"zoomin_pressed.png"},zoomOut:{REST:"zoomout_rest.png",GROUP:"zoomout_grouphover.png",HOVER:"zoomout_hover.png",DOWN:"zoomout_pressed.png"},home:{REST:"home_rest.png",GROUP:"home_grouphover.png",HOVER:"home_hover.png",DOWN:"home_pressed.png"},fullpage:{REST:"fullpage_rest.png",GROUP:"fullpage_grouphover.png",HOVER:"fullpage_hover.png",DOWN:"fullpage_pressed.png"},rotateleft:{REST:"rotateleft_rest.png",GROUP:"rotateleft_grouphover.png",HOVER:"rotateleft_hover.png",DOWN:"rotateleft_pressed.png"},rotateright:{REST:"rotateright_rest.png",GROUP:"rotateright_grouphover.png",HOVER:"rotateright_hover.png",DOWN:"rotateright_pressed.png"},flip:{REST:"flip_rest.png",GROUP:"flip_grouphover.png",HOVER:"flip_hover.png",DOWN:"flip_pressed.png"},previous:{REST:"previous_rest.png",GROUP:"previous_grouphover.png",HOVER:"previous_hover.png",DOWN:"previous_pressed.png"},next:{REST:"next_rest.png",GROUP:"next_grouphover.png",HOVER:"next_hover.png",DOWN:"next_pressed.png"}},debugMode:!1,debugGridColor:["#437AB2","#1B9E77","#D95F02","#7570B3","#E7298A","#66A61E","#E6AB02","#A6761D","#666666"],silenceMultiImageWarnings:!1},SIGNAL:"----seadragon----",delegate:function(l,c){return function(){var u=arguments;return u===void 0&&(u=[]),c.apply(l,u)}},BROWSERS:{UNKNOWN:0,IE:1,FIREFOX:2,SAFARI:3,CHROME:4,OPERA:5,EDGE:6,CHROMEEDGE:7},SUBPIXEL_ROUNDING_OCCURRENCES:{NEVER:0,ONLY_AT_REST:1,ALWAYS:2},_viewers:new Map,getViewer:function(l){return t._viewers.get(this.getElement(l))},getElement:function(l){return typeof l=="string"&&(l=document.getElementById(l)),l},getElementPosition:function(l){var c=new t.Point,u,d;for(l=t.getElement(l),u=t.getElementStyle(l).position==="fixed",d=a(l,u);d;)c.x+=l.offsetLeft,c.y+=l.offsetTop,u&&(c=c.plus(t.getPageScroll())),l=d,u=t.getElementStyle(l).position==="fixed",d=a(l,u);return c},getElementOffset:function(l){l=t.getElement(l);var c=l&&l.ownerDocument,u,d,h={top:0,left:0};return c?(u=c.documentElement,typeof l.getBoundingClientRect<"u"&&(h=l.getBoundingClientRect()),d=c===c.window?c:c.nodeType===9?c.defaultView||c.parentWindow:!1,new t.Point(h.left+(d.pageXOffset||u.scrollLeft)-(u.clientLeft||0),h.top+(d.pageYOffset||u.scrollTop)-(u.clientTop||0))):new t.Point},getElementSize:function(l){return l=t.getElement(l),new t.Point(l.clientWidth,l.clientHeight)},getElementStyle:document.documentElement.currentStyle?function(l){return l=t.getElement(l),l.currentStyle}:function(l){return l=t.getElement(l),window.getComputedStyle(l,"")},getCssPropertyWithVendorPrefix:function(l){var c={};return t.getCssPropertyWithVendorPrefix=function(u){if(c[u]!==void 0)return c[u];var d=document.createElement("div").style,h=null;if(d[u]!==void 0)h=u;else for(var f=["Webkit","Moz","MS","O","webkit","moz","ms","o"],p=t.capitalizeFirstLetter(u),g=0;g<f.length;g++){var m=f[g]+p;if(d[m]!==void 0){h=m;break}}return c[u]=h,h},t.getCssPropertyWithVendorPrefix(l)},capitalizeFirstLetter:function(l){return l.charAt(0).toUpperCase()+l.slice(1)},positiveModulo:function(l,c){var u=l%c;return u<0&&(u+=c),u},pointInElement:function(l,c){l=t.getElement(l);var u=t.getElementOffset(l),d=t.getElementSize(l);return c.x>=u.x&&c.x<u.x+d.x&&c.y<u.y+d.y&&c.y>=u.y},getMousePosition:function(l){if(typeof l.pageX=="number")t.getMousePosition=function(c){var u=new t.Point;return u.x=c.pageX,u.y=c.pageY,u};else if(typeof l.clientX=="number")t.getMousePosition=function(c){var u=new t.Point;return u.x=c.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,u.y=c.clientY+document.body.scrollTop+document.documentElement.scrollTop,u};else throw new Error("Unknown event mouse position, no known technique.");return t.getMousePosition(l)},getPageScroll:function(){var l=document.documentElement||{},c=document.body||{};if(typeof window.pageXOffset=="number")t.getPageScroll=function(){return new t.Point(window.pageXOffset,window.pageYOffset)};else if(c.scrollLeft||c.scrollTop)t.getPageScroll=function(){return new t.Point(document.body.scrollLeft,document.body.scrollTop)};else if(l.scrollLeft||l.scrollTop)t.getPageScroll=function(){return new t.Point(document.documentElement.scrollLeft,document.documentElement.scrollTop)};else return new t.Point(0,0);return t.getPageScroll()},setPageScroll:function(l){if(typeof window.scrollTo<"u")t.setPageScroll=function(d){window.scrollTo(d.x,d.y)};else{var c=t.getPageScroll();if(c.x===l.x&&c.y===l.y)return;document.body.scrollLeft=l.x,document.body.scrollTop=l.y;var u=t.getPageScroll();if(u.x!==c.x&&u.y!==c.y){t.setPageScroll=function(d){document.body.scrollLeft=d.x,document.body.scrollTop=d.y};return}if(document.documentElement.scrollLeft=l.x,document.documentElement.scrollTop=l.y,u=t.getPageScroll(),u.x!==c.x&&u.y!==c.y){t.setPageScroll=function(d){document.documentElement.scrollLeft=d.x,document.documentElement.scrollTop=d.y};return}t.setPageScroll=function(d){}}t.setPageScroll(l)},getWindowSize:function(){var l=document.documentElement||{},c=document.body||{};if(typeof window.innerWidth=="number")t.getWindowSize=function(){return new t.Point(window.innerWidth,window.innerHeight)};else if(l.clientWidth||l.clientHeight)t.getWindowSize=function(){return new t.Point(document.documentElement.clientWidth,document.documentElement.clientHeight)};else if(c.clientWidth||c.clientHeight)t.getWindowSize=function(){return new t.Point(document.body.clientWidth,document.body.clientHeight)};else throw new Error("Unknown window size, no known technique.");return t.getWindowSize()},makeCenteredNode:function(l){l=t.getElement(l);var c=[t.makeNeutralElement("div"),t.makeNeutralElement("div"),t.makeNeutralElement("div")];return t.extend(c[0].style,{display:"table",height:"100%",width:"100%"}),t.extend(c[1].style,{display:"table-row"}),t.extend(c[2].style,{display:"table-cell",verticalAlign:"middle",textAlign:"center"}),c[0].appendChild(c[1]),c[1].appendChild(c[2]),c[2].appendChild(l),c[0]},makeNeutralElement:function(l){var c=document.createElement(l),u=c.style;return u.background="transparent none",u.border="none",u.margin="0px",u.padding="0px",u.position="static",c},now:function(){return Date.now?t.now=Date.now:t.now=function(){return new Date().getTime()},t.now()},makeTransparentImage:function(l){var c=t.makeNeutralElement("img");return c.src=l,c},setElementOpacity:function(l,c,u){var d,h;l=t.getElement(l),u&&!t.Browser.alpha&&(c=Math.round(c)),t.Browser.opacity?l.style.opacity=c<1?c:"":c<1?(d=Math.round(100*c),h="alpha(opacity="+d+")",l.style.filter=h):l.style.filter=""},setElementTouchActionNone:function(l){l=t.getElement(l),typeof l.style.touchAction<"u"?l.style.touchAction="none":typeof l.style.msTouchAction<"u"&&(l.style.msTouchAction="none")},setElementPointerEvents:function(l,c){l=t.getElement(l),typeof l.style<"u"&&typeof l.style.pointerEvents<"u"&&(l.style.pointerEvents=c)},setElementPointerEventsNone:function(l){t.setElementPointerEvents(l,"none")},addClass:function(l,c){l=t.getElement(l),l.className?(" "+l.className+" ").indexOf(" "+c+" ")===-1&&(l.className+=" "+c):l.className=c},indexOf:function(l,c,u){return Array.prototype.indexOf?this.indexOf=function(d,h,f){return d.indexOf(h,f)}:this.indexOf=function(d,h,f){var p,g=f||0,m;if(!d)throw new TypeError;if(m=d.length,m===0||g>=m)return-1;for(g<0&&(g=m-Math.abs(g)),p=g;p<m;p++)if(d[p]===h)return p;return-1},this.indexOf(l,c,u)},removeClass:function(l,c){var u,d=[],h;for(l=t.getElement(l),u=l.className.split(/\s+/),h=0;h<u.length;h++)u[h]&&u[h]!==c&&d.push(u[h]);l.className=d.join(" ")},normalizeEventListenerOptions:function(l){var c;return typeof l<"u"?typeof l=="boolean"?c=t.supportsEventListenerOptions?{capture:l}:l:c=t.supportsEventListenerOptions?l:typeof l.capture<"u"?l.capture:!1:c=t.supportsEventListenerOptions?{capture:!1}:!1,c},addEvent:function(){if(t.supportsAddEventListener)return function(l,c,u,d){d=t.normalizeEventListenerOptions(d),l=t.getElement(l),l.addEventListener(c,u,d)};if(document.documentElement.attachEvent&&document.attachEvent)return function(l,c,u){l=t.getElement(l),l.attachEvent("on"+c,u)};throw new Error("No known event model.")}(),removeEvent:function(){if(t.supportsRemoveEventListener)return function(l,c,u,d){d=t.normalizeEventListenerOptions(d),l=t.getElement(l),l.removeEventListener(c,u,d)};if(document.documentElement.detachEvent&&document.detachEvent)return function(l,c,u){l=t.getElement(l),l.detachEvent("on"+c,u)};throw new Error("No known event model.")}(),cancelEvent:function(l){l.preventDefault()},eventIsCanceled:function(l){return l.defaultPrevented},stopEvent:function(l){l.stopPropagation()},createCallback:function(l,c){var u=[],d;for(d=2;d<arguments.length;d++)u.push(arguments[d]);return function(){var h=u.concat([]),f;for(f=0;f<arguments.length;f++)h.push(arguments[f]);return c.apply(l,h)}},getUrlParameter:function(l){var c=o[l];return c||null},getUrlProtocol:function(l){var c=l.match(/^([a-z]+:)\/\//i);return c===null?window.location.protocol:c[1].toLowerCase()},createAjaxRequest:function(l){var c;try{c=!!new ActiveXObject("Microsoft.XMLHTTP")}catch{c=!1}if(c)window.XMLHttpRequest?t.createAjaxRequest=function(u){return u?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest}:t.createAjaxRequest=function(){return new ActiveXObject("Microsoft.XMLHTTP")};else if(window.XMLHttpRequest)t.createAjaxRequest=function(){return new XMLHttpRequest};else throw new Error("Browser doesn't support XMLHttpRequest.");return t.createAjaxRequest(l)},makeAjaxRequest:function(l,c,u){var d,h,f,p;t.isPlainObject(l)&&(c=l.success,u=l.error,d=l.withCredentials,h=l.headers,f=l.responseType||null,p=l.postData||null,l=l.url);var g=t.getUrlProtocol(l),m=t.createAjaxRequest(g==="file:");if(!t.isFunction(c))throw new Error("makeAjaxRequest requires a success callback");m.onreadystatechange=function(){m.readyState===4&&(m.onreadystatechange=function(){},m.status>=200&&m.status<300||m.status===0&&g!=="http:"&&g!=="https:"?c(m):t.isFunction(u)?u(m):t.console.error("AJAX request returned %d: %s",m.status,l))};var v=p?"POST":"GET";try{if(m.open(v,l,!0),f&&(m.responseType=f),h)for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&h[y]&&m.setRequestHeader(y,h[y]);d&&(m.withCredentials=!0),m.send(p)}catch(S){t.console.error("%s while making AJAX request: %s",S.name,S.message),m.onreadystatechange=function(){},t.isFunction(u)&&u(m,S)}return m},jsonp:function(l){var c,u=l.url,d=document.head||document.getElementsByTagName("head")[0]||document.documentElement,h=l.callbackName||"openseadragon"+t.now(),f=window[h],p="$1"+h+"$2",g=l.param||"callback",m=l.callback;u=u.replace(/(=)\?(&|$)|\?\?/i,p),u+=(/\?/.test(u)?"&":"?")+g+"="+h,window[h]=function(v){if(f)window[h]=f;else try{delete window[h]}catch{}m&&t.isFunction(m)&&m(v)},c=document.createElement("script"),(l.async!==void 0||l.async!==!1)&&(c.async="async"),l.scriptCharset&&(c.charset=l.scriptCharset),c.src=u,c.onload=c.onreadystatechange=function(v,y){(y||!c.readyState||/loaded|complete/.test(c.readyState))&&(c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=void 0)},d.insertBefore(c,d.firstChild)},createFromDZI:function(){throw"OpenSeadragon.createFromDZI is deprecated, use Viewer.open."},parseXml:function(l){if(window.DOMParser)t.parseXml=function(c){var u=null,d;return d=new DOMParser,u=d.parseFromString(c,"text/xml"),u};else if(window.ActiveXObject)t.parseXml=function(c){var u=null;return u=new ActiveXObject("Microsoft.XMLDOM"),u.async=!1,u.loadXML(c),u};else throw new Error("Browser doesn't support XML DOM.");return t.parseXml(l)},parseJSON:function(l){return t.parseJSON=window.JSON.parse,t.parseJSON(l)},imageFormatSupported:function(l){return l=l||"",!!s[l.toLowerCase()]},setImageFormatsSupported:function(l){t.extend(s,l)}});var r=function(l){};t.console=window.console||{log:r,debug:r,info:r,warn:r,error:r,assert:r},t.Browser={vendor:t.BROWSERS.UNKNOWN,version:0,alpha:!0};var s={bmp:!1,jpeg:!0,jpg:!0,png:!0,tif:!1,wdp:!1},o={};(function(){var l=navigator.appVersion,c=navigator.userAgent,u;switch(navigator.appName){case"Microsoft Internet Explorer":window.attachEvent&&window.ActiveXObject&&(t.Browser.vendor=t.BROWSERS.IE,t.Browser.version=parseFloat(c.substring(c.indexOf("MSIE")+5,c.indexOf(";",c.indexOf("MSIE")))));break;case"Netscape":window.addEventListener&&(c.indexOf("Edge")>=0?(t.Browser.vendor=t.BROWSERS.EDGE,t.Browser.version=parseFloat(c.substring(c.indexOf("Edge")+5))):c.indexOf("Edg")>=0?(t.Browser.vendor=t.BROWSERS.CHROMEEDGE,t.Browser.version=parseFloat(c.substring(c.indexOf("Edg")+4))):c.indexOf("Firefox")>=0?(t.Browser.vendor=t.BROWSERS.FIREFOX,t.Browser.version=parseFloat(c.substring(c.indexOf("Firefox")+8))):c.indexOf("Safari")>=0?(t.Browser.vendor=c.indexOf("Chrome")>=0?t.BROWSERS.CHROME:t.BROWSERS.SAFARI,t.Browser.version=parseFloat(c.substring(c.substring(0,c.indexOf("Safari")).lastIndexOf("/")+1,c.indexOf("Safari")))):(u=new RegExp("Trident/.*rv:([0-9]{1,}[.0-9]{0,})"),u.exec(c)!==null&&(t.Browser.vendor=t.BROWSERS.IE,t.Browser.version=parseFloat(RegExp.$1))));break;case"Opera":t.Browser.vendor=t.BROWSERS.OPERA,t.Browser.version=parseFloat(l);break}var d=window.location.search.substring(1),h=d.split("&"),f,p,g;for(g=0;g<h.length;g++)if(f=h[g],p=f.indexOf("="),p>0){var m=f.substring(0,p),v=f.substring(p+1);try{o[m]=decodeURIComponent(v)}catch{t.console.error("Ignoring malformed URL parameter: %s=%s",m,v)}}t.Browser.alpha=!(t.Browser.vendor===t.BROWSERS.CHROME&&t.Browser.version<2),t.Browser.opacity=!0,t.Browser.vendor===t.BROWSERS.IE&&t.Browser.version<11&&t.console.error("Internet Explorer versions < 11 are not supported by OpenSeadragon")})(),function(l){var c=l.requestAnimationFrame||l.mozRequestAnimationFrame||l.webkitRequestAnimationFrame||l.msRequestAnimationFrame,u=l.cancelAnimationFrame||l.mozCancelAnimationFrame||l.webkitCancelAnimationFrame||l.msCancelAnimationFrame;if(c&&u)t.requestAnimationFrame=function(){return c.apply(l,arguments)},t.cancelAnimationFrame=function(){return u.apply(l,arguments)};else{var d=[],h=[],f=0,p;t.requestAnimationFrame=function(g){return d.push([++f,g]),p||(p=setInterval(function(){if(d.length){var m=t.now(),v=h;for(h=d,d=v;h.length;)h.shift()[1](m)}else clearInterval(p),p=void 0},1e3/50)),f},t.cancelAnimationFrame=function(g){var m,v;for(m=0,v=d.length;m<v;m+=1)if(d[m][0]===g){d.splice(m,1);return}for(m=0,v=h.length;m<v;m+=1)if(h[m][0]===g){h.splice(m,1);return}}}}(window);function a(l,c){return c&&l!==document.body?document.body:l.offsetParent}}(e),function(t,n){i.exports?i.exports=n():t.OpenSeadragon=n()}(ML,function(){return e}),function(t){var n={supportsFullScreen:!1,isFullScreen:function(){return!1},getFullScreenElement:function(){return null},requestFullScreen:function(){},exitFullScreen:function(){},cancelFullScreen:function(){},fullScreenEventName:"",fullScreenErrorEventName:""};document.exitFullscreen?(n.supportsFullScreen=!0,n.getFullScreenElement=function(){return document.fullscreenElement},n.requestFullScreen=function(r){return r.requestFullscreen()},n.exitFullScreen=function(){document.exitFullscreen()},n.fullScreenEventName="fullscreenchange",n.fullScreenErrorEventName="fullscreenerror"):document.msExitFullscreen?(n.supportsFullScreen=!0,n.getFullScreenElement=function(){return document.msFullscreenElement},n.requestFullScreen=function(r){return r.msRequestFullscreen()},n.exitFullScreen=function(){document.msExitFullscreen()},n.fullScreenEventName="MSFullscreenChange",n.fullScreenErrorEventName="MSFullscreenError"):document.webkitExitFullscreen?(n.supportsFullScreen=!0,n.getFullScreenElement=function(){return document.webkitFullscreenElement},n.requestFullScreen=function(r){return r.webkitRequestFullscreen()},n.exitFullScreen=function(){document.webkitExitFullscreen()},n.fullScreenEventName="webkitfullscreenchange",n.fullScreenErrorEventName="webkitfullscreenerror"):document.webkitCancelFullScreen?(n.supportsFullScreen=!0,n.getFullScreenElement=function(){return document.webkitCurrentFullScreenElement},n.requestFullScreen=function(r){return r.webkitRequestFullScreen()},n.exitFullScreen=function(){document.webkitCancelFullScreen()},n.fullScreenEventName="webkitfullscreenchange",n.fullScreenErrorEventName="webkitfullscreenerror"):document.mozCancelFullScreen&&(n.supportsFullScreen=!0,n.getFullScreenElement=function(){return document.mozFullScreenElement},n.requestFullScreen=function(r){return r.mozRequestFullScreen()},n.exitFullScreen=function(){document.mozCancelFullScreen()},n.fullScreenEventName="mozfullscreenchange",n.fullScreenErrorEventName="mozfullscreenerror"),n.isFullScreen=function(){return n.getFullScreenElement()!==null},n.cancelFullScreen=function(){t.console.error("cancelFullScreen is deprecated. Use exitFullScreen instead."),n.exitFullScreen()},t.extend(t,n)}(e),function(t){t.EventSource=function(){this.events={}},t.EventSource.prototype={addOnceHandler:function(n,r,s,o,a){var l=this;o=o||1;var c=0,u=function(d){return c++,c===o&&l.removeHandler(n,u),r(d)};this.addHandler(n,u,s,a)},addHandler:function(n,r,s,o){var a=this.events[n];if(a||(this.events[n]=a=[]),r&&t.isFunction(r)){var l=a.length,c={handler:r,userData:s||null,priority:o||0};for(a[l]=c;l>0&&a[l-1].priority<a[l].priority;)a[l]=a[l-1],a[l-1]=c,l--}},removeHandler:function(n,r){var s=this.events[n],o=[],a;if(s&&t.isArray(s)){for(a=0;a<s.length;a++)s[a].handler!==r&&o.push(s[a]);this.events[n]=o}},numberOfHandlers:function(n){var r=this.events[n];return r?r.length:0},removeAllHandlers:function(n){if(n)this.events[n]=[];else for(var r in this.events)this.events[r]=[]},getHandler:function(n){var r=this.events[n];return!r||!r.length?null:(r=r.length===1?[r[0]]:Array.apply(null,r),function(s,o){var a,l=r.length;for(a=0;a<l;a++)r[a]&&(o.eventSource=s,o.userData=r[a].userData,r[a].handler(o))})},raiseEvent:function(n,r){var s=this.getHandler(n);if(s)return s(this,r||{})}}}(e),function(t){var n={};t.MouseTracker=function(R){var A=arguments;t.isPlainObject(R)||(R={element:A[0],clickTimeThreshold:A[1],clickDistThreshold:A[2]}),this.hash=Math.random(),this.element=t.getElement(R.element),this.clickTimeThreshold=R.clickTimeThreshold||t.DEFAULT_SETTINGS.clickTimeThreshold,this.clickDistThreshold=R.clickDistThreshold||t.DEFAULT_SETTINGS.clickDistThreshold,this.dblClickTimeThreshold=R.dblClickTimeThreshold||t.DEFAULT_SETTINGS.dblClickTimeThreshold,this.dblClickDistThreshold=R.dblClickDistThreshold||t.DEFAULT_SETTINGS.dblClickDistThreshold,this.userData=R.userData||null,this.stopDelay=R.stopDelay||50,this.preProcessEventHandler=R.preProcessEventHandler||null,this.contextMenuHandler=R.contextMenuHandler||null,this.enterHandler=R.enterHandler||null,this.leaveHandler=R.leaveHandler||null,this.exitHandler=R.exitHandler||null,this.overHandler=R.overHandler||null,this.outHandler=R.outHandler||null,this.pressHandler=R.pressHandler||null,this.nonPrimaryPressHandler=R.nonPrimaryPressHandler||null,this.releaseHandler=R.releaseHandler||null,this.nonPrimaryReleaseHandler=R.nonPrimaryReleaseHandler||null,this.moveHandler=R.moveHandler||null,this.scrollHandler=R.scrollHandler||null,this.clickHandler=R.clickHandler||null,this.dblClickHandler=R.dblClickHandler||null,this.dragHandler=R.dragHandler||null,this.dragEndHandler=R.dragEndHandler||null,this.pinchHandler=R.pinchHandler||null,this.stopHandler=R.stopHandler||null,this.keyDownHandler=R.keyDownHandler||null,this.keyUpHandler=R.keyUpHandler||null,this.keyHandler=R.keyHandler||null,this.focusHandler=R.focusHandler||null,this.blurHandler=R.blurHandler||null;var L=this;n[this.hash]={click:function(M){S(L,M)},dblclick:function(M){x(L,M)},keydown:function(M){E(L,M)},keyup:function(M){C(L,M)},keypress:function(M){b(L,M)},focus:function(M){I(L,M)},blur:function(M){D(L,M)},contextmenu:function(M){P(L,M)},wheel:function(M){k(L,M)},mousewheel:function(M){N(L,M)},DOMMouseScroll:function(M){N(L,M)},MozMousePixelScroll:function(M){N(L,M)},losecapture:function(M){K(L,M)},mouseenter:function(M){Q(L,M)},mouseleave:function(M){le(L,M)},mouseover:function(M){re(L,M)},mouseout:function(M){ye(L,M)},mousedown:function(M){de(L,M)},mouseup:function(M){Pe(L,M)},mousemove:function(M){Fe(L,M)},touchstart:function(M){q(L,M)},touchend:function(M){H(L,M)},touchmove:function(M){X(L,M)},touchcancel:function(M){F(L,M)},gesturestart:function(M){U(L,M)},gesturechange:function(M){j(L,M)},gotpointercapture:function(M){V(L,M)},lostpointercapture:function(M){Z(L,M)},pointerenter:function(M){Q(L,M)},pointerleave:function(M){le(L,M)},pointerover:function(M){re(L,M)},pointerout:function(M){ye(L,M)},pointerdown:function(M){de(L,M)},pointerup:function(M){Pe(L,M)},pointermove:function(M){Fe(L,M)},pointercancel:function(M){it(L,M)},pointerupcaptured:function(M){qe(L,M)},pointermovecaptured:function(M){Ue(L,M)},tracking:!1,activePointersLists:[],lastClickPos:null,dblClickTimeOut:null,pinchGPoints:[],lastPinchDist:0,currentPinchDist:0,lastPinchCenter:null,currentPinchCenter:null,sentDragEvent:!1},this.hasGestureHandlers=!!(this.pressHandler||this.nonPrimaryPressHandler||this.releaseHandler||this.nonPrimaryReleaseHandler||this.clickHandler||this.dblClickHandler||this.dragHandler||this.dragEndHandler||this.pinchHandler),this.hasScrollHandler=!!this.scrollHandler,t.MouseTracker.havePointerEvents&&t.setElementPointerEvents(this.element,"auto"),this.exitHandler&&t.console.error("MouseTracker.exitHandler is deprecated. Use MouseTracker.leaveHandler instead."),R.startDisabled||this.setTracking(!0)},t.MouseTracker.prototype={destroy:function(){l(this),this.element=null,n[this.hash]=null,delete n[this.hash]},isTracking:function(){return n[this.hash].tracking},setTracking:function(R){return R?a(this):l(this),this},getActivePointersListByType:function(R){var A=n[this.hash],L,M=A.activePointersLists.length,Y;for(L=0;L<M;L++)if(A.activePointersLists[L].type===R)return A.activePointersLists[L];return Y=new t.MouseTracker.GesturePointList(R),A.activePointersLists.push(Y),Y},getActivePointerCount:function(){var R=n[this.hash],A,L=R.activePointersLists.length,M=0;for(A=0;A<L;A++)M+=R.activePointersLists[A].getLength();return M},preProcessEventHandler:function(){},contextMenuHandler:function(){},enterHandler:function(){},leaveHandler:function(){},exitHandler:function(){},overHandler:function(){},outHandler:function(){},pressHandler:function(){},nonPrimaryPressHandler:function(){},releaseHandler:function(){},nonPrimaryReleaseHandler:function(){},moveHandler:function(){},scrollHandler:function(){},clickHandler:function(){},dblClickHandler:function(){},dragHandler:function(){},dragEndHandler:function(){},pinchHandler:function(){},stopHandler:function(){},keyDownHandler:function(){},keyUpHandler:function(){},keyHandler:function(){},focusHandler:function(){},blurHandler:function(){}};var r=function(){try{return window.self!==window.top}catch{return!0}}();function s(R){try{return R.addEventListener&&R.removeEventListener}catch{return!1}}t.MouseTracker.gesturePointVelocityTracker=function(){var R=[],A=0,L=0,M=function(Ze,ke){return Ze.hash.toString()+ke.type+ke.id.toString()},Y=function(){var Ze,ke=R.length,vi,Et,ys=t.now(),Ih,kt,Cr;for(Ih=ys-L,L=ys,Ze=0;Ze<ke;Ze++)vi=R[Ze],Et=vi.gPoint,Et.direction=Math.atan2(Et.currentPos.y-vi.lastPos.y,Et.currentPos.x-vi.lastPos.x),kt=vi.lastPos.distanceTo(Et.currentPos),vi.lastPos=Et.currentPos,Cr=1e3*kt/(Ih+1),Et.speed=.75*Cr+.25*Et.speed},ee=function(Ze,ke){var vi=M(Ze,ke);R.push({guid:vi,gPoint:ke,lastPos:ke.currentPos}),R.length===1&&(L=t.now(),A=window.setInterval(Y,50))},be=function(Ze,ke){var vi=M(Ze,ke),Et,ys=R.length;for(Et=0;Et<ys;Et++)if(R[Et].guid===vi){R.splice(Et,1),ys--,ys===0&&window.clearInterval(A);break}};return{addPoint:ee,removePoint:be}}(),t.MouseTracker.captureElement=document,t.MouseTracker.wheelEventName=t.Browser.vendor===t.BROWSERS.IE&&t.Browser.version>8||"onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll",t.MouseTracker.subscribeEvents=["click","dblclick","keydown","keyup","keypress","focus","blur","contextmenu",t.MouseTracker.wheelEventName],t.MouseTracker.wheelEventName==="DOMMouseScroll"&&t.MouseTracker.subscribeEvents.push("MozMousePixelScroll"),window.PointerEvent?(t.MouseTracker.havePointerEvents=!0,t.MouseTracker.subscribeEvents.push("pointerenter","pointerleave","pointerover","pointerout","pointerdown","pointerup","pointermove","pointercancel"),t.MouseTracker.havePointerCapture=function(){var R=document.createElement("div");return t.isFunction(R.setPointerCapture)&&t.isFunction(R.releasePointerCapture)}(),t.MouseTracker.havePointerCapture&&t.MouseTracker.subscribeEvents.push("gotpointercapture","lostpointercapture")):(t.MouseTracker.havePointerEvents=!1,t.MouseTracker.subscribeEvents.push("mouseenter","mouseleave","mouseover","mouseout","mousedown","mouseup","mousemove"),t.MouseTracker.mousePointerId="legacy-mouse",t.MouseTracker.havePointerCapture=function(){var R=document.createElement("div");return t.isFunction(R.setCapture)&&t.isFunction(R.releaseCapture)}(),t.MouseTracker.havePointerCapture&&t.MouseTracker.subscribeEvents.push("losecapture"),"ontouchstart"in window&&t.MouseTracker.subscribeEvents.push("touchstart","touchend","touchmove","touchcancel"),"ongesturestart"in window&&t.MouseTracker.subscribeEvents.push("gesturestart","gesturechange")),t.MouseTracker.GesturePointList=function(R){this._gPoints=[],this.type=R,this.buttons=0,this.contacts=0,this.clicks=0,this.captureCount=0},t.MouseTracker.GesturePointList.prototype={getLength:function(){return this._gPoints.length},asArray:function(){return this._gPoints},add:function(R){return this._gPoints.push(R)},removeById:function(R){var A,L=this._gPoints.length;for(A=0;A<L;A++)if(this._gPoints[A].id===R){this._gPoints.splice(A,1);break}return this._gPoints.length},getByIndex:function(R){return R<this._gPoints.length?this._gPoints[R]:null},getById:function(R){var A,L=this._gPoints.length;for(A=0;A<L;A++)if(this._gPoints[A].id===R)return this._gPoints[A];return null},getPrimary:function(R){var A,L=this._gPoints.length;for(A=0;A<L;A++)if(this._gPoints[A].isPrimary)return this._gPoints[A];return null},addContact:function(){++this.contacts,this.contacts>1&&(this.type==="mouse"||this.type==="pen")&&(t.console.warn("GesturePointList.addContact() Implausible contacts value"),this.contacts=1)},removeContact:function(){--this.contacts,this.contacts<0&&(this.contacts=0)}};function o(R){var A=n[R.hash],L,M,Y,ee,be,Ze=A.activePointersLists.length;for(L=0;L<Ze;L++)if(Y=A.activePointersLists[L],Y.getLength()>0){for(be=[],ee=Y.asArray(),M=0;M<ee.length;M++)be.push(ee[M]);for(M=0;M<be.length;M++)De(R,Y,be[M])}for(L=0;L<Ze;L++)A.activePointersLists.pop();A.sentDragEvent=!1}function a(R){var A=n[R.hash],L,M;if(!A.tracking){for(M=0;M<t.MouseTracker.subscribeEvents.length;M++)L=t.MouseTracker.subscribeEvents[M],t.addEvent(R.element,L,A[L],L===t.MouseTracker.wheelEventName?{passive:!1,capture:!1}:!1);o(R),A.tracking=!0}}function l(R){var A=n[R.hash],L,M;if(A.tracking){for(M=0;M<t.MouseTracker.subscribeEvents.length;M++)L=t.MouseTracker.subscribeEvents[M],t.removeEvent(R.element,L,A[L],!1);o(R),A.tracking=!1}}function c(R,A){var L=n[R.hash];if(A==="pointerevent")return{upName:"pointerup",upHandler:L.pointerupcaptured,moveName:"pointermove",moveHandler:L.pointermovecaptured};if(A==="mouse")return{upName:"pointerup",upHandler:L.pointerupcaptured,moveName:"pointermove",moveHandler:L.pointermovecaptured};if(A==="touch")return{upName:"touchend",upHandler:L.touchendcaptured,moveName:"touchmove",moveHandler:L.touchmovecaptured};throw new Error("MouseTracker.getCaptureEventParams: Unknown pointer type.")}function u(R,A){var L;if(t.MouseTracker.havePointerCapture)if(t.MouseTracker.havePointerEvents)try{R.element.setPointerCapture(A.id)}catch{t.console.warn("setPointerCapture() called on invalid pointer ID");return}else R.element.setCapture(!0);else L=c(R,t.MouseTracker.havePointerEvents?"pointerevent":A.type),r&&s(window.top)&&t.addEvent(window.top,L.upName,L.upHandler,!0),t.addEvent(t.MouseTracker.captureElement,L.upName,L.upHandler,!0),t.addEvent(t.MouseTracker.captureElement,L.moveName,L.moveHandler,!0);z(R,A,!0)}function d(R,A){var L,M,Y;if(t.MouseTracker.havePointerCapture)if(t.MouseTracker.havePointerEvents){if(M=R.getActivePointersListByType(A.type),Y=M.getById(A.id),!Y||!Y.captured)return;try{R.element.releasePointerCapture(A.id)}catch{}}else R.element.releaseCapture();else L=c(R,t.MouseTracker.havePointerEvents?"pointerevent":A.type),r&&s(window.top)&&t.removeEvent(window.top,L.upName,L.upHandler,!0),t.removeEvent(t.MouseTracker.captureElement,L.moveName,L.moveHandler,!0),t.removeEvent(t.MouseTracker.captureElement,L.upName,L.upHandler,!0);z(R,A,!1)}function h(R){return t.MouseTracker.havePointerEvents?R.pointerId:t.MouseTracker.mousePointerId}function f(R){return t.MouseTracker.havePointerEvents?R.pointerType||(t.Browser.vendor===t.BROWSERS.IE?"mouse":""):"mouse"}function p(R){return t.MouseTracker.havePointerEvents?R.isPrimary:!0}function g(R){return t.getMousePosition(R)}function m(R,A){return v(g(R),A)}function v(R,A){var L=t.getElementOffset(A);return R.minus(L)}function y(R,A){return new t.Point((R.x+A.x)/2,(R.y+A.y)/2)}function S(R,A){var L={originalEvent:A,eventType:"click",pointerType:"mouse",isEmulated:!1};O(R,L),L.preventDefault&&!L.defaultPrevented&&t.cancelEvent(A),L.stopPropagation&&t.stopEvent(A)}function x(R,A){var L={originalEvent:A,eventType:"dblclick",pointerType:"mouse",isEmulated:!1};O(R,L),L.preventDefault&&!L.defaultPrevented&&t.cancelEvent(A),L.stopPropagation&&t.stopEvent(A)}function E(R,A){var L=null,M={originalEvent:A,eventType:"keydown",pointerType:"",isEmulated:!1};O(R,M),R.keyDownHandler&&!M.preventGesture&&!M.defaultPrevented&&(L={eventSource:R,keyCode:A.keyCode?A.keyCode:A.charCode,ctrl:A.ctrlKey,shift:A.shiftKey,alt:A.altKey,meta:A.metaKey,originalEvent:A,preventDefault:M.preventDefault||M.defaultPrevented,userData:R.userData},R.keyDownHandler(L)),(L&&L.preventDefault||M.preventDefault&&!M.defaultPrevented)&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function C(R,A){var L=null,M={originalEvent:A,eventType:"keyup",pointerType:"",isEmulated:!1};O(R,M),R.keyUpHandler&&!M.preventGesture&&!M.defaultPrevented&&(L={eventSource:R,keyCode:A.keyCode?A.keyCode:A.charCode,ctrl:A.ctrlKey,shift:A.shiftKey,alt:A.altKey,meta:A.metaKey,originalEvent:A,preventDefault:M.preventDefault||M.defaultPrevented,userData:R.userData},R.keyUpHandler(L)),(L&&L.preventDefault||M.preventDefault&&!M.defaultPrevented)&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function b(R,A){var L=null,M={originalEvent:A,eventType:"keypress",pointerType:"",isEmulated:!1};O(R,M),R.keyHandler&&!M.preventGesture&&!M.defaultPrevented&&(L={eventSource:R,keyCode:A.keyCode?A.keyCode:A.charCode,ctrl:A.ctrlKey,shift:A.shiftKey,alt:A.altKey,meta:A.metaKey,originalEvent:A,preventDefault:M.preventDefault||M.defaultPrevented,userData:R.userData},R.keyHandler(L)),(L&&L.preventDefault||M.preventDefault&&!M.defaultPrevented)&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function I(R,A){var L={originalEvent:A,eventType:"focus",pointerType:"",isEmulated:!1};O(R,L),R.focusHandler&&!L.preventGesture&&R.focusHandler({eventSource:R,originalEvent:A,userData:R.userData})}function D(R,A){var L={originalEvent:A,eventType:"blur",pointerType:"",isEmulated:!1};O(R,L),R.blurHandler&&!L.preventGesture&&R.blurHandler({eventSource:R,originalEvent:A,userData:R.userData})}function P(R,A){var L=null,M={originalEvent:A,eventType:"contextmenu",pointerType:"mouse",isEmulated:!1};O(R,M),R.contextMenuHandler&&!M.preventGesture&&!M.defaultPrevented&&(L={eventSource:R,position:v(g(A),R.element),originalEvent:M.originalEvent,preventDefault:M.preventDefault||M.defaultPrevented,userData:R.userData},R.contextMenuHandler(L)),(L&&L.preventDefault||M.preventDefault&&!M.defaultPrevented)&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function k(R,A){B(R,A,A)}function N(R,A){var L={target:A.target||A.srcElement,type:"wheel",shiftKey:A.shiftKey||!1,clientX:A.clientX,clientY:A.clientY,pageX:A.pageX?A.pageX:A.clientX,pageY:A.pageY?A.pageY:A.clientY,deltaMode:A.type==="MozMousePixelScroll"?0:1,deltaX:0,deltaZ:0};t.MouseTracker.wheelEventName==="mousewheel"?L.deltaY=-A.wheelDelta/t.DEFAULT_SETTINGS.pixelsPerWheelLine:L.deltaY=A.detail,B(R,L,A)}function B(R,A,L){var M=0,Y,ee=null;M=A.deltaY<0?1:-1,Y={originalEvent:A,eventType:"wheel",pointerType:"mouse",isEmulated:A!==L},O(R,Y),R.scrollHandler&&!Y.preventGesture&&!Y.defaultPrevented&&(ee={eventSource:R,pointerType:"mouse",position:m(A,R.element),scroll:M,shift:A.shiftKey,isTouchEvent:!1,originalEvent:L,preventDefault:Y.preventDefault||Y.defaultPrevented,userData:R.userData},R.scrollHandler(ee)),Y.stopPropagation&&t.stopEvent(L),(ee&&ee.preventDefault||Y.preventDefault&&!Y.defaultPrevented)&&t.cancelEvent(L)}function K(R,A){var L={id:t.MouseTracker.mousePointerId,type:"mouse"},M={originalEvent:A,eventType:"lostpointercapture",pointerType:"mouse",isEmulated:!1};O(R,M),A.target===R.element&&z(R,L,!1),M.stopPropagation&&t.stopEvent(A)}function q(R,A){var L,M,Y=A.changedTouches.length,ee,be=R.getActivePointersListByType("touch");L=t.now(),be.getLength()>A.touches.length-Y&&t.console.warn("Tracked touch contact count doesn't match event.touches.length");var Ze={originalEvent:A,eventType:"pointerdown",pointerType:"touch",isEmulated:!1};for(O(R,Ze),M=0;M<Y;M++)ee={id:A.changedTouches[M].identifier,type:"touch",isPrimary:be.getLength()===0,currentPos:g(A.changedTouches[M]),currentTime:L},ie(R,Ze,ee),$e(R,Ze,ee,0),z(R,ee,!0);Ze.preventDefault&&!Ze.defaultPrevented&&t.cancelEvent(A),Ze.stopPropagation&&t.stopEvent(A)}function H(R,A){var L,M,Y=A.changedTouches.length,ee;L=t.now();var be={originalEvent:A,eventType:"pointerup",pointerType:"touch",isEmulated:!1};for(O(R,be),M=0;M<Y;M++)ee={id:A.changedTouches[M].identifier,type:"touch",currentPos:g(A.changedTouches[M]),currentTime:L},ze(R,be,ee,0),z(R,ee,!1),te(R,be,ee);be.preventDefault&&!be.defaultPrevented&&t.cancelEvent(A),be.stopPropagation&&t.stopEvent(A)}function X(R,A){var L,M,Y=A.changedTouches.length,ee;L=t.now();var be={originalEvent:A,eventType:"pointermove",pointerType:"touch",isEmulated:!1};for(O(R,be),M=0;M<Y;M++)ee={id:A.changedTouches[M].identifier,type:"touch",currentPos:g(A.changedTouches[M]),currentTime:L},ce(R,be,ee);be.preventDefault&&!be.defaultPrevented&&t.cancelEvent(A),be.stopPropagation&&t.stopEvent(A)}function F(R,A){var L=A.changedTouches.length,M,Y,ee={originalEvent:A,eventType:"pointercancel",pointerType:"touch",isEmulated:!1};for(O(R,ee),M=0;M<L;M++)Y={id:A.changedTouches[M].identifier,type:"touch"},fe(R,ee,Y);ee.stopPropagation&&t.stopEvent(A)}function U(R,A){return t.eventIsCanceled(A)||A.preventDefault(),!1}function j(R,A){return t.eventIsCanceled(A)||A.preventDefault(),!1}function V(R,A){var L={originalEvent:A,eventType:"gotpointercapture",pointerType:f(A),isEmulated:!1};O(R,L),A.target===R.element&&z(R,{id:A.pointerId,type:f(A)},!0),L.stopPropagation&&t.stopEvent(A)}function Z(R,A){var L={originalEvent:A,eventType:"lostpointercapture",pointerType:f(A),isEmulated:!1};O(R,L),A.target===R.element&&z(R,{id:A.pointerId,type:f(A)},!1),L.stopPropagation&&t.stopEvent(A)}function Q(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M={originalEvent:A,eventType:"pointerenter",pointerType:L.type,isEmulated:!1};O(R,M),ie(R,M,L)}function le(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M={originalEvent:A,eventType:"pointerleave",pointerType:L.type,isEmulated:!1};O(R,M),te(R,M,L)}function re(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M={originalEvent:A,eventType:"pointerover",pointerType:L.type,isEmulated:!1};O(R,M),xe(R,M,L),M.preventDefault&&!M.defaultPrevented&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function ye(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M={originalEvent:A,eventType:"pointerout",pointerType:L.type,isEmulated:!1};O(R,M),he(R,M,L),M.preventDefault&&!M.defaultPrevented&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function de(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M=t.MouseTracker.havePointerEvents&&L.type==="touch"&&t.Browser.vendor!==t.BROWSERS.IE,Y={originalEvent:A,eventType:"pointerdown",pointerType:L.type,isEmulated:!1};O(R,Y),$e(R,Y,L,A.button),Y.preventDefault&&!Y.defaultPrevented&&t.cancelEvent(A),Y.stopPropagation&&t.stopEvent(A),Y.shouldCapture&&(M?z(R,L,!0):u(R,L))}function Pe(R,A){Le(R,A)}function qe(R,A){var L=R.getActivePointersListByType(f(A));L.getById(A.pointerId)&&Le(R,A),t.stopEvent(A)}function Le(R,A){var L;L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()};var M={originalEvent:A,eventType:"pointerup",pointerType:L.type,isEmulated:!1};O(R,M),ze(R,M,L,A.button),M.preventDefault&&!M.defaultPrevented&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A),M.shouldReleaseCapture&&(A.target===R.element?d(R,L):z(R,L,!1))}function Fe(R,A){Xe(R,A)}function Ue(R,A){var L=R.getActivePointersListByType(f(A));L.getById(A.pointerId)&&Xe(R,A),t.stopEvent(A)}function Xe(R,A){var L={id:h(A),type:f(A),isPrimary:p(A),currentPos:g(A),currentTime:t.now()},M={originalEvent:A,eventType:"pointermove",pointerType:L.type,isEmulated:!1};O(R,M),ce(R,M,L),M.preventDefault&&!M.defaultPrevented&&t.cancelEvent(A),M.stopPropagation&&t.stopEvent(A)}function it(R,A){var L={id:A.pointerId,type:f(A)},M={originalEvent:A,eventType:"pointercancel",pointerType:L.type,isEmulated:!1};O(R,M),fe(R,M,L),M.stopPropagation&&t.stopEvent(A)}function zt(R,A){return A.speed=0,A.direction=0,A.contactPos=A.currentPos,A.contactTime=A.currentTime,A.lastPos=A.currentPos,A.lastTime=A.currentTime,R.add(A)}function De(R,A,L){var M,Y=A.getById(L.id);return Y?(Y.captured&&(t.console.warn("stopTrackingPointer() called on captured pointer"),d(R,Y)),A.removeContact(),M=A.removeById(L.id)):M=A.getLength(),M}function w(R,A){switch(A.eventType){case"pointermove":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!1,A.preventGesture=!R.hasGestureHandlers,A.stopPropagation=!1;break;case"pointerover":case"pointerout":case"contextmenu":case"keydown":case"keyup":case"keypress":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!1,A.preventGesture=!1,A.stopPropagation=!1;break;case"pointerdown":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!1,A.preventGesture=!R.hasGestureHandlers,A.stopPropagation=!1;break;case"pointerup":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!1,A.preventGesture=!R.hasGestureHandlers,A.stopPropagation=!1;break;case"wheel":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!1,A.preventGesture=!R.hasScrollHandler,A.stopPropagation=!1;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":A.isStoppable=!0,A.isCancelable=!1,A.preventDefault=!1,A.preventGesture=!1,A.stopPropagation=!1;break;case"click":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!!R.clickHandler,A.preventGesture=!1,A.stopPropagation=!1;break;case"dblclick":A.isStoppable=!0,A.isCancelable=!0,A.preventDefault=!!R.dblClickHandler,A.preventGesture=!1,A.stopPropagation=!1;break;case"focus":case"blur":case"pointerenter":case"pointerleave":default:A.isStoppable=!1,A.isCancelable=!1,A.preventDefault=!1,A.preventGesture=!1,A.stopPropagation=!1;break}}function O(R,A){A.eventSource=R,A.eventPhase=A.originalEvent&&typeof A.originalEvent.eventPhase<"u"?A.originalEvent.eventPhase:0,A.defaultPrevented=t.eventIsCanceled(A.originalEvent),A.shouldCapture=!1,A.shouldReleaseCapture=!1,A.userData=R.userData,w(R,A),R.preProcessEventHandler&&R.preProcessEventHandler(A)}function z(R,A,L){var M=R.getActivePointersListByType(A.type),Y=M.getById(A.id);Y?L&&!Y.captured?(Y.captured=!0,M.captureCount++):!L&&Y.captured&&(Y.captured=!1,M.captureCount--,M.captureCount<0&&(M.captureCount=0,t.console.warn("updatePointerCaptured() - pointsList.captureCount went negative"))):t.console.warn("updatePointerCaptured() called on untracked pointer")}function ie(R,A,L){var M=R.getActivePointersListByType(L.type),Y;Y=M.getById(L.id),Y?(Y.insideElement=!0,Y.lastPos=Y.currentPos,Y.lastTime=Y.currentTime,Y.currentPos=L.currentPos,Y.currentTime=L.currentTime,L=Y):(L.captured=!1,L.insideElementPressed=!1,L.insideElement=!0,zt(M,L)),R.enterHandler&&R.enterHandler({eventSource:R,pointerType:L.type,position:v(L.currentPos,R.element),buttons:M.buttons,pointers:R.getActivePointerCount(),insideElementPressed:L.insideElementPressed,buttonDownAny:M.buttons!==0,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData})}function te(R,A,L){var M=R.getActivePointersListByType(L.type),Y,ee;Y=M.getById(L.id),Y?(Y.captured?(Y.insideElement=!1,Y.lastPos=Y.currentPos,Y.lastTime=Y.currentTime,Y.currentPos=L.currentPos,Y.currentTime=L.currentTime):De(R,M,Y),L=Y):(L.captured=!1,L.insideElementPressed=!1),(R.leaveHandler||R.exitHandler)&&(ee={eventSource:R,pointerType:L.type,position:L.currentPos&&v(L.currentPos,R.element),buttons:M.buttons,pointers:R.getActivePointerCount(),insideElementPressed:L.insideElementPressed,buttonDownAny:M.buttons!==0,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData},R.leaveHandler&&R.leaveHandler(ee),R.exitHandler&&R.exitHandler(ee))}function xe(R,A,L){var M,Y;M=R.getActivePointersListByType(L.type),Y=M.getById(L.id),Y?L=Y:(L.captured=!1,L.insideElementPressed=!1),R.overHandler&&R.overHandler({eventSource:R,pointerType:L.type,position:v(L.currentPos,R.element),buttons:M.buttons,pointers:R.getActivePointerCount(),insideElementPressed:L.insideElementPressed,buttonDownAny:M.buttons!==0,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData})}function he(R,A,L){var M,Y;M=R.getActivePointersListByType(L.type),Y=M.getById(L.id),Y?L=Y:(L.captured=!1,L.insideElementPressed=!1),R.outHandler&&R.outHandler({eventSource:R,pointerType:L.type,position:L.currentPos&&v(L.currentPos,R.element),buttons:M.buttons,pointers:R.getActivePointerCount(),insideElementPressed:L.insideElementPressed,buttonDownAny:M.buttons!==0,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData})}function $e(R,A,L,M){var Y=n[R.hash],ee=R.getActivePointersListByType(L.type),be;if(typeof A.originalEvent.buttons<"u"?ee.buttons=A.originalEvent.buttons:M===0?ee.buttons|=1:M===1?ee.buttons|=4:M===2?ee.buttons|=2:M===3?ee.buttons|=8:M===4?ee.buttons|=16:M===5&&(ee.buttons|=32),M!==0){A.shouldCapture=!1,A.shouldReleaseCapture=!1,R.nonPrimaryPressHandler&&!A.preventGesture&&!A.defaultPrevented&&(A.preventDefault=!0,R.nonPrimaryPressHandler({eventSource:R,pointerType:L.type,position:v(L.currentPos,R.element),button:M,buttons:ee.buttons,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData}));return}be=ee.getById(L.id),be?(be.insideElementPressed=!0,be.insideElement=!0,be.originalTarget=A.originalEvent.target,be.contactPos=L.currentPos,be.contactTime=L.currentTime,be.lastPos=be.currentPos,be.lastTime=be.currentTime,be.currentPos=L.currentPos,be.currentTime=L.currentTime,L=be):(L.captured=!1,L.insideElementPressed=!0,L.insideElement=!0,L.originalTarget=A.originalEvent.target,zt(ee,L)),ee.addContact(),!A.preventGesture&&!A.defaultPrevented?(A.shouldCapture=!0,A.shouldReleaseCapture=!1,A.preventDefault=!0,(R.dragHandler||R.dragEndHandler||R.pinchHandler)&&t.MouseTracker.gesturePointVelocityTracker.addPoint(R,L),ee.contacts===1?R.pressHandler&&!A.preventGesture&&R.pressHandler({eventSource:R,pointerType:L.type,position:v(L.contactPos,R.element),buttons:ee.buttons,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData}):ee.contacts===2&&R.pinchHandler&&L.type==="touch"&&(Y.pinchGPoints=ee.asArray(),Y.lastPinchDist=Y.currentPinchDist=Y.pinchGPoints[0].currentPos.distanceTo(Y.pinchGPoints[1].currentPos),Y.lastPinchCenter=Y.currentPinchCenter=y(Y.pinchGPoints[0].currentPos,Y.pinchGPoints[1].currentPos))):(A.shouldCapture=!1,A.shouldReleaseCapture=!1)}function ze(R,A,L,M){var Y=n[R.hash],ee=R.getActivePointersListByType(L.type),be,Ze,ke,vi=!1,Et;if(typeof A.originalEvent.buttons<"u"?ee.buttons=A.originalEvent.buttons:M===0?ee.buttons^=-2:M===1?ee.buttons^=-5:M===2?ee.buttons^=-3:M===3?ee.buttons^=-9:M===4?ee.buttons^=-17:M===5&&(ee.buttons^=-33),A.shouldCapture=!1,M!==0){A.shouldReleaseCapture=!1,R.nonPrimaryReleaseHandler&&!A.preventGesture&&!A.defaultPrevented&&(A.preventDefault=!0,R.nonPrimaryReleaseHandler({eventSource:R,pointerType:L.type,position:v(L.currentPos,R.element),button:M,buttons:ee.buttons,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData}));return}ke=ee.getById(L.id),ke?(ee.removeContact(),ke.captured&&(vi=!0),ke.lastPos=ke.currentPos,ke.lastTime=ke.currentTime,ke.currentPos=L.currentPos,ke.currentTime=L.currentTime,ke.insideElement||De(R,ee,ke),be=ke.currentPos,Ze=ke.currentTime):(L.captured=!1,L.insideElementPressed=!1,L.insideElement=!0,zt(ee,L),ke=L),!A.preventGesture&&!A.defaultPrevented&&(vi?(A.shouldReleaseCapture=!0,A.preventDefault=!0,(R.dragHandler||R.dragEndHandler||R.pinchHandler)&&t.MouseTracker.gesturePointVelocityTracker.removePoint(R,ke),ee.contacts===0?(R.releaseHandler&&be&&R.releaseHandler({eventSource:R,pointerType:ke.type,position:v(be,R.element),buttons:ee.buttons,insideElementPressed:ke.insideElementPressed,insideElementReleased:ke.insideElement,isTouchEvent:ke.type==="touch",originalEvent:A.originalEvent,userData:R.userData}),R.dragEndHandler&&Y.sentDragEvent&&R.dragEndHandler({eventSource:R,pointerType:ke.type,position:v(ke.currentPos,R.element),speed:ke.speed,direction:ke.direction,shift:A.originalEvent.shiftKey,isTouchEvent:ke.type==="touch",originalEvent:A.originalEvent,userData:R.userData}),Y.sentDragEvent=!1,(R.clickHandler||R.dblClickHandler)&&ke.insideElement&&(Et=Ze-ke.contactTime<=R.clickTimeThreshold&&ke.contactPos.distanceTo(be)<=R.clickDistThreshold,R.clickHandler&&R.clickHandler({eventSource:R,pointerType:ke.type,position:v(ke.currentPos,R.element),quick:Et,shift:A.originalEvent.shiftKey,isTouchEvent:ke.type==="touch",originalEvent:A.originalEvent,originalTarget:ke.originalTarget,userData:R.userData}),R.dblClickHandler&&Et&&(ee.clicks++,ee.clicks===1?(Y.lastClickPos=be,Y.dblClickTimeOut=setTimeout(function(){ee.clicks=0},R.dblClickTimeThreshold)):ee.clicks===2&&(clearTimeout(Y.dblClickTimeOut),ee.clicks=0,Y.lastClickPos.distanceTo(be)<=R.dblClickDistThreshold&&R.dblClickHandler({eventSource:R,pointerType:ke.type,position:v(ke.currentPos,R.element),shift:A.originalEvent.shiftKey,isTouchEvent:ke.type==="touch",originalEvent:A.originalEvent,userData:R.userData}),Y.lastClickPos=null)))):ee.contacts===2&&R.pinchHandler&&ke.type==="touch"&&(Y.pinchGPoints=ee.asArray(),Y.lastPinchDist=Y.currentPinchDist=Y.pinchGPoints[0].currentPos.distanceTo(Y.pinchGPoints[1].currentPos),Y.lastPinchCenter=Y.currentPinchCenter=y(Y.pinchGPoints[0].currentPos,Y.pinchGPoints[1].currentPos))):(A.shouldReleaseCapture=!1,R.releaseHandler&&be&&(R.releaseHandler({eventSource:R,pointerType:ke.type,position:v(be,R.element),buttons:ee.buttons,insideElementPressed:ke.insideElementPressed,insideElementReleased:ke.insideElement,isTouchEvent:ke.type==="touch",originalEvent:A.originalEvent,userData:R.userData}),A.preventDefault=!0)))}function ce(R,A,L){var M=n[R.hash],Y=R.getActivePointersListByType(L.type),ee,be,Ze;if(typeof A.originalEvent.buttons<"u"&&(Y.buttons=A.originalEvent.buttons),ee=Y.getById(L.id),ee)ee.lastPos=ee.currentPos,ee.lastTime=ee.currentTime,ee.currentPos=L.currentPos,ee.currentTime=L.currentTime;else return;A.shouldCapture=!1,A.shouldReleaseCapture=!1,R.stopHandler&&L.type==="mouse"&&(clearTimeout(R.stopTimeOut),R.stopTimeOut=setTimeout(function(){He(R,A.originalEvent,L.type)},R.stopDelay)),Y.contacts===0?R.moveHandler&&R.moveHandler({eventSource:R,pointerType:L.type,position:v(L.currentPos,R.element),buttons:Y.buttons,isTouchEvent:L.type==="touch",originalEvent:A.originalEvent,userData:R.userData}):Y.contacts===1?(R.moveHandler&&(ee=Y.asArray()[0],R.moveHandler({eventSource:R,pointerType:ee.type,position:v(ee.currentPos,R.element),buttons:Y.buttons,isTouchEvent:ee.type==="touch",originalEvent:A.originalEvent,userData:R.userData})),R.dragHandler&&!A.preventGesture&&!A.defaultPrevented&&(ee=Y.asArray()[0],Ze=ee.currentPos.minus(ee.lastPos),R.dragHandler({eventSource:R,pointerType:ee.type,position:v(ee.currentPos,R.element),buttons:Y.buttons,delta:Ze,speed:ee.speed,direction:ee.direction,shift:A.originalEvent.shiftKey,isTouchEvent:ee.type==="touch",originalEvent:A.originalEvent,userData:R.userData}),A.preventDefault=!0,M.sentDragEvent=!0)):Y.contacts===2&&(R.moveHandler&&(be=Y.asArray(),R.moveHandler({eventSource:R,pointerType:be[0].type,position:v(y(be[0].currentPos,be[1].currentPos),R.element),buttons:Y.buttons,isTouchEvent:be[0].type==="touch",originalEvent:A.originalEvent,userData:R.userData})),R.pinchHandler&&L.type==="touch"&&!A.preventGesture&&!A.defaultPrevented&&(Ze=M.pinchGPoints[0].currentPos.distanceTo(M.pinchGPoints[1].currentPos),Ze!==M.currentPinchDist&&(M.lastPinchDist=M.currentPinchDist,M.currentPinchDist=Ze,M.lastPinchCenter=M.currentPinchCenter,M.currentPinchCenter=y(M.pinchGPoints[0].currentPos,M.pinchGPoints[1].currentPos),R.pinchHandler({eventSource:R,pointerType:"touch",gesturePoints:M.pinchGPoints,lastCenter:v(M.lastPinchCenter,R.element),center:v(M.currentPinchCenter,R.element),lastDistance:M.lastPinchDist,distance:M.currentPinchDist,shift:A.originalEvent.shiftKey,originalEvent:A.originalEvent,userData:R.userData}),A.preventDefault=!0)))}function fe(R,A,L){var M=R.getActivePointersListByType(L.type),Y;Y=M.getById(L.id),Y&&De(R,M,Y)}function He(R,A,L){R.stopHandler&&R.stopHandler({eventSource:R,pointerType:L,position:m(A,R.element),buttons:R.getActivePointersListByType(L).buttons,isTouchEvent:L==="touch",originalEvent:A,userData:R.userData})}}(e),function(t){t.ControlAnchor={NONE:0,TOP_LEFT:1,TOP_RIGHT:2,BOTTOM_RIGHT:3,BOTTOM_LEFT:4,ABSOLUTE:5},t.Control=function(n,r,s){var o=n.parentNode;typeof r=="number"&&(t.console.error("Passing an anchor directly into the OpenSeadragon.Control constructor is deprecated; please use an options object instead. Support for this deprecated variant is scheduled for removal in December 2013"),r={anchor:r}),r.attachToViewer=typeof r.attachToViewer>"u"?!0:r.attachToViewer,this.autoFade=typeof r.autoFade>"u"?!0:r.autoFade,this.element=n,this.anchor=r.anchor,this.container=s,this.anchor===t.ControlAnchor.ABSOLUTE?(this.wrapper=t.makeNeutralElement("div"),this.wrapper.style.position="absolute",this.wrapper.style.top=typeof r.top=="number"?r.top+"px":r.top,this.wrapper.style.left=typeof r.left=="number"?r.left+"px":r.left,this.wrapper.style.height=typeof r.height=="number"?r.height+"px":r.height,this.wrapper.style.width=typeof r.width=="number"?r.width+"px":r.width,this.wrapper.style.margin="0px",this.wrapper.style.padding="0px",this.element.style.position="relative",this.element.style.top="0px",this.element.style.left="0px",this.element.style.height="100%",this.element.style.width="100%"):(this.wrapper=t.makeNeutralElement("div"),this.wrapper.style.display="inline-block",this.anchor===t.ControlAnchor.NONE&&(this.wrapper.style.width=this.wrapper.style.height="100%")),this.wrapper.appendChild(this.element),r.attachToViewer?this.anchor===t.ControlAnchor.TOP_RIGHT||this.anchor===t.ControlAnchor.BOTTOM_RIGHT?this.container.insertBefore(this.wrapper,this.container.firstChild):this.container.appendChild(this.wrapper):o.appendChild(this.wrapper)},t.Control.prototype={destroy:function(){this.wrapper.removeChild(this.element),this.anchor!==t.ControlAnchor.NONE&&this.container.removeChild(this.wrapper)},isVisible:function(){return this.wrapper.style.display!=="none"},setVisible:function(n){this.wrapper.style.display=n?this.anchor===t.ControlAnchor.ABSOLUTE?"block":"inline-block":"none"},setOpacity:function(n){this.element[t.SIGNAL]&&t.Browser.vendor===t.BROWSERS.IE?t.setElementOpacity(this.element,n,!0):t.setElementOpacity(this.wrapper,n,!0)}}}(e),function(t){t.ControlDock=function(r){var s=["topleft","topright","bottomright","bottomleft"],o,a;for(t.extend(!0,this,{id:"controldock-"+t.now()+"-"+Math.floor(Math.random()*1e6),container:t.makeNeutralElement("div"),controls:[]},r),this.container.onsubmit=function(){return!1},this.element&&(this.element=t.getElement(this.element),this.element.appendChild(this.container),this.element.style.position="relative",this.container.style.width="100%",this.container.style.height="100%"),a=0;a<s.length;a++)o=s[a],this.controls[o]=t.makeNeutralElement("div"),this.controls[o].style.position="absolute",o.match("left")&&(this.controls[o].style.left="0px"),o.match("right")&&(this.controls[o].style.right="0px"),o.match("top")&&(this.controls[o].style.top="0px"),o.match("bottom")&&(this.controls[o].style.bottom="0px");this.container.appendChild(this.controls.topleft),this.container.appendChild(this.controls.topright),this.container.appendChild(this.controls.bottomright),this.container.appendChild(this.controls.bottomleft)},t.ControlDock.prototype={addControl:function(r,s){r=t.getElement(r);var o=null;if(!(n(this,r)>=0)){switch(s.anchor){case t.ControlAnchor.TOP_RIGHT:o=this.controls.topright,r.style.position="relative",r.style.paddingRight="0px",r.style.paddingTop="0px";break;case t.ControlAnchor.BOTTOM_RIGHT:o=this.controls.bottomright,r.style.position="relative",r.style.paddingRight="0px",r.style.paddingBottom="0px";break;case t.ControlAnchor.BOTTOM_LEFT:o=this.controls.bottomleft,r.style.position="relative",r.style.paddingLeft="0px",r.style.paddingBottom="0px";break;case t.ControlAnchor.TOP_LEFT:o=this.controls.topleft,r.style.position="relative",r.style.paddingLeft="0px",r.style.paddingTop="0px";break;case t.ControlAnchor.ABSOLUTE:o=this.container,r.style.margin="0px",r.style.padding="0px";break;default:case t.ControlAnchor.NONE:o=this.container,r.style.margin="0px",r.style.padding="0px";break}this.controls.push(new t.Control(r,s,o)),r.style.display="inline-block"}},removeControl:function(r){r=t.getElement(r);var s=n(this,r);return s>=0&&(this.controls[s].destroy(),this.controls.splice(s,1)),this},clearControls:function(){for(;this.controls.length>0;)this.controls.pop().destroy();return this},areControlsEnabled:function(){var r;for(r=this.controls.length-1;r>=0;r--)if(this.controls[r].isVisible())return!0;return!1},setControlsEnabled:function(r){var s;for(s=this.controls.length-1;s>=0;s--)this.controls[s].setVisible(r);return this}};function n(r,s){var o=r.controls,a;for(a=o.length-1;a>=0;a--)if(o[a].element===s)return a;return-1}}(e),function(t){t.Placement=t.freezeObject({CENTER:0,TOP_LEFT:1,TOP:2,TOP_RIGHT:3,RIGHT:4,BOTTOM_RIGHT:5,BOTTOM:6,BOTTOM_LEFT:7,LEFT:8,properties:{0:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!1,isVerticallyCentered:!0,isBottom:!1},1:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!0,isVerticallyCentered:!1,isBottom:!1},2:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!0,isVerticallyCentered:!1,isBottom:!1},3:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!0,isVerticallyCentered:!1,isBottom:!1},4:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!1,isVerticallyCentered:!0,isBottom:!1},5:{isLeft:!1,isHorizontallyCentered:!1,isRight:!0,isTop:!1,isVerticallyCentered:!1,isBottom:!0},6:{isLeft:!1,isHorizontallyCentered:!0,isRight:!1,isTop:!1,isVerticallyCentered:!1,isBottom:!0},7:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!1,isVerticallyCentered:!1,isBottom:!0},8:{isLeft:!0,isHorizontallyCentered:!1,isRight:!1,isTop:!1,isVerticallyCentered:!0,isBottom:!1}}})}(e),function(t){var n={},r=1;t.Viewer=function(w){var O=arguments,z=this,ie;if(t.isPlainObject(w)||(w={id:O[0],xmlPath:O.length>1?O[1]:void 0,prefixUrl:O.length>2?O[2]:void 0,controls:O.length>3?O[3]:void 0,overlays:O.length>4?O[4]:void 0}),w.config&&(t.extend(!0,w,w.config),delete w.config),t.extend(!0,this,{id:w.id,hash:w.hash||r++,initialPage:0,element:null,container:null,canvas:null,overlays:[],overlaysContainer:null,previousBody:[],customControls:[],source:null,drawer:null,world:null,viewport:null,navigator:null,collectionViewport:null,collectionDrawer:null,navImages:null,buttonGroup:null,profiler:null},t.DEFAULT_SETTINGS,w),typeof this.hash>"u")throw new Error("A hash must be defined, either by specifying options.id or options.hash.");for(typeof n[this.hash]<"u"&&t.console.warn("Hash "+this.hash+" has already been used."),n[this.hash]={fsBoundsDelta:new t.Point(1,1),prevContainerSize:null,animating:!1,forceRedraw:!1,needsResize:!1,forceResize:!1,mouseInside:!1,group:null,zooming:!1,zoomFactor:null,lastZoomTime:null,fullPage:!1,onfullscreenchange:null,lastClickTime:null,draggingToZoom:!1},this._sequenceIndex=0,this._firstOpen=!0,this._updateRequestId=null,this._loadQueue=[],this.currentOverlays=[],this._updatePixelDensityRatioBind=null,this._lastScrollTime=t.now(),t.EventSource.call(this),this.addHandler("open-failed",function(te){var xe=t.getString("Errors.OpenFailed",te.eventSource,te.message);z._showMessage(xe)}),t.ControlDock.call(this,w),this.xmlPath&&(this.tileSources=[this.xmlPath]),this.element=this.element||document.getElementById(this.id),this.canvas=t.makeNeutralElement("div"),this.canvas.className="openseadragon-canvas",function(te){te.width="100%",te.height="100%",te.overflow="hidden",te.position="absolute",te.top="0px",te.left="0px"}(this.canvas.style),t.setElementTouchActionNone(this.canvas),w.tabIndex!==""&&(this.canvas.tabIndex=w.tabIndex===void 0?0:w.tabIndex),this.container.className="openseadragon-container",function(te){te.width="100%",te.height="100%",te.position="relative",te.overflow="hidden",te.left="0px",te.top="0px",te.textAlign="left"}(this.container.style),t.setElementTouchActionNone(this.container),this.container.insertBefore(this.canvas,this.container.firstChild),this.element.appendChild(this.container),this.bodyWidth=document.body.style.width,this.bodyHeight=document.body.style.height,this.bodyOverflow=document.body.style.overflow,this.docOverflow=document.documentElement.style.overflow,this.innerTracker=new t.MouseTracker({userData:"Viewer.innerTracker",element:this.canvas,startDisabled:!this.mouseNavEnabled,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,dblClickTimeThreshold:this.dblClickTimeThreshold,dblClickDistThreshold:this.dblClickDistThreshold,contextMenuHandler:t.delegate(this,m),keyDownHandler:t.delegate(this,v),keyHandler:t.delegate(this,y),clickHandler:t.delegate(this,S),dblClickHandler:t.delegate(this,x),dragHandler:t.delegate(this,E),dragEndHandler:t.delegate(this,C),enterHandler:t.delegate(this,b),leaveHandler:t.delegate(this,I),pressHandler:t.delegate(this,D),releaseHandler:t.delegate(this,P),nonPrimaryPressHandler:t.delegate(this,k),nonPrimaryReleaseHandler:t.delegate(this,N),scrollHandler:t.delegate(this,H),pinchHandler:t.delegate(this,B),focusHandler:t.delegate(this,K),blurHandler:t.delegate(this,q)}),this.outerTracker=new t.MouseTracker({userData:"Viewer.outerTracker",element:this.container,startDisabled:!this.mouseNavEnabled,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,dblClickTimeThreshold:this.dblClickTimeThreshold,dblClickDistThreshold:this.dblClickDistThreshold,enterHandler:t.delegate(this,X),leaveHandler:t.delegate(this,F)}),this.toolbar&&(this.toolbar=new t.ControlDock({element:this.toolbar})),this.bindStandardControls(),n[this.hash].prevContainerSize=s(this.container),window.ResizeObserver?(this._autoResizePolling=!1,this._resizeObserver=new ResizeObserver(function(){n[z.hash].needsResize=!0}),this._resizeObserver.observe(this.container,{})):this._autoResizePolling=!0,this.world=new t.World({viewer:this}),this.world.addHandler("add-item",function(te){z.source=z.world.getItemAt(0).source,n[z.hash].forceRedraw=!0,z._updateRequestId||(z._updateRequestId=c(z,U))}),this.world.addHandler("remove-item",function(te){z.world.getItemCount()?z.source=z.world.getItemAt(0).source:z.source=null,n[z.hash].forceRedraw=!0}),this.world.addHandler("metrics-change",function(te){z.viewport&&z.viewport._setContentBounds(z.world.getHomeBounds(),z.world.getContentFactor())}),this.world.addHandler("item-index-change",function(te){z.source=z.world.getItemAt(0).source}),this.viewport=new t.Viewport({containerSize:n[this.hash].prevContainerSize,springStiffness:this.springStiffness,animationTime:this.animationTime,minZoomImageRatio:this.minZoomImageRatio,maxZoomPixelRatio:this.maxZoomPixelRatio,visibilityRatio:this.visibilityRatio,wrapHorizontal:this.wrapHorizontal,wrapVertical:this.wrapVertical,defaultZoomLevel:this.defaultZoomLevel,minZoomLevel:this.minZoomLevel,maxZoomLevel:this.maxZoomLevel,viewer:this,degrees:this.degrees,flipped:this.flipped,navigatorRotate:this.navigatorRotate,homeFillsViewer:this.homeFillsViewer,margins:this.viewportMargins,silenceMultiImageWarnings:this.silenceMultiImageWarnings}),this.viewport._setContentBounds(this.world.getHomeBounds(),this.world.getContentFactor()),this.imageLoader=new t.ImageLoader({jobLimit:this.imageLoaderLimit,timeout:w.timeout,tileRetryMax:this.tileRetryMax,tileRetryDelay:this.tileRetryDelay}),this.tileCache=new t.TileCache({maxImageCacheCount:this.maxImageCacheCount}),this.drawer=new t.Drawer({viewer:this,viewport:this.viewport,element:this.canvas,debugGridColor:this.debugGridColor}),this.overlaysContainer=t.makeNeutralElement("div"),this.canvas.appendChild(this.overlaysContainer),this.drawer.canRotate()||(this.rotateLeft&&(ie=this.buttonGroup.buttons.indexOf(this.rotateLeft),this.buttonGroup.buttons.splice(ie,1),this.buttonGroup.element.removeChild(this.rotateLeft.element)),this.rotateRight&&(ie=this.buttonGroup.buttons.indexOf(this.rotateRight),this.buttonGroup.buttons.splice(ie,1),this.buttonGroup.element.removeChild(this.rotateRight.element))),this._addUpdatePixelDensityRatioEvent(),this.showNavigator&&(this.navigator=new t.Navigator({element:this.navigatorElement,id:this.navigatorId,position:this.navigatorPosition,sizeRatio:this.navigatorSizeRatio,maintainSizeRatio:this.navigatorMaintainSizeRatio,top:this.navigatorTop,left:this.navigatorLeft,width:this.navigatorWidth,height:this.navigatorHeight,autoResize:this.navigatorAutoResize,autoFade:this.navigatorAutoFade,prefixUrl:this.prefixUrl,viewer:this,navigatorRotate:this.navigatorRotate,background:this.navigatorBackground,opacity:this.navigatorOpacity,borderColor:this.navigatorBorderColor,displayRegionColor:this.navigatorDisplayRegionColor,crossOriginPolicy:this.crossOriginPolicy,animationTime:this.animationTime})),this.sequenceMode&&this.bindSequenceControls(),this.tileSources&&this.open(this.tileSources),ie=0;ie<this.customControls.length;ie++)this.addControl(this.customControls[ie].id,{anchor:this.customControls[ie].anchor});t.requestAnimationFrame(function(){d(z)}),this.imageSmoothingEnabled!==void 0&&!this.imageSmoothingEnabled&&this.drawer.setImageSmoothingEnabled(this.imageSmoothingEnabled),t._viewers.set(this.element,this)},t.extend(t.Viewer.prototype,t.EventSource.prototype,t.ControlDock.prototype,{isOpen:function(){return!!this.world.getItemCount()},openDzi:function(w){return t.console.error("[Viewer.openDzi] this function is deprecated; use Viewer.open() instead."),this.open(w)},openTileSource:function(w){return t.console.error("[Viewer.openTileSource] this function is deprecated; use Viewer.open() instead."),this.open(w)},get buttons(){return t.console.warn("Viewer.buttons is deprecated; Please use Viewer.buttonGroup"),this.buttonGroup},open:function(w,O){var z=this;if(this.close(),!w)return this;if(this.sequenceMode&&t.isArray(w))return this.referenceStrip&&(this.referenceStrip.destroy(),this.referenceStrip=null),typeof O<"u"&&!isNaN(O)&&(this.initialPage=O),this.tileSources=w,this._sequenceIndex=Math.max(0,Math.min(this.tileSources.length-1,this.initialPage)),this.tileSources.length&&(this.open(this.tileSources[this._sequenceIndex]),this.showReferenceStrip&&this.addReferenceStrip()),this._updateSequenceButtons(this._sequenceIndex),this;if(t.isArray(w)||(w=[w]),!w.length)return this;this._opening=!0;for(var ie=w.length,te=0,xe=0,he,$e=function(){if(te+xe===ie)if(te){(z._firstOpen||!z.preserveViewport)&&(z.viewport.goHome(!0),z.viewport.update()),z._firstOpen=!1;var fe=w[0];if(fe.tileSource&&(fe=fe.tileSource),z.overlays&&!z.preserveOverlays)for(var He=0;He<z.overlays.length;He++)z.currentOverlays[He]=a(z,z.overlays[He]);z._drawOverlays(),z._opening=!1,z.raiseEvent("open",{source:fe})}else z._opening=!1,z.raiseEvent("open-failed",he)},ze=function(fe){(!t.isPlainObject(fe)||!fe.tileSource)&&(fe={tileSource:fe}),fe.index!==void 0&&(t.console.error("[Viewer.open] setting indexes here is not supported; use addTiledImage instead"),delete fe.index),fe.collectionImmediately===void 0&&(fe.collectionImmediately=!0);var He=fe.success;fe.success=function(A){if(te++,fe.tileSource.overlays)for(var L=0;L<fe.tileSource.overlays.length;L++)z.addOverlay(fe.tileSource.overlays[L]);He&&He(A),$e()};var R=fe.error;fe.error=function(A){xe++,he||(he=A),R&&R(A),$e()},z.addTiledImage(fe)},ce=0;ce<w.length;ce++)ze(w[ce]);return this},close:function(){return n[this.hash]?(this._opening=!1,this.navigator&&this.navigator.close(),this.preserveOverlays||(this.clearOverlays(),this.overlaysContainer.innerHTML=""),n[this.hash].animating=!1,this.world.removeAll(),this.imageLoader.clear(),this.raiseEvent("close"),this):this},destroy:function(){if(n[this.hash]){if(this.raiseEvent("before-destroy"),this._removeUpdatePixelDensityRatioEvent(),this.close(),this.clearOverlays(),this.overlaysContainer.innerHTML="",this._resizeObserver&&this._resizeObserver.disconnect(),this.referenceStrip&&(this.referenceStrip.destroy(),this.referenceStrip=null),this._updateRequestId!==null&&(t.cancelAnimationFrame(this._updateRequestId),this._updateRequestId=null),this.drawer&&this.drawer.destroy(),this.navigator&&(this.navigator.destroy(),n[this.navigator.hash]=null,delete n[this.navigator.hash],this.navigator=null),this.buttonGroup)this.buttonGroup.destroy();else if(this.customButtons)for(;this.customButtons.length;)this.customButtons.pop().destroy();if(this.paging&&this.paging.destroy(),this.element)for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);this.container.onsubmit=null,this.clearControls(),this.innerTracker&&this.innerTracker.destroy(),this.outerTracker&&this.outerTracker.destroy(),n[this.hash]=null,delete n[this.hash],this.canvas=null,this.container=null,t._viewers.delete(this.element),this.element=null,this.raiseEvent("destroy"),this.removeAllHandlers()}},isMouseNavEnabled:function(){return this.innerTracker.isTracking()},setMouseNavEnabled:function(w){return this.innerTracker.setTracking(w),this.outerTracker.setTracking(w),this.raiseEvent("mouse-enabled",{enabled:w}),this},areControlsEnabled:function(){var w=this.controls.length,O;for(O=0;O<this.controls.length;O++)w=w&&this.controls[O].isVisible();return w},setControlsEnabled:function(w){return w?f(this):d(this),this.raiseEvent("controls-enabled",{enabled:w}),this},setDebugMode:function(w){for(var O=0;O<this.world.getItemCount();O++)this.world.getItemAt(O).debugMode=w;this.debugMode=w,this.forceRedraw()},setAjaxHeaders:function(w,O){if(w===null&&(w={}),!t.isPlainObject(w)){console.error("[Viewer.setAjaxHeaders] Ignoring invalid headers, must be a plain object");return}if(O===void 0&&(O=!0),this.ajaxHeaders=w,O){for(var z=0;z<this.world.getItemCount();z++)this.world.getItemAt(z)._updateAjaxHeaders(!0);if(this.navigator&&this.navigator.setAjaxHeaders(this.ajaxHeaders,!0),this.referenceStrip&&this.referenceStrip.miniViewers)for(var ie in this.referenceStrip.miniViewers)this.referenceStrip.miniViewers[ie].setAjaxHeaders(this.ajaxHeaders,!0)}},addButton:function(w){this.buttonGroup.addButton(w)},isFullPage:function(){return n[this.hash].fullPage},setFullPage:function(w){var O=document.body,z=O.style,ie=document.documentElement.style,te=this,xe,he;if(w===this.isFullPage())return this;var $e={fullPage:w,preventDefaultAction:!1};if(this.raiseEvent("pre-full-page",$e),$e.preventDefaultAction)return this;if(w){for(this.elementSize=t.getElementSize(this.element),this.pageScroll=t.getPageScroll(),this.elementMargin=this.element.style.margin,this.element.style.margin="0",this.elementPadding=this.element.style.padding,this.element.style.padding="0",this.bodyMargin=z.margin,this.docMargin=ie.margin,z.margin="0",ie.margin="0",this.bodyPadding=z.padding,this.docPadding=ie.padding,z.padding="0",ie.padding="0",this.bodyWidth=z.width,this.docWidth=ie.width,z.width="100%",ie.width="100%",this.bodyHeight=z.height,this.docHeight=ie.height,z.height="100%",ie.height="100%",this.bodyDisplay=z.display,z.display="block",this.previousBody=[],n[this.hash].prevElementParent=this.element.parentNode,n[this.hash].prevNextSibling=this.element.nextSibling,n[this.hash].prevElementWidth=this.element.style.width,n[this.hash].prevElementHeight=this.element.style.height,xe=O.childNodes.length,he=0;he<xe;he++)this.previousBody.push(O.childNodes[0]),O.removeChild(O.childNodes[0]);this.toolbar&&this.toolbar.element&&(this.toolbar.parentNode=this.toolbar.element.parentNode,this.toolbar.nextSibling=this.toolbar.element.nextSibling,O.appendChild(this.toolbar.element),t.addClass(this.toolbar.element,"fullpage")),t.addClass(this.element,"fullpage"),O.appendChild(this.element),this.element.style.height="100vh",this.element.style.width="100vw",this.toolbar&&this.toolbar.element&&(this.element.style.height=t.getElementSize(this.element).y-t.getElementSize(this.toolbar.element).y+"px"),n[this.hash].fullPage=!0,t.delegate(this,X)({})}else{for(this.element.style.margin=this.elementMargin,this.element.style.padding=this.elementPadding,z.margin=this.bodyMargin,ie.margin=this.docMargin,z.padding=this.bodyPadding,ie.padding=this.docPadding,z.width=this.bodyWidth,ie.width=this.docWidth,z.height=this.bodyHeight,ie.height=this.docHeight,z.display=this.bodyDisplay,O.removeChild(this.element),xe=this.previousBody.length,he=0;he<xe;he++)O.appendChild(this.previousBody.shift());t.removeClass(this.element,"fullpage"),n[this.hash].prevElementParent.insertBefore(this.element,n[this.hash].prevNextSibling),this.toolbar&&this.toolbar.element&&(O.removeChild(this.toolbar.element),t.removeClass(this.toolbar.element,"fullpage"),this.toolbar.parentNode.insertBefore(this.toolbar.element,this.toolbar.nextSibling),delete this.toolbar.parentNode,delete this.toolbar.nextSibling),this.element.style.width=n[this.hash].prevElementWidth,this.element.style.height=n[this.hash].prevElementHeight;var ze=0,ce=function(){t.setPageScroll(te.pageScroll);var fe=t.getPageScroll();ze++,ze<10&&(fe.x!==te.pageScroll.x||fe.y!==te.pageScroll.y)&&t.requestAnimationFrame(ce)};t.requestAnimationFrame(ce),n[this.hash].fullPage=!1,t.delegate(this,F)({})}return this.navigator&&this.viewport&&this.navigator.update(this.viewport),this.raiseEvent("full-page",{fullPage:w}),this},setFullScreen:function(w){var O=this;if(!t.supportsFullScreen)return this.setFullPage(w);if(t.isFullScreen()===w)return this;var z={fullScreen:w,preventDefaultAction:!1};if(this.raiseEvent("pre-full-screen",z),z.preventDefaultAction)return this;if(w){if(this.setFullPage(!0),!this.isFullPage())return this;this.fullPageStyleWidth=this.element.style.width,this.fullPageStyleHeight=this.element.style.height,this.element.style.width="100%",this.element.style.height="100%";var ie=function(){var te=t.isFullScreen();te||(t.removeEvent(document,t.fullScreenEventName,ie),t.removeEvent(document,t.fullScreenErrorEventName,ie),O.setFullPage(!1),O.isFullPage()&&(O.element.style.width=O.fullPageStyleWidth,O.element.style.height=O.fullPageStyleHeight)),O.navigator&&O.viewport&&setTimeout(function(){O.navigator.update(O.viewport)}),O.raiseEvent("full-screen",{fullScreen:te})};t.addEvent(document,t.fullScreenEventName,ie),t.addEvent(document,t.fullScreenErrorEventName,ie),t.requestFullScreen(document.body)}else t.exitFullScreen();return this},isVisible:function(){return this.container.style.visibility!=="hidden"},isFullScreen:function(){return t.isFullScreen()&&this.isFullPage()},setVisible:function(w){return this.container.style.visibility=w?"":"hidden",this.raiseEvent("visible",{visible:w}),this},addTiledImage:function(w){t.console.assert(w,"[Viewer.addTiledImage] options is required"),t.console.assert(w.tileSource,"[Viewer.addTiledImage] options.tileSource is required"),t.console.assert(!w.replace||w.index>-1&&w.index<this.world.getItemCount(),"[Viewer.addTiledImage] if options.replace is used, options.index must be a valid index in Viewer.world");var O=this;w.replace&&(w.replaceItem=O.world.getItemAt(w.index)),this._hideMessage(),w.placeholderFillStyle===void 0&&(w.placeholderFillStyle=this.placeholderFillStyle),w.opacity===void 0&&(w.opacity=this.opacity),w.preload===void 0&&(w.preload=this.preload),w.compositeOperation===void 0&&(w.compositeOperation=this.compositeOperation),w.crossOriginPolicy===void 0&&(w.crossOriginPolicy=w.tileSource.crossOriginPolicy!==void 0?w.tileSource.crossOriginPolicy:this.crossOriginPolicy),w.ajaxWithCredentials===void 0&&(w.ajaxWithCredentials=this.ajaxWithCredentials),w.loadTilesWithAjax===void 0&&(w.loadTilesWithAjax=this.loadTilesWithAjax),t.isPlainObject(w.ajaxHeaders)||(w.ajaxHeaders={});var z={options:w};function ie(he){for(var $e=0;$e<O._loadQueue.length;$e++)if(O._loadQueue[$e]===z){O._loadQueue.splice($e,1);break}O._loadQueue.length===0&&te(z),O.raiseEvent("add-item-failed",he),w.error&&w.error(he)}function te(he){O.collectionMode&&(O.world.arrange({immediately:he.options.collectionImmediately,rows:O.collectionRows,columns:O.collectionColumns,layout:O.collectionLayout,tileSize:O.collectionTileSize,tileMargin:O.collectionTileMargin}),O.world.setAutoRefigureSizes(!0))}if(t.isArray(w.tileSource)){setTimeout(function(){ie({message:"[Viewer.addTiledImage] Sequences can not be added; add them one at a time instead.",source:w.tileSource,options:w})});return}this._loadQueue.push(z);function xe(){for(var he,$e,ze;O._loadQueue.length&&(he=O._loadQueue[0],!!he.tileSource);){if(O._loadQueue.splice(0,1),he.options.replace){var ce=O.world.getIndexOfItem(he.options.replaceItem);ce!==-1&&(he.options.index=ce),O.world.removeItem(he.options.replaceItem)}$e=new t.TiledImage({viewer:O,source:he.tileSource,viewport:O.viewport,drawer:O.drawer,tileCache:O.tileCache,imageLoader:O.imageLoader,x:he.options.x,y:he.options.y,width:he.options.width,height:he.options.height,fitBounds:he.options.fitBounds,fitBoundsPlacement:he.options.fitBoundsPlacement,clip:he.options.clip,placeholderFillStyle:he.options.placeholderFillStyle,opacity:he.options.opacity,preload:he.options.preload,degrees:he.options.degrees,flipped:he.options.flipped,compositeOperation:he.options.compositeOperation,springStiffness:O.springStiffness,animationTime:O.animationTime,minZoomImageRatio:O.minZoomImageRatio,wrapHorizontal:O.wrapHorizontal,wrapVertical:O.wrapVertical,immediateRender:O.immediateRender,blendTime:O.blendTime,alwaysBlend:O.alwaysBlend,minPixelRatio:O.minPixelRatio,smoothTileEdgesMinZoom:O.smoothTileEdgesMinZoom,iOSDevice:O.iOSDevice,crossOriginPolicy:he.options.crossOriginPolicy,ajaxWithCredentials:he.options.ajaxWithCredentials,loadTilesWithAjax:he.options.loadTilesWithAjax,ajaxHeaders:he.options.ajaxHeaders,debugMode:O.debugMode,subPixelRoundingForTransparency:O.subPixelRoundingForTransparency}),O.collectionMode&&O.world.setAutoRefigureSizes(!1),O.navigator&&(ze=t.extend({},he.options,{replace:!1,originalTiledImage:$e,tileSource:he.tileSource}),O.navigator.addTiledImage(ze)),O.world.addItem($e,{index:he.options.index}),O._loadQueue.length===0&&te(he),O.world.getItemCount()===1&&!O.preserveViewport&&O.viewport.goHome(!0),he.options.success&&he.options.success({item:$e})}}o(this,w.tileSource,w,function(he){z.tileSource=he,xe()},function(he){he.options=w,ie(he),xe()})},addSimpleImage:function(w){t.console.assert(w,"[Viewer.addSimpleImage] options is required"),t.console.assert(w.url,"[Viewer.addSimpleImage] options.url is required");var O=t.extend({},w,{tileSource:{type:"image",url:w.url}});delete O.url,this.addTiledImage(O)},addLayer:function(w){var O=this;t.console.error("[Viewer.addLayer] this function is deprecated; use Viewer.addTiledImage() instead.");var z=t.extend({},w,{success:function(ie){O.raiseEvent("add-layer",{options:w,drawer:ie.item})},error:function(ie){O.raiseEvent("add-layer-failed",ie)}});return this.addTiledImage(z),this},getLayerAtLevel:function(w){return t.console.error("[Viewer.getLayerAtLevel] this function is deprecated; use World.getItemAt() instead."),this.world.getItemAt(w)},getLevelOfLayer:function(w){return t.console.error("[Viewer.getLevelOfLayer] this function is deprecated; use World.getIndexOfItem() instead."),this.world.getIndexOfItem(w)},getLayersCount:function(){return t.console.error("[Viewer.getLayersCount] this function is deprecated; use World.getItemCount() instead."),this.world.getItemCount()},setLayerLevel:function(w,O){return t.console.error("[Viewer.setLayerLevel] this function is deprecated; use World.setItemIndex() instead."),this.world.setItemIndex(w,O)},removeLayer:function(w){return t.console.error("[Viewer.removeLayer] this function is deprecated; use World.removeItem() instead."),this.world.removeItem(w)},forceRedraw:function(){return n[this.hash].forceRedraw=!0,this},forceResize:function(){n[this.hash].needsResize=!0,n[this.hash].forceResize=!0},bindSequenceControls:function(){var w=t.delegate(this,p),O=t.delegate(this,g),z=t.delegate(this,this.goToNextPage),ie=t.delegate(this,this.goToPreviousPage),te=this.navImages,xe=!0;return this.showSequenceControl&&((this.previousButton||this.nextButton)&&(xe=!1),this.previousButton=new t.Button({element:this.previousButton?t.getElement(this.previousButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.PreviousPage"),srcRest:Q(this.prefixUrl,te.previous.REST),srcGroup:Q(this.prefixUrl,te.previous.GROUP),srcHover:Q(this.prefixUrl,te.previous.HOVER),srcDown:Q(this.prefixUrl,te.previous.DOWN),onRelease:ie,onFocus:w,onBlur:O}),this.nextButton=new t.Button({element:this.nextButton?t.getElement(this.nextButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.NextPage"),srcRest:Q(this.prefixUrl,te.next.REST),srcGroup:Q(this.prefixUrl,te.next.GROUP),srcHover:Q(this.prefixUrl,te.next.HOVER),srcDown:Q(this.prefixUrl,te.next.DOWN),onRelease:z,onFocus:w,onBlur:O}),this.navPrevNextWrap||this.previousButton.disable(),(!this.tileSources||!this.tileSources.length)&&this.nextButton.disable(),xe&&(this.paging=new t.ButtonGroup({buttons:[this.previousButton,this.nextButton],clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold}),this.pagingControl=this.paging.element,this.toolbar?this.toolbar.addControl(this.pagingControl,{anchor:t.ControlAnchor.BOTTOM_RIGHT}):this.addControl(this.pagingControl,{anchor:this.sequenceControlAnchor||t.ControlAnchor.TOP_LEFT}))),this},bindStandardControls:function(){var w=t.delegate(this,le),O=t.delegate(this,ye),z=t.delegate(this,qe),ie=t.delegate(this,re),te=t.delegate(this,Le),xe=t.delegate(this,Ue),he=t.delegate(this,Xe),$e=t.delegate(this,it),ze=t.delegate(this,zt),ce=t.delegate(this,De),fe=t.delegate(this,p),He=t.delegate(this,g),R=this.navImages,A=[],L=!0;return this.showNavigationControl&&((this.zoomInButton||this.zoomOutButton||this.homeButton||this.fullPageButton||this.rotateLeftButton||this.rotateRightButton||this.flipButton)&&(L=!1),this.showZoomControl&&(A.push(this.zoomInButton=new t.Button({element:this.zoomInButton?t.getElement(this.zoomInButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.ZoomIn"),srcRest:Q(this.prefixUrl,R.zoomIn.REST),srcGroup:Q(this.prefixUrl,R.zoomIn.GROUP),srcHover:Q(this.prefixUrl,R.zoomIn.HOVER),srcDown:Q(this.prefixUrl,R.zoomIn.DOWN),onPress:w,onRelease:O,onClick:z,onEnter:w,onExit:O,onFocus:fe,onBlur:He})),A.push(this.zoomOutButton=new t.Button({element:this.zoomOutButton?t.getElement(this.zoomOutButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.ZoomOut"),srcRest:Q(this.prefixUrl,R.zoomOut.REST),srcGroup:Q(this.prefixUrl,R.zoomOut.GROUP),srcHover:Q(this.prefixUrl,R.zoomOut.HOVER),srcDown:Q(this.prefixUrl,R.zoomOut.DOWN),onPress:ie,onRelease:O,onClick:te,onEnter:ie,onExit:O,onFocus:fe,onBlur:He}))),this.showHomeControl&&A.push(this.homeButton=new t.Button({element:this.homeButton?t.getElement(this.homeButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.Home"),srcRest:Q(this.prefixUrl,R.home.REST),srcGroup:Q(this.prefixUrl,R.home.GROUP),srcHover:Q(this.prefixUrl,R.home.HOVER),srcDown:Q(this.prefixUrl,R.home.DOWN),onRelease:xe,onFocus:fe,onBlur:He})),this.showFullPageControl&&A.push(this.fullPageButton=new t.Button({element:this.fullPageButton?t.getElement(this.fullPageButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.FullPage"),srcRest:Q(this.prefixUrl,R.fullpage.REST),srcGroup:Q(this.prefixUrl,R.fullpage.GROUP),srcHover:Q(this.prefixUrl,R.fullpage.HOVER),srcDown:Q(this.prefixUrl,R.fullpage.DOWN),onRelease:he,onFocus:fe,onBlur:He})),this.showRotationControl&&(A.push(this.rotateLeftButton=new t.Button({element:this.rotateLeftButton?t.getElement(this.rotateLeftButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.RotateLeft"),srcRest:Q(this.prefixUrl,R.rotateleft.REST),srcGroup:Q(this.prefixUrl,R.rotateleft.GROUP),srcHover:Q(this.prefixUrl,R.rotateleft.HOVER),srcDown:Q(this.prefixUrl,R.rotateleft.DOWN),onRelease:$e,onFocus:fe,onBlur:He})),A.push(this.rotateRightButton=new t.Button({element:this.rotateRightButton?t.getElement(this.rotateRightButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.RotateRight"),srcRest:Q(this.prefixUrl,R.rotateright.REST),srcGroup:Q(this.prefixUrl,R.rotateright.GROUP),srcHover:Q(this.prefixUrl,R.rotateright.HOVER),srcDown:Q(this.prefixUrl,R.rotateright.DOWN),onRelease:ze,onFocus:fe,onBlur:He}))),this.showFlipControl&&A.push(this.flipButton=new t.Button({element:this.flipButton?t.getElement(this.flipButton):null,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,tooltip:t.getString("Tooltips.Flip"),srcRest:Q(this.prefixUrl,R.flip.REST),srcGroup:Q(this.prefixUrl,R.flip.GROUP),srcHover:Q(this.prefixUrl,R.flip.HOVER),srcDown:Q(this.prefixUrl,R.flip.DOWN),onRelease:ce,onFocus:fe,onBlur:He})),L?(this.buttonGroup=new t.ButtonGroup({buttons:A,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold}),this.navControl=this.buttonGroup.element,this.addHandler("open",t.delegate(this,Fe)),this.toolbar?this.toolbar.addControl(this.navControl,{anchor:this.navigationControlAnchor||t.ControlAnchor.TOP_LEFT}):this.addControl(this.navControl,{anchor:this.navigationControlAnchor||t.ControlAnchor.TOP_LEFT})):this.customButtons=A),this},currentPage:function(){return this._sequenceIndex},goToPage:function(w){return this.tileSources&&w>=0&&w<this.tileSources.length&&(this._sequenceIndex=w,this._updateSequenceButtons(w),this.open(this.tileSources[w]),this.referenceStrip&&this.referenceStrip.setFocus(w),this.raiseEvent("page",{page:w})),this},addOverlay:function(w,O,z,ie){var te;if(t.isPlainObject(w)?te=w:te={element:w,location:O,placement:z,onDraw:ie},w=t.getElement(te.element),l(this.currentOverlays,w)>=0)return this;var xe=a(this,te);return this.currentOverlays.push(xe),xe.drawHTML(this.overlaysContainer,this.viewport),this.raiseEvent("add-overlay",{element:w,location:te.location,placement:te.placement}),this},updateOverlay:function(w,O,z){var ie;return w=t.getElement(w),ie=l(this.currentOverlays,w),ie>=0&&(this.currentOverlays[ie].update(O,z),n[this.hash].forceRedraw=!0,this.raiseEvent("update-overlay",{element:w,location:O,placement:z})),this},removeOverlay:function(w){var O;return w=t.getElement(w),O=l(this.currentOverlays,w),O>=0&&(this.currentOverlays[O].destroy(),this.currentOverlays.splice(O,1),n[this.hash].forceRedraw=!0,this.raiseEvent("remove-overlay",{element:w})),this},clearOverlays:function(){for(;this.currentOverlays.length>0;)this.currentOverlays.pop().destroy();return n[this.hash].forceRedraw=!0,this.raiseEvent("clear-overlay",{}),this},getOverlayById:function(w){var O;return w=t.getElement(w),O=l(this.currentOverlays,w),O>=0?this.currentOverlays[O]:null},_updateSequenceButtons:function(w){this.nextButton&&(!this.tileSources||this.tileSources.length-1===w?this.navPrevNextWrap||this.nextButton.disable():this.nextButton.enable()),this.previousButton&&(w>0?this.previousButton.enable():this.navPrevNextWrap||this.previousButton.disable())},_showMessage:function(w){this._hideMessage();var O=t.makeNeutralElement("div");O.appendChild(document.createTextNode(w)),this.messageDiv=t.makeCenteredNode(O),t.addClass(this.messageDiv,"openseadragon-message"),this.container.appendChild(this.messageDiv)},_hideMessage:function(){var w=this.messageDiv;w&&(w.parentNode.removeChild(w),delete this.messageDiv)},gestureSettingsByDeviceType:function(w){switch(w){case"mouse":return this.gestureSettingsMouse;case"touch":return this.gestureSettingsTouch;case"pen":return this.gestureSettingsPen;default:return this.gestureSettingsUnknown}},_drawOverlays:function(){var w,O=this.currentOverlays.length;for(w=0;w<O;w++)this.currentOverlays[w].drawHTML(this.overlaysContainer,this.viewport)},_cancelPendingImages:function(){this._loadQueue=[]},removeReferenceStrip:function(){this.showReferenceStrip=!1,this.referenceStrip&&(this.referenceStrip.destroy(),this.referenceStrip=null)},addReferenceStrip:function(){if(this.showReferenceStrip=!0,this.sequenceMode){if(this.referenceStrip)return;this.tileSources.length&&this.tileSources.length>1&&(this.referenceStrip=new t.ReferenceStrip({id:this.referenceStripElement,position:this.referenceStripPosition,sizeRatio:this.referenceStripSizeRatio,scroll:this.referenceStripScroll,height:this.referenceStripHeight,width:this.referenceStripWidth,tileSources:this.tileSources,prefixUrl:this.prefixUrl,useCanvas:this.useCanvas,viewer:this}),this.referenceStrip.setFocus(this._sequenceIndex))}else t.console.warn('Attempting to display a reference strip while "sequenceMode" is off.')},_addUpdatePixelDensityRatioEvent:function(){this._updatePixelDensityRatioBind=this._updatePixelDensityRatio.bind(this),t.addEvent(window,"resize",this._updatePixelDensityRatioBind)},_removeUpdatePixelDensityRatioEvent:function(){t.removeEvent(window,"resize",this._updatePixelDensityRatioBind)},_updatePixelDensityRatio:function(){var w=t.pixelDensityRatio,O=t.getCurrentPixelDensityRatio();w!==O&&(t.pixelDensityRatio=O,this.world.resetItems(),this.forceRedraw())},goToPreviousPage:function(){var w=this._sequenceIndex-1;this.navPrevNextWrap&&w<0&&(w+=this.tileSources.length),this.goToPage(w)},goToNextPage:function(){var w=this._sequenceIndex+1;this.navPrevNextWrap&&w>=this.tileSources.length&&(w=0),this.goToPage(w)},isAnimating:function(){return n[this.hash].animating}});function s(w){return w=t.getElement(w),new t.Point(w.clientWidth===0?1:w.clientWidth,w.clientHeight===0?1:w.clientHeight)}function o(w,O,z,ie,te){var xe=w;if(t.type(O)==="string"){if(O.match(/^\s*<.*>\s*$/))O=t.parseXml(O);else if(O.match(/^\s*[{[].*[}\]]\s*$/))try{var he=t.parseJSON(O);O=he}catch{}}function $e(ze,ce){ze.ready?ie(ze):(ze.addHandler("ready",function(){ie(ze)}),ze.addHandler("open-failed",function(fe){te({message:fe.message,source:ce})}))}setTimeout(function(){if(t.type(O)==="string")O=new t.TileSource({url:O,crossOriginPolicy:z.crossOriginPolicy!==void 0?z.crossOriginPolicy:w.crossOriginPolicy,ajaxWithCredentials:w.ajaxWithCredentials,ajaxHeaders:z.ajaxHeaders?z.ajaxHeaders:w.ajaxHeaders,splitHashDataForPost:w.splitHashDataForPost,useCanvas:w.useCanvas,success:function(He){ie(He.tileSource)}}),O.addHandler("open-failed",function(He){te(He)});else if(t.isPlainObject(O)||O.nodeType)if(O.crossOriginPolicy===void 0&&(z.crossOriginPolicy!==void 0||w.crossOriginPolicy!==void 0)&&(O.crossOriginPolicy=z.crossOriginPolicy!==void 0?z.crossOriginPolicy:w.crossOriginPolicy),O.ajaxWithCredentials===void 0&&(O.ajaxWithCredentials=w.ajaxWithCredentials),O.useCanvas===void 0&&(O.useCanvas=w.useCanvas),t.isFunction(O.getTileUrl)){var ze=new t.TileSource(O);ze.getTileUrl=O.getTileUrl,ie(ze)}else{var ce=t.TileSource.determineType(xe,O);if(!ce){te({message:"Unable to load TileSource",source:O});return}var fe=ce.prototype.configure.apply(xe,[O]);$e(new ce(fe),O)}else $e(O,O)})}function a(w,O){if(O instanceof t.Overlay)return O;var z=null;if(O.element)z=t.getElement(O.element);else{var ie=O.id?O.id:"openseadragon-overlay-"+Math.floor(Math.random()*1e7);z=t.getElement(O.id),z||(z=document.createElement("a"),z.href="#/overlay/"+ie),z.id=ie,t.addClass(z,O.className?O.className:"openseadragon-overlay")}var te=O.location,xe=O.width,he=O.height;if(!te){var $e=O.x,ze=O.y;if(O.px!==void 0){var ce=w.viewport.imageToViewportRectangle(new t.Rect(O.px,O.py,xe||0,he||0));$e=ce.x,ze=ce.y,xe=xe!==void 0?ce.width:void 0,he=he!==void 0?ce.height:void 0}te=new t.Point($e,ze)}var fe=O.placement;return fe&&t.type(fe)==="string"&&(fe=t.Placement[O.placement.toUpperCase()]),new t.Overlay({element:z,location:te,placement:fe,onDraw:O.onDraw,checkResize:O.checkResize,width:xe,height:he,rotationMode:O.rotationMode})}function l(w,O){var z;for(z=w.length-1;z>=0;z--)if(w[z].element===O)return z;return-1}function c(w,O){return t.requestAnimationFrame(function(){O(w)})}function u(w){t.requestAnimationFrame(function(){h(w)})}function d(w){w.autoHideControls&&(w.controlsShouldFade=!0,w.controlsFadeBeginTime=t.now()+w.controlsFadeDelay,window.setTimeout(function(){u(w)},w.controlsFadeDelay))}function h(w){var O,z,ie,te;if(w.controlsShouldFade){for(O=t.now(),z=O-w.controlsFadeBeginTime,ie=1-z/w.controlsFadeLength,ie=Math.min(1,ie),ie=Math.max(0,ie),te=w.controls.length-1;te>=0;te--)w.controls[te].autoFade&&w.controls[te].setOpacity(ie);ie>0&&u(w)}}function f(w){var O;for(w.controlsShouldFade=!1,O=w.controls.length-1;O>=0;O--)w.controls[O].setOpacity(1)}function p(){f(this)}function g(){d(this)}function m(w){var O={tracker:w.eventSource,position:w.position,originalEvent:w.originalEvent,preventDefault:w.preventDefault};this.raiseEvent("canvas-contextmenu",O),w.preventDefault=O.preventDefault}function v(w){var O={originalEvent:w.originalEvent,preventDefaultAction:!1,preventVerticalPan:w.preventVerticalPan||!this.panVertical,preventHorizontalPan:w.preventHorizontalPan||!this.panHorizontal};if(this.raiseEvent("canvas-key",O),!O.preventDefaultAction&&!w.ctrl&&!w.alt&&!w.meta)switch(w.keyCode){case 38:O.preventVerticalPan||(w.shift?this.viewport.zoomBy(1.1):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(0,-this.pixelsPerArrowPress))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 40:O.preventVerticalPan||(w.shift?this.viewport.zoomBy(.9):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(0,this.pixelsPerArrowPress))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 37:O.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(-this.pixelsPerArrowPress,0))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 39:O.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(this.pixelsPerArrowPress,0))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 187:this.viewport.zoomBy(1.1),this.viewport.applyConstraints(),w.preventDefault=!0;break;case 189:this.viewport.zoomBy(.9),this.viewport.applyConstraints(),w.preventDefault=!0;break;case 48:this.viewport.goHome(),this.viewport.applyConstraints(),w.preventDefault=!0;break;case 87:O.preventVerticalPan||(w.shift?this.viewport.zoomBy(1.1):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(0,-40))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 83:O.preventVerticalPan||(w.shift?this.viewport.zoomBy(.9):this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(0,40))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 65:O.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(-40,0))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 68:O.preventHorizontalPan||(this.viewport.panBy(this.viewport.deltaPointsFromPixels(new t.Point(40,0))),this.viewport.applyConstraints()),w.preventDefault=!0;break;case 82:w.shift?this.viewport.flipped?this.viewport.setRotation(this.viewport.getRotation()+this.rotationIncrement):this.viewport.setRotation(this.viewport.getRotation()-this.rotationIncrement):this.viewport.flipped?this.viewport.setRotation(this.viewport.getRotation()-this.rotationIncrement):this.viewport.setRotation(this.viewport.getRotation()+this.rotationIncrement),this.viewport.applyConstraints(),w.preventDefault=!0;break;case 70:this.viewport.toggleFlip(),w.preventDefault=!0;break;case 74:this.goToPreviousPage();break;case 75:this.goToNextPage();break;default:w.preventDefault=!1;break}else w.preventDefault=!1}function y(w){var O={originalEvent:w.originalEvent};this.raiseEvent("canvas-key-press",O)}function S(w){var O,z=document.activeElement===this.canvas;z||this.canvas.focus(),this.viewport.flipped&&(w.position.x=this.viewport.getContainerSize().x-w.position.x);var ie={tracker:w.eventSource,position:w.position,quick:w.quick,shift:w.shift,originalEvent:w.originalEvent,originalTarget:w.originalTarget,preventDefaultAction:!1};this.raiseEvent("canvas-click",ie),!ie.preventDefaultAction&&this.viewport&&w.quick&&(O=this.gestureSettingsByDeviceType(w.pointerType),O.clickToZoom===!0&&(this.viewport.zoomBy(w.shift?1/this.zoomPerClick:this.zoomPerClick,O.zoomToRefPoint?this.viewport.pointFromPixel(w.position,!0):null),this.viewport.applyConstraints()),O.dblClickDragToZoom&&(n[this.hash].draggingToZoom===!0?(n[this.hash].lastClickTime=null,n[this.hash].draggingToZoom=!1):n[this.hash].lastClickTime=t.now()))}function x(w){var O,z={tracker:w.eventSource,position:w.position,shift:w.shift,originalEvent:w.originalEvent,preventDefaultAction:!1};this.raiseEvent("canvas-double-click",z),!z.preventDefaultAction&&this.viewport&&(O=this.gestureSettingsByDeviceType(w.pointerType),O.dblClickToZoom&&(this.viewport.zoomBy(w.shift?1/this.zoomPerClick:this.zoomPerClick,O.zoomToRefPoint?this.viewport.pointFromPixel(w.position,!0):null),this.viewport.applyConstraints()))}function E(w){var O,z={tracker:w.eventSource,pointerType:w.pointerType,position:w.position,delta:w.delta,speed:w.speed,direction:w.direction,shift:w.shift,originalEvent:w.originalEvent,preventDefaultAction:!1};if(this.raiseEvent("canvas-drag",z),O=this.gestureSettingsByDeviceType(w.pointerType),!z.preventDefaultAction&&this.viewport){if(O.dblClickDragToZoom&&n[this.hash].draggingToZoom){var ie=Math.pow(this.zoomPerDblClickDrag,w.delta.y/50);this.viewport.zoomBy(ie)}else if(O.dragToPan&&!n[this.hash].draggingToZoom){if(this.panHorizontal||(w.delta.x=0),this.panVertical||(w.delta.y=0),this.viewport.flipped&&(w.delta.x=-w.delta.x),this.constrainDuringPan){var te=this.viewport.deltaPointsFromPixels(w.delta.negate());this.viewport.centerSpringX.target.value+=te.x,this.viewport.centerSpringY.target.value+=te.y;var xe=this.viewport.getConstrainedBounds();this.viewport.centerSpringX.target.value-=te.x,this.viewport.centerSpringY.target.value-=te.y,xe.xConstrained&&(w.delta.x=0),xe.yConstrained&&(w.delta.y=0)}this.viewport.panBy(this.viewport.deltaPointsFromPixels(w.delta.negate()),O.flickEnabled&&!this.constrainDuringPan)}}}function C(w){var O,z={tracker:w.eventSource,pointerType:w.pointerType,position:w.position,speed:w.speed,direction:w.direction,shift:w.shift,originalEvent:w.originalEvent,preventDefaultAction:!1};if(this.raiseEvent("canvas-drag-end",z),O=this.gestureSettingsByDeviceType(w.pointerType),!z.preventDefaultAction&&this.viewport){if(!n[this.hash].draggingToZoom&&O.flickEnabled&&w.speed>=O.flickMinSpeed){var ie=0;this.panHorizontal&&(ie=O.flickMomentum*w.speed*Math.cos(w.direction));var te=0;this.panVertical&&(te=O.flickMomentum*w.speed*Math.sin(w.direction));var xe=this.viewport.pixelFromPoint(this.viewport.getCenter(!0)),he=this.viewport.pointFromPixel(new t.Point(xe.x-ie,xe.y-te));this.viewport.panTo(he,!1)}this.viewport.applyConstraints()}O.dblClickDragToZoom&&n[this.hash].draggingToZoom===!0&&(n[this.hash].draggingToZoom=!1)}function b(w){this.raiseEvent("canvas-enter",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,buttons:w.buttons,pointers:w.pointers,insideElementPressed:w.insideElementPressed,buttonDownAny:w.buttonDownAny,originalEvent:w.originalEvent})}function I(w){this.raiseEvent("canvas-exit",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,buttons:w.buttons,pointers:w.pointers,insideElementPressed:w.insideElementPressed,buttonDownAny:w.buttonDownAny,originalEvent:w.originalEvent})}function D(w){var O;if(this.raiseEvent("canvas-press",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,insideElementPressed:w.insideElementPressed,insideElementReleased:w.insideElementReleased,originalEvent:w.originalEvent}),O=this.gestureSettingsByDeviceType(w.pointerType),O.dblClickDragToZoom){var z=n[this.hash].lastClickTime,ie=t.now();if(z===null)return;ie-z<this.dblClickTimeThreshold&&(n[this.hash].draggingToZoom=!0),n[this.hash].lastClickTime=null}}function P(w){this.raiseEvent("canvas-release",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,insideElementPressed:w.insideElementPressed,insideElementReleased:w.insideElementReleased,originalEvent:w.originalEvent})}function k(w){this.raiseEvent("canvas-nonprimary-press",{tracker:w.eventSource,position:w.position,pointerType:w.pointerType,button:w.button,buttons:w.buttons,originalEvent:w.originalEvent})}function N(w){this.raiseEvent("canvas-nonprimary-release",{tracker:w.eventSource,position:w.position,pointerType:w.pointerType,button:w.button,buttons:w.buttons,originalEvent:w.originalEvent})}function B(w){var O,z,ie,te,xe={tracker:w.eventSource,pointerType:w.pointerType,gesturePoints:w.gesturePoints,lastCenter:w.lastCenter,center:w.center,lastDistance:w.lastDistance,distance:w.distance,shift:w.shift,originalEvent:w.originalEvent,preventDefaultPanAction:!1,preventDefaultZoomAction:!1,preventDefaultRotateAction:!1};if(this.raiseEvent("canvas-pinch",xe),this.viewport&&(O=this.gestureSettingsByDeviceType(w.pointerType),O.pinchToZoom&&(!xe.preventDefaultPanAction||!xe.preventDefaultZoomAction)&&(z=this.viewport.pointFromPixel(w.center,!0),O.zoomToRefPoint&&!xe.preventDefaultPanAction&&(ie=this.viewport.pointFromPixel(w.lastCenter,!0),te=ie.minus(z),this.panHorizontal||(te.x=0),this.panVertical||(te.y=0),this.viewport.panBy(te,!0)),xe.preventDefaultZoomAction||this.viewport.zoomBy(w.distance/w.lastDistance,z,!0),this.viewport.applyConstraints()),O.pinchRotate&&!xe.preventDefaultRotateAction)){var he=Math.atan2(w.gesturePoints[0].currentPos.y-w.gesturePoints[1].currentPos.y,w.gesturePoints[0].currentPos.x-w.gesturePoints[1].currentPos.x),$e=Math.atan2(w.gesturePoints[0].lastPos.y-w.gesturePoints[1].lastPos.y,w.gesturePoints[0].lastPos.x-w.gesturePoints[1].lastPos.x);z=this.viewport.pointFromPixel(w.center,!0),this.viewport.rotateTo(this.viewport.getRotation(!0)+(he-$e)*(180/Math.PI),z,!0)}}function K(w){this.raiseEvent("canvas-focus",{tracker:w.eventSource,originalEvent:w.originalEvent})}function q(w){this.raiseEvent("canvas-blur",{tracker:w.eventSource,originalEvent:w.originalEvent})}function H(w){var O,z,ie,te,xe;te=t.now(),xe=te-this._lastScrollTime,xe>this.minScrollDeltaTime?(this._lastScrollTime=te,O={tracker:w.eventSource,position:w.position,scroll:w.scroll,shift:w.shift,originalEvent:w.originalEvent,preventDefaultAction:!1,preventDefault:!0},this.raiseEvent("canvas-scroll",O),!O.preventDefaultAction&&this.viewport&&(this.viewport.flipped&&(w.position.x=this.viewport.getContainerSize().x-w.position.x),z=this.gestureSettingsByDeviceType(w.pointerType),z.scrollToZoom&&(ie=Math.pow(this.zoomPerScroll,w.scroll),this.viewport.zoomBy(ie,z.zoomToRefPoint?this.viewport.pointFromPixel(w.position,!0):null),this.viewport.applyConstraints())),w.preventDefault=O.preventDefault):w.preventDefault=!0}function X(w){n[this.hash].mouseInside=!0,f(this),this.raiseEvent("container-enter",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,buttons:w.buttons,pointers:w.pointers,insideElementPressed:w.insideElementPressed,buttonDownAny:w.buttonDownAny,originalEvent:w.originalEvent})}function F(w){w.pointers<1&&(n[this.hash].mouseInside=!1,n[this.hash].animating||d(this)),this.raiseEvent("container-exit",{tracker:w.eventSource,pointerType:w.pointerType,position:w.position,buttons:w.buttons,pointers:w.pointers,insideElementPressed:w.insideElementPressed,buttonDownAny:w.buttonDownAny,originalEvent:w.originalEvent})}function U(w){V(w),w.isOpen()?w._updateRequestId=c(w,U):w._updateRequestId=!1}function j(w,O){var z=w.viewport,ie=z.getZoom(),te=z.getCenter();z.resize(O,w.preserveImageSizeOnResize),z.panTo(te,!0);var xe;if(w.preserveImageSizeOnResize)xe=n[w.hash].prevContainerSize.x/O.x;else{var he=new t.Point(0,0),$e=new t.Point(n[w.hash].prevContainerSize.x,n[w.hash].prevContainerSize.y).distanceTo(he),ze=new t.Point(O.x,O.y).distanceTo(he);xe=ze/$e*n[w.hash].prevContainerSize.x/O.x}z.zoomTo(ie*xe,null,!0),n[w.hash].prevContainerSize=O,n[w.hash].forceRedraw=!0,n[w.hash].needsResize=!1,n[w.hash].forceResize=!1}function V(w){if(!(w._opening||!n[w.hash])){if(w.autoResize||n[w.hash].forceResize){var O;if(w._autoResizePolling){O=s(w.container);var z=n[w.hash].prevContainerSize;O.equals(z)||(n[w.hash].needsResize=!0)}n[w.hash].needsResize&&j(w,O||s(w.container))}var ie=w.viewport.update(),te=w.world.update()||ie;ie&&w.raiseEvent("viewport-change"),w.referenceStrip&&(te=w.referenceStrip.update(w.viewport)||te);var xe=n[w.hash].animating;!xe&&te&&(w.raiseEvent("animation-start"),f(w));var he=xe&&!te;he&&(n[w.hash].animating=!1),(te||he||n[w.hash].forceRedraw||w.world.needsDraw())&&(Z(w),w._drawOverlays(),w.navigator&&w.navigator.update(w.viewport),n[w.hash].forceRedraw=!1,te&&w.raiseEvent("animation")),he&&(w.raiseEvent("animation-finish"),n[w.hash].mouseInside||d(w)),n[w.hash].animating=te}}function Z(w){w.imageLoader.clear(),w.drawer.clear(),w.world.draw(),w.raiseEvent("update-viewport",{})}function Q(w,O){return w?w+O:O}function le(){n[this.hash].lastZoomTime=t.now(),n[this.hash].zoomFactor=this.zoomPerSecond,n[this.hash].zooming=!0,de(this)}function re(){n[this.hash].lastZoomTime=t.now(),n[this.hash].zoomFactor=1/this.zoomPerSecond,n[this.hash].zooming=!0,de(this)}function ye(){n[this.hash].zooming=!1}function de(w){t.requestAnimationFrame(t.delegate(w,Pe))}function Pe(){var w,O,z;n[this.hash].zooming&&this.viewport&&(w=t.now(),O=w-n[this.hash].lastZoomTime,z=Math.pow(n[this.hash].zoomFactor,O/1e3),this.viewport.zoomBy(z),this.viewport.applyConstraints(),n[this.hash].lastZoomTime=w,de(this))}function qe(){this.viewport&&(n[this.hash].zooming=!1,this.viewport.zoomBy(this.zoomPerClick/1),this.viewport.applyConstraints())}function Le(){this.viewport&&(n[this.hash].zooming=!1,this.viewport.zoomBy(1/this.zoomPerClick),this.viewport.applyConstraints())}function Fe(){this.buttonGroup&&(this.buttonGroup.emulateEnter(),this.buttonGroup.emulateLeave())}function Ue(){this.viewport&&this.viewport.goHome()}function Xe(){this.isFullPage()&&!t.isFullScreen()?this.setFullPage(!1):this.setFullScreen(!this.isFullPage()),this.buttonGroup&&this.buttonGroup.emulateLeave(),this.fullPageButton.element.focus(),this.viewport&&this.viewport.applyConstraints()}function it(){if(this.viewport){var w=this.viewport.getRotation();this.viewport.flipped?w+=this.rotationIncrement:w-=this.rotationIncrement,this.viewport.setRotation(w)}}function zt(){if(this.viewport){var w=this.viewport.getRotation();this.viewport.flipped?w-=this.rotationIncrement:w+=this.rotationIncrement,this.viewport.setRotation(w)}}function De(){this.viewport.toggleFlip()}}(e),function(t){t.Navigator=function(c){var u=c.viewer,d=this,h,f;c.element||c.id?(c.element?(c.id&&t.console.warn("Given option.id for Navigator was ignored since option.element was provided and is being used instead."),c.element.id?c.id=c.element.id:c.id="navigator-"+t.now(),this.element=c.element):this.element=document.getElementById(c.id),c.controlOptions={anchor:t.ControlAnchor.NONE,attachToViewer:!1,autoFade:!1}):(c.id="navigator-"+t.now(),this.element=t.makeNeutralElement("div"),c.controlOptions={anchor:t.ControlAnchor.TOP_RIGHT,attachToViewer:!0,autoFade:c.autoFade},c.position&&(c.position==="BOTTOM_RIGHT"?c.controlOptions.anchor=t.ControlAnchor.BOTTOM_RIGHT:c.position==="BOTTOM_LEFT"?c.controlOptions.anchor=t.ControlAnchor.BOTTOM_LEFT:c.position==="TOP_RIGHT"?c.controlOptions.anchor=t.ControlAnchor.TOP_RIGHT:c.position==="TOP_LEFT"?c.controlOptions.anchor=t.ControlAnchor.TOP_LEFT:c.position==="ABSOLUTE"&&(c.controlOptions.anchor=t.ControlAnchor.ABSOLUTE,c.controlOptions.top=c.top,c.controlOptions.left=c.left,c.controlOptions.height=c.height,c.controlOptions.width=c.width))),this.element.id=c.id,this.element.className+=" navigator",c=t.extend(!0,{sizeRatio:t.DEFAULT_SETTINGS.navigatorSizeRatio},c,{element:this.element,tabIndex:-1,showNavigator:!1,mouseNavEnabled:!1,showNavigationControl:!1,showSequenceControl:!1,immediateRender:!0,blendTime:0,animationTime:c.animationTime,autoResize:!1,minZoomImageRatio:1,background:c.background,opacity:c.opacity,borderColor:c.borderColor,displayRegionColor:c.displayRegionColor}),c.minPixelRatio=this.minPixelRatio=u.minPixelRatio,t.setElementTouchActionNone(this.element),this.borderWidth=2,this.fudge=new t.Point(1,1),this.totalBorderWidths=new t.Point(this.borderWidth*2,this.borderWidth*2).minus(this.fudge),c.controlOptions.anchor!==t.ControlAnchor.NONE&&function(m,v){m.margin="0px",m.border=v+"px solid "+c.borderColor,m.padding="0px",m.background=c.background,m.opacity=c.opacity,m.overflow="hidden"}(this.element.style,this.borderWidth),this.displayRegion=t.makeNeutralElement("div"),this.displayRegion.id=this.element.id+"-displayregion",this.displayRegion.className="displayregion",function(m,v){m.position="relative",m.top="0px",m.left="0px",m.fontSize="0px",m.overflow="hidden",m.border=v+"px solid "+c.displayRegionColor,m.margin="0px",m.padding="0px",m.background="transparent",m.float="left",m.cssFloat="left",m.styleFloat="left",m.zIndex=999999999,m.cursor="default",m.boxSizing="content-box"}(this.displayRegion.style,this.borderWidth),t.setElementPointerEventsNone(this.displayRegion),t.setElementTouchActionNone(this.displayRegion),this.displayRegionContainer=t.makeNeutralElement("div"),this.displayRegionContainer.id=this.element.id+"-displayregioncontainer",this.displayRegionContainer.className="displayregioncontainer",this.displayRegionContainer.style.width="100%",this.displayRegionContainer.style.height="100%",t.setElementPointerEventsNone(this.displayRegionContainer),t.setElementTouchActionNone(this.displayRegionContainer),u.addControl(this.element,c.controlOptions),this._resizeWithViewer=c.controlOptions.anchor!==t.ControlAnchor.ABSOLUTE&&c.controlOptions.anchor!==t.ControlAnchor.NONE,c.width&&c.height?(this.setWidth(c.width),this.setHeight(c.height)):this._resizeWithViewer&&(h=t.getElementSize(u.element),this.element.style.height=Math.round(h.y*c.sizeRatio)+"px",this.element.style.width=Math.round(h.x*c.sizeRatio)+"px",this.oldViewerSize=h,f=t.getElementSize(this.element),this.elementArea=f.x*f.y),this.oldContainerSize=new t.Point(0,0),t.Viewer.apply(this,[c]),this.displayRegionContainer.appendChild(this.displayRegion),this.element.getElementsByTagName("div")[0].appendChild(this.displayRegionContainer);function p(m,v){a(d.displayRegionContainer,m),a(d.displayRegion,-m),d.viewport.setRotation(m,v)}if(c.navigatorRotate){var g=c.viewer.viewport?c.viewer.viewport.getRotation():c.viewer.degrees||0;p(g,!0),c.viewer.addHandler("rotate",function(m){p(m.degrees,m.immediately)})}this.innerTracker.destroy(),this.innerTracker=new t.MouseTracker({userData:"Navigator.innerTracker",element:this.element,dragHandler:t.delegate(this,r),clickHandler:t.delegate(this,n),releaseHandler:t.delegate(this,s),scrollHandler:t.delegate(this,o),preProcessEventHandler:function(m){m.eventType==="wheel"&&(m.preventDefault=!0)}}),this.outerTracker.userData="Navigator.outerTracker",t.setElementPointerEventsNone(this.canvas),t.setElementPointerEventsNone(this.container),this.addHandler("reset-size",function(){d.viewport&&d.viewport.goHome(!0)}),u.world.addHandler("item-index-change",function(m){window.setTimeout(function(){var v=d.world.getItemAt(m.previousIndex);d.world.setItemIndex(v,m.newIndex)},1)}),u.world.addHandler("remove-item",function(m){var v=m.item,y=d._getMatchingItem(v);y&&d.world.removeItem(y)}),this.update(u.viewport)},t.extend(t.Navigator.prototype,t.EventSource.prototype,t.Viewer.prototype,{updateSize:function(){if(this.viewport){var c=new t.Point(this.container.clientWidth===0?1:this.container.clientWidth,this.container.clientHeight===0?1:this.container.clientHeight);c.equals(this.oldContainerSize)||(this.viewport.resize(c,!0),this.viewport.goHome(!0),this.oldContainerSize=c,this.drawer.clear(),this.world.draw())}},setWidth:function(c){this.width=c,this.element.style.width=typeof c=="number"?c+"px":c,this._resizeWithViewer=!1,this.updateSize()},setHeight:function(c){this.height=c,this.element.style.height=typeof c=="number"?c+"px":c,this._resizeWithViewer=!1,this.updateSize()},setFlip:function(c){return this.viewport.setFlip(c),this.setDisplayTransform(this.viewer.viewport.getFlip()?"scale(-1,1)":"scale(1,1)"),this},setDisplayTransform:function(c){l(this.displayRegion,c),l(this.canvas,c),l(this.element,c)},update:function(c){var u,d,h,f,p,g;if(u=t.getElementSize(this.viewer.element),this._resizeWithViewer&&u.x&&u.y&&!u.equals(this.oldViewerSize)&&(this.oldViewerSize=u,this.maintainSizeRatio||!this.elementArea?(d=u.x*this.sizeRatio,h=u.y*this.sizeRatio):(d=Math.sqrt(this.elementArea*(u.x/u.y)),h=this.elementArea/d),this.element.style.width=Math.round(d)+"px",this.element.style.height=Math.round(h)+"px",this.elementArea||(this.elementArea=d*h),this.updateSize()),c&&this.viewport){if(f=c.getBoundsNoRotate(!0),p=this.viewport.pixelFromPointNoRotate(f.getTopLeft(),!1),g=this.viewport.pixelFromPointNoRotate(f.getBottomRight(),!1).minus(this.totalBorderWidths),!this.navigatorRotate){var m=c.getRotation(!0);a(this.displayRegion,-m)}var v=this.displayRegion.style;v.display=this.world.getItemCount()?"block":"none",v.top=p.y.toFixed(2)+"px",v.left=p.x.toFixed(2)+"px";var y=g.x-p.x,S=g.y-p.y;v.width=Math.round(Math.max(y,0))+"px",v.height=Math.round(Math.max(S,0))+"px"}},addTiledImage:function(c){var u=this,d=c.originalTiledImage;delete c.original;var h=t.extend({},c,{success:function(f){var p=f.item;p._originalForNavigator=d,u._matchBounds(p,d,!0),u._matchOpacity(p,d),u._matchCompositeOperation(p,d);function g(){u._matchBounds(p,d)}function m(){u._matchOpacity(p,d)}function v(){u._matchCompositeOperation(p,d)}d.addHandler("bounds-change",g),d.addHandler("clip-change",g),d.addHandler("opacity-change",m),d.addHandler("composite-operation-change",v)}});return t.Viewer.prototype.addTiledImage.apply(this,[h])},destroy:function(){return t.Viewer.prototype.destroy.apply(this)},_getMatchingItem:function(c){for(var u=this.world.getItemCount(),d,h=0;h<u;h++)if(d=this.world.getItemAt(h),d._originalForNavigator===c)return d;return null},_matchBounds:function(c,u,d){var h=u.getBoundsNoRotate();c.setPosition(h.getTopLeft(),d),c.setWidth(h.width,d),c.setRotation(u.getRotation(),d),c.setClip(u.getClip()),c.setFlip(u.getFlip())},_matchOpacity:function(c,u){c.setOpacity(u.opacity)},_matchCompositeOperation:function(c,u){c.setCompositeOperation(u.compositeOperation)}});function n(c){var u={tracker:c.eventSource,position:c.position,quick:c.quick,shift:c.shift,originalEvent:c.originalEvent,preventDefaultAction:!1};if(this.viewer.raiseEvent("navigator-click",u),!u.preventDefaultAction&&c.quick&&this.viewer.viewport&&(this.panVertical||this.panHorizontal)){this.viewer.viewport.flipped&&(c.position.x=this.viewport.getContainerSize().x-c.position.x);var d=this.viewport.pointFromPixel(c.position);this.panVertical?this.panHorizontal||(d.x=this.viewer.viewport.getCenter(!0).x):d.y=this.viewer.viewport.getCenter(!0).y,this.viewer.viewport.panTo(d),this.viewer.viewport.applyConstraints()}}function r(c){var u={tracker:c.eventSource,position:c.position,delta:c.delta,speed:c.speed,direction:c.direction,shift:c.shift,originalEvent:c.originalEvent,preventDefaultAction:!1};this.viewer.raiseEvent("navigator-drag",u),!u.preventDefaultAction&&this.viewer.viewport&&(this.panHorizontal||(c.delta.x=0),this.panVertical||(c.delta.y=0),this.viewer.viewport.flipped&&(c.delta.x=-c.delta.x),this.viewer.viewport.panBy(this.viewport.deltaPointsFromPixels(c.delta)),this.viewer.constrainDuringPan&&this.viewer.viewport.applyConstraints())}function s(c){c.insideElementPressed&&this.viewer.viewport&&this.viewer.viewport.applyConstraints()}function o(c){var u={tracker:c.eventSource,position:c.position,scroll:c.scroll,shift:c.shift,originalEvent:c.originalEvent,preventDefault:c.preventDefault};this.viewer.raiseEvent("navigator-scroll",u),c.preventDefault=u.preventDefault}function a(c,u){l(c,"rotate("+u+"deg)")}function l(c,u){c.style.webkitTransform=u,c.style.mozTransform=u,c.style.msTransform=u,c.style.oTransform=u,c.style.transform=u}}(e),function(t){var n={Errors:{Dzc:"Sorry, we don't support Deep Zoom Collections!",Dzi:"Hmm, this doesn't appear to be a valid Deep Zoom Image.",Xml:"Hmm, this doesn't appear to be a valid Deep Zoom Image.",ImageFormat:"Sorry, we don't support {0}-based Deep Zoom Images.",Security:"It looks like a security restriction stopped us from loading this Deep Zoom Image.",Status:"This space unintentionally left blank ({0} {1}).",OpenFailed:"Unable to open {0}: {1}"},Tooltips:{FullPage:"Toggle full page",Home:"Go home",ZoomIn:"Zoom in",ZoomOut:"Zoom out",NextPage:"Next page",PreviousPage:"Previous page",RotateLeft:"Rotate left",RotateRight:"Rotate right",Flip:"Flip Horizontally"}};t.extend(t,{getString:function(r){var s=r.split("."),o=null,a=arguments,l=n,c;for(c=0;c<s.length-1;c++)l=l[s[c]]||{};return o=l[s[c]],typeof o!="string"&&(t.console.error("Untranslated source string:",r),o=""),o.replace(/\{\d+\}/g,function(u){var d=parseInt(u.match(/\d+/),10)+1;return d<a.length?a[d]:""})},setString:function(r,s){var o=r.split("."),a=n,l;for(l=0;l<o.length-1;l++)a[o[l]]||(a[o[l]]={}),a=a[o[l]];a[o[l]]=s}})}(e),function(t){t.Point=function(n,r){this.x=typeof n=="number"?n:0,this.y=typeof r=="number"?r:0},t.Point.prototype={clone:function(){return new t.Point(this.x,this.y)},plus:function(n){return new t.Point(this.x+n.x,this.y+n.y)},minus:function(n){return new t.Point(this.x-n.x,this.y-n.y)},times:function(n){return new t.Point(this.x*n,this.y*n)},divide:function(n){return new t.Point(this.x/n,this.y/n)},negate:function(){return new t.Point(-this.x,-this.y)},distanceTo:function(n){return Math.sqrt(Math.pow(this.x-n.x,2)+Math.pow(this.y-n.y,2))},squaredDistanceTo:function(n){return Math.pow(this.x-n.x,2)+Math.pow(this.y-n.y,2)},apply:function(n){return new t.Point(n(this.x),n(this.y))},equals:function(n){return n instanceof t.Point&&this.x===n.x&&this.y===n.y},rotate:function(n,r){r=r||new t.Point(0,0);var s,o;if(n%90===0){var a=t.positiveModulo(n,360);switch(a){case 0:s=1,o=0;break;case 90:s=0,o=1;break;case 180:s=-1,o=0;break;case 270:s=0,o=-1;break}}else{var l=n*Math.PI/180;s=Math.cos(l),o=Math.sin(l)}var c=s*(this.x-r.x)-o*(this.y-r.y)+r.x,u=o*(this.x-r.x)+s*(this.y-r.y)+r.y;return new t.Point(c,u)},toString:function(){return"("+Math.round(this.x*100)/100+","+Math.round(this.y*100)/100+")"}}}(e),function(t){t.TileSource=function(r,s,o,a,l,c){var u=this,d=arguments,h,f;if(t.isPlainObject(r)?h=r:h={width:d[0],height:d[1],tileSize:d[2],tileOverlap:d[3],minLevel:d[4],maxLevel:d[5]},t.EventSource.call(this),t.extend(!0,this,h),!this.success){for(f=0;f<arguments.length;f++)if(t.isFunction(arguments[f])){this.success=arguments[f];break}}this.success&&this.addHandler("ready",function(p){u.success(p)}),t.type(arguments[0])==="string"&&(this.url=arguments[0]),this.url?(this.aspectRatio=1,this.dimensions=new t.Point(10,10),this._tileWidth=0,this._tileHeight=0,this.tileOverlap=0,this.minLevel=0,this.maxLevel=0,this.ready=!1,this.getImageInfo(this.url)):(this.ready=!0,this.aspectRatio=h.width&&h.height?h.width/h.height:1,this.dimensions=new t.Point(h.width,h.height),this.tileSize?(this._tileWidth=this._tileHeight=this.tileSize,delete this.tileSize):(this.tileWidth?(this._tileWidth=this.tileWidth,delete this.tileWidth):this._tileWidth=0,this.tileHeight?(this._tileHeight=this.tileHeight,delete this.tileHeight):this._tileHeight=0),this.tileOverlap=h.tileOverlap?h.tileOverlap:0,this.minLevel=h.minLevel?h.minLevel:0,this.maxLevel=h.maxLevel!==void 0&&h.maxLevel!==null?h.maxLevel:h.width&&h.height?Math.ceil(Math.log(Math.max(h.width,h.height))/Math.log(2)):0,this.success&&t.isFunction(this.success)&&this.success(this))},t.TileSource.prototype={getTileSize:function(r){return t.console.error("[TileSource.getTileSize] is deprecated. Use TileSource.getTileWidth() and TileSource.getTileHeight() instead"),this._tileWidth},getTileWidth:function(r){return this._tileWidth?this._tileWidth:this.getTileSize(r)},getTileHeight:function(r){return this._tileHeight?this._tileHeight:this.getTileSize(r)},setMaxLevel:function(r){this.maxLevel=r,this._memoizeLevelScale()},getLevelScale:function(r){return this._memoizeLevelScale(),this.getLevelScale(r)},_memoizeLevelScale:function(){var r={},s;for(s=0;s<=this.maxLevel;s++)r[s]=1/Math.pow(2,this.maxLevel-s);this.getLevelScale=function(o){return r[o]}},getNumTiles:function(r){var s=this.getLevelScale(r),o=Math.ceil(s*this.dimensions.x/this.getTileWidth(r)),a=Math.ceil(s*this.dimensions.y/this.getTileHeight(r));return new t.Point(o,a)},getPixelRatio:function(r){var s=this.dimensions.times(this.getLevelScale(r)),o=1/s.x*t.pixelDensityRatio,a=1/s.y*t.pixelDensityRatio;return new t.Point(o,a)},getClosestLevel:function(){var r,s;for(r=this.minLevel+1;r<=this.maxLevel&&(s=this.getNumTiles(r),!(s.x>1||s.y>1));r++);return r-1},getTileAtPoint:function(r,s){var o=s.x>=0&&s.x<=1&&s.y>=0&&s.y<=1/this.aspectRatio;t.console.assert(o,"[TileSource.getTileAtPoint] must be called with a valid point.");var a=this.dimensions.x*this.getLevelScale(r),l=s.x*a,c=s.y*a,u=Math.floor(l/this.getTileWidth(r)),d=Math.floor(c/this.getTileHeight(r));s.x>=1&&(u=this.getNumTiles(r).x-1);var h=1e-15;return s.y>=1/this.aspectRatio-h&&(d=this.getNumTiles(r).y-1),new t.Point(u,d)},getTileBounds:function(r,s,o,a){var l=this.dimensions.times(this.getLevelScale(r)),c=this.getTileWidth(r),u=this.getTileHeight(r),d=s===0?0:c*s-this.tileOverlap,h=o===0?0:u*o-this.tileOverlap,f=c+(s===0?1:2)*this.tileOverlap,p=u+(o===0?1:2)*this.tileOverlap,g=1/l.x;return f=Math.min(f,l.x-d),p=Math.min(p,l.y-h),a?new t.Rect(0,0,f,p):new t.Rect(d*g,h*g,f*g,p*g)},getImageInfo:function(r){var s=this,o,a,l,c,u,d,h;r&&(u=r.split("/"),d=u[u.length-1],h=d.lastIndexOf("."),h>-1&&(u[u.length-1]=d.slice(0,h)));var f=null;if(this.splitHashDataForPost){var p=r.indexOf("#");p!==-1&&(f=r.substring(p+1),r=r.substr(0,p))}a=function(g){typeof g=="string"&&(g=t.parseXml(g));var m=t.TileSource.determineType(s,g,r);if(!m){s.raiseEvent("open-failed",{message:"Unable to load TileSource",source:r});return}c=m.prototype.configure.apply(s,[g,r,f]),c.ajaxWithCredentials===void 0&&(c.ajaxWithCredentials=s.ajaxWithCredentials),l=new m(c),s.ready=!0,s.raiseEvent("ready",{tileSource:l})},r.match(/\.js$/)?(o=r.split("/").pop().replace(".js",""),t.jsonp({url:r,async:!1,callbackName:o,callback:a})):t.makeAjaxRequest({url:r,postData:f,withCredentials:this.ajaxWithCredentials,headers:this.ajaxHeaders,success:function(g){var m=n(g);a(m)},error:function(g,m){var v;try{v="HTTP "+g.status+" attempting to load TileSource: "+r}catch{var y;typeof m>"u"||!m.toString?y="Unknown error":y=m.toString(),v=y+" attempting to load TileSource: "+r}t.console.error(v),s.raiseEvent("open-failed",{message:v,source:r,postData:f})}})},supports:function(r,s){return!1},configure:function(r,s,o){throw new Error("Method not implemented.")},getTileUrl:function(r,s,o){throw new Error("Method not implemented.")},getTilePostData:function(r,s,o){return null},getTileAjaxHeaders:function(r,s,o){return{}},getTileHashKey:function(r,s,o,a,l,c){function u(d){return l?d+"+"+JSON.stringify(l):d}return u(typeof a!="string"?r+"/"+s+"_"+o:a)},tileExists:function(r,s,o){var a=this.getNumTiles(r);return r>=this.minLevel&&r<=this.maxLevel&&s>=0&&o>=0&&s<a.x&&o<a.y},hasTransparency:function(r,s,o,a){return!!r||s.match(".png")},downloadTileStart:function(r){var s=r.userData,o=new Image;s.image=o,s.request=null;var a=function(l){if(!o){r.finish(null,s.request,"Image load failed: undefined Image instance.");return}o.onload=o.onerror=o.onabort=null,r.finish(l?null:o,s.request,l)};o.onload=function(){a()},o.onabort=o.onerror=function(){a("Image load aborted.")},r.loadWithAjax?s.request=t.makeAjaxRequest({url:r.src,withCredentials:r.ajaxWithCredentials,headers:r.ajaxHeaders,responseType:"arraybuffer",postData:r.postData,success:function(l){var c;try{c=new window.Blob([l.response])}catch(h){var u=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder;if(h.name==="TypeError"&&u){var d=new u;d.append(l.response),c=d.getBlob()}}c.size===0?a("Empty image response."):o.src=(window.URL||window.webkitURL).createObjectURL(c)},error:function(l){a("Image load aborted - XHR error")}}):(r.crossOriginPolicy!==!1&&(o.crossOrigin=r.crossOriginPolicy),o.src=r.src)},downloadTileAbort:function(r){r.userData.request&&r.userData.request.abort();var s=r.userData.image;r.userData.image&&(s.onload=s.onerror=s.onabort=null)},createTileCache:function(r,s,o){r._data=s},destroyTileCache:function(r){r._data=null,r._renderedContext=null},getTileCacheData:function(r){return r._data},getTileCacheDataAsImage:function(r){return r._data},getTileCacheDataAsContext2D:function(r){if(!r._renderedContext){var s=document.createElement("canvas");s.width=r._data.width,s.height=r._data.height,r._renderedContext=s.getContext("2d"),r._renderedContext.drawImage(r._data,0,0),r._data=null}return r._renderedContext}},t.extend(!0,t.TileSource.prototype,t.EventSource.prototype);function n(r){var s=r.responseText,o=r.status,a,l;if(r){if(r.status!==200&&r.status!==0)throw o=r.status,a=o===404?"Not Found":r.statusText,new Error(t.getString("Errors.Status",o,a))}else throw new Error(t.getString("Errors.Security"));if(s.match(/^\s*<.*/))try{l=r.responseXML&&r.responseXML.documentElement?r.responseXML:t.parseXml(s)}catch{l=r.responseText}else if(s.match(/\s*[{[].*/))try{l=t.parseJSON(s)}catch{l=s}else l=s;return l}t.TileSource.determineType=function(r,s,o){var a;for(a in e)if(a.match(/.+TileSource$/)&&t.isFunction(e[a])&&t.isFunction(e[a].prototype.supports)&&e[a].prototype.supports.call(r,s,o))return e[a];return t.console.error("No TileSource was able to open %s %s",o,s),null}}(e),function(t){t.DziTileSource=function(s,o,a,l,c,u,d,h,f){var p,g,m,v;if(t.isPlainObject(s)?v=s:v={width:arguments[0],height:arguments[1],tileSize:arguments[2],tileOverlap:arguments[3],tilesUrl:arguments[4],fileFormat:arguments[5],displayRects:arguments[6],minLevel:arguments[7],maxLevel:arguments[8]},this._levelRects={},this.tilesUrl=v.tilesUrl,this.fileFormat=v.fileFormat,this.displayRects=v.displayRects,this.displayRects)for(p=this.displayRects.length-1;p>=0;p--)for(g=this.displayRects[p],m=g.minLevel;m<=g.maxLevel;m++)this._levelRects[m]||(this._levelRects[m]=[]),this._levelRects[m].push(g);t.TileSource.apply(this,[v])},t.extend(t.DziTileSource.prototype,t.TileSource.prototype,{supports:function(s,o){var a;return s.Image?a=s.Image.xmlns:s.documentElement&&(s.documentElement.localName==="Image"||s.documentElement.tagName==="Image")&&(a=s.documentElement.namespaceURI),a=(a||"").toLowerCase(),a.indexOf("schemas.microsoft.com/deepzoom/2008")!==-1||a.indexOf("schemas.microsoft.com/deepzoom/2009")!==-1},configure:function(s,o,a){var l;return t.isPlainObject(s)?l=r(this,s):l=n(this,s),o&&!l.tilesUrl&&(l.tilesUrl=o.replace(/([^/]+?)(\.(dzi|xml|js)?(\?[^/]*)?)?\/?$/,"$1_files/"),o.search(/\.(dzi|xml|js)\?/)!==-1?l.queryParams=o.match(/\?.*/):l.queryParams=""),l},getTileUrl:function(s,o,a){return[this.tilesUrl,s,"/",o,"_",a,".",this.fileFormat,this.queryParams].join("")},tileExists:function(s,o,a){var l=this._levelRects[s],c,u,d,h,f,p,g;if(this.minLevel&&s<this.minLevel||this.maxLevel&&s>this.maxLevel)return!1;if(!l||!l.length)return!0;for(g=l.length-1;g>=0;g--)if(c=l[g],!(s<c.minLevel||s>c.maxLevel)&&(u=this.getLevelScale(s),d=c.x*u,h=c.y*u,f=d+c.width*u,p=h+c.height*u,d=Math.floor(d/this._tileWidth),h=Math.floor(h/this._tileWidth),f=Math.ceil(f/this._tileWidth),p=Math.ceil(p/this._tileWidth),d<=o&&o<f&&h<=a&&a<p))return!0;return!1}});function n(s,o){if(!o||!o.documentElement)throw new Error(t.getString("Errors.Xml"));var a=o.documentElement,l=a.localName||a.tagName,c=o.documentElement.namespaceURI,u=null,d=[],h,f,p,g,m;if(l==="Image")try{if(g=a.getElementsByTagName("Size")[0],g===void 0&&(g=a.getElementsByTagNameNS(c,"Size")[0]),u={Image:{xmlns:"http://schemas.microsoft.com/deepzoom/2008",Url:a.getAttribute("Url"),Format:a.getAttribute("Format"),DisplayRect:null,Overlap:parseInt(a.getAttribute("Overlap"),10),TileSize:parseInt(a.getAttribute("TileSize"),10),Size:{Height:parseInt(g.getAttribute("Height"),10),Width:parseInt(g.getAttribute("Width"),10)}}},!t.imageFormatSupported(u.Image.Format))throw new Error(t.getString("Errors.ImageFormat",u.Image.Format.toUpperCase()));for(h=a.getElementsByTagName("DisplayRect"),h===void 0&&(h=a.getElementsByTagNameNS(c,"DisplayRect")[0]),m=0;m<h.length;m++)f=h[m],p=f.getElementsByTagName("Rect")[0],p===void 0&&(p=f.getElementsByTagNameNS(c,"Rect")[0]),d.push({Rect:{X:parseInt(p.getAttribute("X"),10),Y:parseInt(p.getAttribute("Y"),10),Width:parseInt(p.getAttribute("Width"),10),Height:parseInt(p.getAttribute("Height"),10),MinLevel:parseInt(f.getAttribute("MinLevel"),10),MaxLevel:parseInt(f.getAttribute("MaxLevel"),10)}});return d.length&&(u.Image.DisplayRect=d),r(s,u)}catch(S){throw S instanceof Error?S:new Error(t.getString("Errors.Dzi"))}else{if(l==="Collection")throw new Error(t.getString("Errors.Dzc"));if(l==="Error"){var v=a.getElementsByTagName("Message")[0],y=v.firstChild.nodeValue;throw new Error(y)}}throw new Error(t.getString("Errors.Dzi"))}function r(s,o){var a=o.Image,l=a.Url,c=a.Format,u=a.Size,d=a.DisplayRect||[],h=parseInt(u.Width,10),f=parseInt(u.Height,10),p=parseInt(a.TileSize,10),g=parseInt(a.Overlap,10),m=[],v,y;for(y=0;y<d.length;y++)v=d[y].Rect,m.push(new t.DisplayRect(parseInt(v.X,10),parseInt(v.Y,10),parseInt(v.Width,10),parseInt(v.Height,10),parseInt(v.MinLevel,10),parseInt(v.MaxLevel,10)));return t.extend(!0,{width:h,height:f,tileSize:p,tileOverlap:g,minLevel:null,maxLevel:null,tilesUrl:l,fileFormat:c,displayRects:m},o)}}(e),function(t){t.IIIFTileSource=function(a){if(t.extend(!0,this,a),this._id=this["@id"]||this.id||this.identifier||null,!(this.height&&this.width&&this._id))throw new Error("IIIF required parameters (width, height, or id) not provided.");if(a.tileSizePerScaleFactor={},this.tileFormat=this.tileFormat||"jpg",this.version=a.version,this.tile_width&&this.tile_height)a.tileWidth=this.tile_width,a.tileHeight=this.tile_height;else if(this.tile_width)a.tileSize=this.tile_width;else if(this.tile_height)a.tileSize=this.tile_height;else if(this.tiles)if(this.tiles.length===1)a.tileWidth=this.tiles[0].width,a.tileHeight=this.tiles[0].height||this.tiles[0].width,this.scale_factors=this.tiles[0].scaleFactors;else{this.scale_factors=[];for(var l=0;l<this.tiles.length;l++)for(var c=0;c<this.tiles[l].scaleFactors.length;c++){var u=this.tiles[l].scaleFactors[c];this.scale_factors.push(u),a.tileSizePerScaleFactor[u]={width:this.tiles[l].width,height:this.tiles[l].height||this.tiles[l].width}}}else if(n(a)){for(var d=Math.min(this.height,this.width),h=[256,512,1024],f=[],p=0;p<h.length;p++)h[p]<=d&&f.push(h[p]);f.length>0?a.tileSize=Math.max.apply(null,f):a.tileSize=d}else this.sizes&&this.sizes.length>0?(this.emulateLegacyImagePyramid=!0,a.levels=r(this),t.extend(!0,a,{width:a.levels[a.levels.length-1].width,height:a.levels[a.levels.length-1].height,tileSize:Math.max(a.height,a.width),tileOverlap:0,minLevel:0,maxLevel:a.levels.length-1}),this.levels=a.levels):t.console.error("Nothing in the info.json to construct image pyramids from");if(!a.maxLevel&&!this.emulateLegacyImagePyramid)if(!this.scale_factors)a.maxLevel=Number(Math.round(Math.log(Math.max(this.width,this.height),2)));else{var g=Math.max.apply(null,this.scale_factors);a.maxLevel=Math.round(Math.log(g)*Math.LOG2E)}if(this.sizes){var m=this.sizes.length;(m===a.maxLevel||m===a.maxLevel+1)&&(this.levelSizes=this.sizes.slice().sort(function(v,y){return v.width-y.width}),m===a.maxLevel&&this.levelSizes.push({width:this.width,height:this.height}))}t.TileSource.apply(this,[a])},t.extend(t.IIIFTileSource.prototype,t.TileSource.prototype,{supports:function(a,l){return a.protocol&&a.protocol==="http://iiif.io/api/image"||a["@context"]&&(a["@context"]==="http://library.stanford.edu/iiif/image-api/1.1/context.json"||a["@context"]==="http://iiif.io/api/image/1/context.json")||a.profile&&a.profile.indexOf("http://library.stanford.edu/iiif/image-api/compliance.html")===0||a.identifier&&a.width&&a.height?!0:!!(a.documentElement&&a.documentElement.tagName==="info"&&a.documentElement.namespaceURI==="http://library.stanford.edu/iiif/image-api/ns/")},configure:function(a,l,c){if(t.isPlainObject(a)){if(!a["@context"])a["@context"]="http://iiif.io/api/image/1.0/context.json",a["@id"]=l.replace("/info.json",""),a.version=1;else{var d=a["@context"];if(Array.isArray(d)){for(var h=0;h<d.length;h++)if(typeof d[h]=="string"&&(/^http:\/\/iiif\.io\/api\/image\/[1-3]\/context\.json$/.test(d[h])||d[h]==="http://library.stanford.edu/iiif/image-api/1.1/context.json")){d=d[h];break}}switch(d){case"http://iiif.io/api/image/1/context.json":case"http://library.stanford.edu/iiif/image-api/1.1/context.json":a.version=1;break;case"http://iiif.io/api/image/2/context.json":a.version=2;break;case"http://iiif.io/api/image/3/context.json":a.version=3;break;default:t.console.error("Data has a @context property which contains no known IIIF context URI.")}}if(a.preferredFormats){for(var f=0;f<a.preferredFormats.length;f++)if(e.imageFormatSupported(a.preferredFormats[f])){a.tileFormat=a.preferredFormats[f];break}}return a}else{var u=s(a);return u["@context"]="http://iiif.io/api/image/1.0/context.json",u["@id"]=l.replace("/info.xml",""),u.version=1,u}},getTileWidth:function(a){if(this.emulateLegacyImagePyramid)return t.TileSource.prototype.getTileWidth.call(this,a);var l=Math.pow(2,this.maxLevel-a);return this.tileSizePerScaleFactor&&this.tileSizePerScaleFactor[l]?this.tileSizePerScaleFactor[l].width:this._tileWidth},getTileHeight:function(a){if(this.emulateLegacyImagePyramid)return t.TileSource.prototype.getTileHeight.call(this,a);var l=Math.pow(2,this.maxLevel-a);return this.tileSizePerScaleFactor&&this.tileSizePerScaleFactor[l]?this.tileSizePerScaleFactor[l].height:this._tileHeight},getLevelScale:function(a){if(this.emulateLegacyImagePyramid){var l=NaN;return this.levels.length>0&&a>=this.minLevel&&a<=this.maxLevel&&(l=this.levels[a].width/this.levels[this.maxLevel].width),l}return t.TileSource.prototype.getLevelScale.call(this,a)},getNumTiles:function(a){if(this.emulateLegacyImagePyramid){var l=this.getLevelScale(a);return l?new t.Point(1,1):new t.Point(0,0)}if(this.levelSizes){var c=this.levelSizes[a],u=Math.ceil(c.width/this.getTileWidth(a)),d=Math.ceil(c.height/this.getTileHeight(a));return new t.Point(u,d)}else return t.TileSource.prototype.getNumTiles.call(this,a)},getTileAtPoint:function(a,l){if(this.emulateLegacyImagePyramid)return new t.Point(0,0);if(this.levelSizes){var c=l.x>=0&&l.x<=1&&l.y>=0&&l.y<=1/this.aspectRatio;t.console.assert(c,"[TileSource.getTileAtPoint] must be called with a valid point.");var u=this.levelSizes[a].width,d=l.x*u,h=l.y*u,f=Math.floor(d/this.getTileWidth(a)),p=Math.floor(h/this.getTileHeight(a));l.x>=1&&(f=this.getNumTiles(a).x-1);var g=1e-15;return l.y>=1/this.aspectRatio-g&&(p=this.getNumTiles(a).y-1),new t.Point(f,p)}return t.TileSource.prototype.getTileAtPoint.call(this,a,l)},getTileUrl:function(a,l,c){if(this.emulateLegacyImagePyramid){var u=null;return this.levels.length>0&&a>=this.minLevel&&a<=this.maxLevel&&(u=this.levels[a].url),u}var d="0",h=Math.pow(.5,this.maxLevel-a),f,p,g,m,v,y,S,x,E,C,b,I,D,P,k,N;return this.levelSizes?(f=this.levelSizes[a].width,p=this.levelSizes[a].height):(f=Math.ceil(this.width*h),p=Math.ceil(this.height*h)),g=this.getTileWidth(a),m=this.getTileHeight(a),v=Math.round(g/h),y=Math.round(m/h),this.version===1?k="native."+this.tileFormat:k="default."+this.tileFormat,f<g&&p<m?(this.version===2&&f===this.width?I="full":this.version===3&&f===this.width&&p===this.height?I="max":this.version===3?I=f+","+p:I=f+",",S="full"):(x=l*v,E=c*y,C=Math.min(v,this.width-x),b=Math.min(y,this.height-E),l===0&&c===0&&C===this.width&&b===this.height?S="full":S=[x,E,C,b].join(","),D=Math.min(g,f-l*g),P=Math.min(m,p-c*m),this.version===2&&D===this.width?I="full":this.version===3&&D===this.width&&P===this.height?I="max":this.version===3?I=D+","+P:I=D+","),N=[this._id,S,I,d,k].join("/"),N},__testonly__:{canBeTiled:n,constructLevels:r}});function n(a){var l=["http://library.stanford.edu/iiif/image-api/compliance.html#level0","http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0","http://iiif.io/api/image/2/level0.json","level0","https://iiif.io/api/image/3/level0.json"],c=Array.isArray(a.profile)?a.profile[0]:a.profile,u=l.indexOf(c)!==-1,d=!1;return a.version===2&&a.profile.length>1&&a.profile[1].supports&&(d=a.profile[1].supports.indexOf("sizeByW")!==-1),a.version===3&&a.extraFeatures&&(d=a.extraFeatures.indexOf("sizeByWh")!==-1),!u||d}function r(a){for(var l=[],c=0;c<a.sizes.length;c++)l.push({url:a._id+"/full/"+a.sizes[c].width+","+(a.version===3?a.sizes[c].height:"")+"/0/default."+a.tileFormat,width:a.sizes[c].width,height:a.sizes[c].height});return l.sort(function(u,d){return u.width-d.width})}function s(a){if(!a||!a.documentElement)throw new Error(t.getString("Errors.Xml"));var l=a.documentElement,c=l.tagName,u=null;if(c==="info")try{return u={},o(l,u),u}catch(d){throw d instanceof Error?d:new Error(t.getString("Errors.IIIF"))}throw new Error(t.getString("Errors.IIIF"))}function o(a,l,c){var u,d;if(a.nodeType===3&&c)d=a.nodeValue.trim(),d.match(/^\d*$/)&&(d=Number(d)),l[c]?(t.isArray(l[c])||(l[c]=[l[c]]),l[c].push(d)):l[c]=d;else if(a.nodeType===1)for(u=0;u<a.childNodes.length;u++)o(a.childNodes[u],l,a.nodeName)}}(e),function(t){t.OsmTileSource=function(n,r,s,o,a){var l;t.isPlainObject(n)?l=n:l={width:arguments[0],height:arguments[1],tileSize:arguments[2],tileOverlap:arguments[3],tilesUrl:arguments[4]},(!l.width||!l.height)&&(l.width=65572864,l.height=65572864),l.tileSize||(l.tileSize=256,l.tileOverlap=0),l.tilesUrl||(l.tilesUrl="http://tile.openstreetmap.org/"),l.minLevel=8,t.TileSource.apply(this,[l])},t.extend(t.OsmTileSource.prototype,t.TileSource.prototype,{supports:function(n,r){return n.type&&n.type==="openstreetmaps"},configure:function(n,r,s){return n},getTileUrl:function(n,r,s){return this.tilesUrl+(n-8)+"/"+r+"/"+s+".png"}})}(e),function(t){t.TmsTileSource=function(n,r,s,o,a){var l;t.isPlainObject(n)?l=n:l={width:arguments[0],height:arguments[1],tileSize:arguments[2],tileOverlap:arguments[3],tilesUrl:arguments[4]};var c=Math.ceil(l.width/256)*256,u=Math.ceil(l.height/256)*256,d;c>u?d=c/256:d=u/256,l.maxLevel=Math.ceil(Math.log(d)/Math.log(2))-1,l.tileSize=256,l.width=c,l.height=u,t.TileSource.apply(this,[l])},t.extend(t.TmsTileSource.prototype,t.TileSource.prototype,{supports:function(n,r){return n.type&&n.type==="tiledmapservice"},configure:function(n,r,s){return n},getTileUrl:function(n,r,s){var o=this.getNumTiles(n).y-1;return this.tilesUrl+n+"/"+r+"/"+(o-s)+".png"}})}(e),function(t){t.ZoomifyTileSource=function(n){typeof n.tileSize>"u"&&(n.tileSize=256),typeof n.fileFormat>"u"&&(n.fileFormat="jpg",this.fileFormat=n.fileFormat);var r={x:n.width,y:n.height};for(n.imageSizes=[{x:n.width,y:n.height}],n.gridSize=[this._getGridSize(n.width,n.height,n.tileSize)];parseInt(r.x,10)>n.tileSize||parseInt(r.y,10)>n.tileSize;)r.x=Math.floor(r.x/2),r.y=Math.floor(r.y/2),n.imageSizes.push({x:r.x,y:r.y}),n.gridSize.push(this._getGridSize(r.x,r.y,n.tileSize));n.imageSizes.reverse(),n.gridSize.reverse(),n.minLevel=0,n.maxLevel=n.gridSize.length-1,e.TileSource.apply(this,[n])},t.extend(t.ZoomifyTileSource.prototype,t.TileSource.prototype,{_getGridSize:function(n,r,s){return{x:Math.ceil(n/s),y:Math.ceil(r/s)}},_calculateAbsoluteTileNumber:function(n,r,s){for(var o=0,a={},l=0;l<n;l++)a=this.gridSize[l],o+=a.x*a.y;return a=this.gridSize[n],o+=a.x*s+r,o},supports:function(n,r){return n.type&&n.type==="zoomifytileservice"},configure:function(n,r,s){return n},getTileUrl:function(n,r,s){var o=0,a=this._calculateAbsoluteTileNumber(n,r,s);return o=Math.floor(a/256),this.tilesUrl+"TileGroup"+o+"/"+n+"-"+r+"-"+s+"."+this.fileFormat}})}(e),function(t){t.LegacyTileSource=function(o){var a,l,c;t.isArray(o)&&(a={type:"legacy-image-pyramid",levels:o}),a.levels=n(a.levels),a.levels.length>0?(l=a.levels[a.levels.length-1].width,c=a.levels[a.levels.length-1].height):(l=0,c=0,t.console.error("No supported image formats found")),t.extend(!0,a,{width:l,height:c,tileSize:Math.max(c,l),tileOverlap:0,minLevel:0,maxLevel:a.levels.length>0?a.levels.length-1:0}),t.TileSource.apply(this,[a]),this.levels=a.levels},t.extend(t.LegacyTileSource.prototype,t.TileSource.prototype,{supports:function(o,a){return o.type&&o.type==="legacy-image-pyramid"||o.documentElement&&o.documentElement.getAttribute("type")==="legacy-image-pyramid"},configure:function(o,a,l){var c;return t.isPlainObject(o)?c=s(this,o):c=r(this,o),c},getLevelScale:function(o){var a=NaN;return this.levels.length>0&&o>=this.minLevel&&o<=this.maxLevel&&(a=this.levels[o].width/this.levels[this.maxLevel].width),a},getNumTiles:function(o){var a=this.getLevelScale(o);return a?new t.Point(1,1):new t.Point(0,0)},getTileUrl:function(o,a,l){var c=null;return this.levels.length>0&&o>=this.minLevel&&o<=this.maxLevel&&(c=this.levels[o].url),c}});function n(o){var a=[],l,c;for(c=0;c<o.length;c++)l=o[c],l.height&&l.width&&l.url?a.push({url:l.url,width:Number(l.width),height:Number(l.height)}):t.console.error("Unsupported image format: %s",l.url?l.url:"<no URL>");return a.sort(function(u,d){return u.height-d.height})}function r(o,a){if(!a||!a.documentElement)throw new Error(t.getString("Errors.Xml"));var l=a.documentElement,c=l.tagName,u=null,d=[],h,f;if(c==="image")try{for(u={type:l.getAttribute("type"),levels:[]},d=l.getElementsByTagName("level"),f=0;f<d.length;f++)h=d[f],u.levels.push({url:h.getAttribute("url"),width:parseInt(h.getAttribute("width"),10),height:parseInt(h.getAttribute("height"),10)});return s(o,u)}catch(p){throw p instanceof Error?p:new Error("Unknown error parsing Legacy Image Pyramid XML.")}else{if(c==="collection")throw new Error("Legacy Image Pyramid Collections not yet supported.");if(c==="error")throw new Error("Error: "+a)}throw new Error("Unknown element "+c)}function s(o,a){return a.levels}}(e),function(t){t.ImageTileSource=function(n){n=t.extend({buildPyramid:!0,crossOriginPolicy:!1,ajaxWithCredentials:!1,useCanvas:!0},n),t.TileSource.apply(this,[n])},t.extend(t.ImageTileSource.prototype,t.TileSource.prototype,{supports:function(n,r){return n.type&&n.type==="image"},configure:function(n,r,s){return n},getImageInfo:function(n){var r=this._image=new Image,s=this;this.crossOriginPolicy&&(r.crossOrigin=this.crossOriginPolicy),this.ajaxWithCredentials&&(r.useCredentials=this.ajaxWithCredentials),t.addEvent(r,"load",function(){s.width=r.naturalWidth,s.height=r.naturalHeight,s.aspectRatio=s.width/s.height,s.dimensions=new t.Point(s.width,s.height),s._tileWidth=s.width,s._tileHeight=s.height,s.tileOverlap=0,s.minLevel=0,s.levels=s._buildLevels(),s.maxLevel=s.levels.length-1,s.ready=!0,s.raiseEvent("ready",{tileSource:s})}),t.addEvent(r,"error",function(){s.raiseEvent("open-failed",{message:"Error loading image at "+n,source:n})}),r.src=n},getLevelScale:function(n){var r=NaN;return n>=this.minLevel&&n<=this.maxLevel&&(r=this.levels[n].width/this.levels[this.maxLevel].width),r},getNumTiles:function(n){var r=this.getLevelScale(n);return r?new t.Point(1,1):new t.Point(0,0)},getTileUrl:function(n,r,s){var o=null;return n>=this.minLevel&&n<=this.maxLevel&&(o=this.levels[n].url),o},getContext2D:function(n,r,s){var o=null;return n>=this.minLevel&&n<=this.maxLevel&&(o=this.levels[n].context2D),o},destroy:function(){this._freeupCanvasMemory()},_buildLevels:function(){var n=[{url:this._image.src,width:this._image.naturalWidth,height:this._image.naturalHeight}];if(!this.buildPyramid||!t.supportsCanvas||!this.useCanvas)return delete this._image,n;var r=this._image.naturalWidth,s=this._image.naturalHeight,o=document.createElement("canvas"),a=o.getContext("2d");if(o.width=r,o.height=s,a.drawImage(this._image,0,0,r,s),n[0].context2D=a,delete this._image,t.isCanvasTainted(o))return n;for(;r>=2&&s>=2;){r=Math.floor(r/2),s=Math.floor(s/2);var l=document.createElement("canvas"),c=l.getContext("2d");l.width=r,l.height=s,c.drawImage(o,0,0,r,s),n.splice(0,0,{context2D:c,width:r,height:s}),o=l,a=c}return n},_freeupCanvasMemory:function(){for(var n=0;n<this.levels.length;n++)this.levels[n].context2D&&(this.levels[n].context2D.canvas.height=0,this.levels[n].context2D.canvas.width=0)}})}(e),function(t){t.TileSourceCollection=function(n,r,s,o){t.console.error("TileSourceCollection is deprecated; use World instead")}}(e),function(t){t.ButtonState={REST:0,GROUP:1,HOVER:2,DOWN:3},t.Button=function(c){var u=this;t.EventSource.call(this),t.extend(!0,this,{tooltip:null,srcRest:null,srcGroup:null,srcHover:null,srcDown:null,clickTimeThreshold:t.DEFAULT_SETTINGS.clickTimeThreshold,clickDistThreshold:t.DEFAULT_SETTINGS.clickDistThreshold,fadeDelay:0,fadeLength:2e3,onPress:null,onRelease:null,onClick:null,onEnter:null,onExit:null,onFocus:null,onBlur:null,userData:null},c),this.element=c.element||t.makeNeutralElement("div"),c.element||(this.imgRest=t.makeTransparentImage(this.srcRest),this.imgGroup=t.makeTransparentImage(this.srcGroup),this.imgHover=t.makeTransparentImage(this.srcHover),this.imgDown=t.makeTransparentImage(this.srcDown),this.imgRest.alt=this.imgGroup.alt=this.imgHover.alt=this.imgDown.alt=this.tooltip,t.setElementPointerEventsNone(this.imgRest),t.setElementPointerEventsNone(this.imgGroup),t.setElementPointerEventsNone(this.imgHover),t.setElementPointerEventsNone(this.imgDown),this.element.style.position="relative",t.setElementTouchActionNone(this.element),this.imgGroup.style.position=this.imgHover.style.position=this.imgDown.style.position="absolute",this.imgGroup.style.top=this.imgHover.style.top=this.imgDown.style.top="0px",this.imgGroup.style.left=this.imgHover.style.left=this.imgDown.style.left="0px",this.imgHover.style.visibility=this.imgDown.style.visibility="hidden",t.Browser.vendor===t.BROWSERS.FIREFOX&&t.Browser.version<3&&(this.imgGroup.style.top=this.imgHover.style.top=this.imgDown.style.top=""),this.element.appendChild(this.imgRest),this.element.appendChild(this.imgGroup),this.element.appendChild(this.imgHover),this.element.appendChild(this.imgDown)),this.addHandler("press",this.onPress),this.addHandler("release",this.onRelease),this.addHandler("click",this.onClick),this.addHandler("enter",this.onEnter),this.addHandler("exit",this.onExit),this.addHandler("focus",this.onFocus),this.addHandler("blur",this.onBlur),this.currentState=t.ButtonState.GROUP,this.fadeBeginTime=null,this.shouldFade=!1,this.element.style.display="inline-block",this.element.style.position="relative",this.element.title=this.tooltip,this.tracker=new t.MouseTracker({userData:"Button.tracker",element:this.element,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,enterHandler:function(d){d.insideElementPressed?(a(u,t.ButtonState.DOWN),u.raiseEvent("enter",{originalEvent:d.originalEvent})):d.buttonDownAny||a(u,t.ButtonState.HOVER)},focusHandler:function(d){u.tracker.enterHandler(d),u.raiseEvent("focus",{originalEvent:d.originalEvent})},leaveHandler:function(d){l(u,t.ButtonState.GROUP),d.insideElementPressed&&u.raiseEvent("exit",{originalEvent:d.originalEvent})},blurHandler:function(d){u.tracker.leaveHandler(d),u.raiseEvent("blur",{originalEvent:d.originalEvent})},pressHandler:function(d){a(u,t.ButtonState.DOWN),u.raiseEvent("press",{originalEvent:d.originalEvent})},releaseHandler:function(d){d.insideElementPressed&&d.insideElementReleased?(l(u,t.ButtonState.HOVER),u.raiseEvent("release",{originalEvent:d.originalEvent})):d.insideElementPressed?l(u,t.ButtonState.GROUP):a(u,t.ButtonState.HOVER)},clickHandler:function(d){d.quick&&u.raiseEvent("click",{originalEvent:d.originalEvent})},keyHandler:function(d){d.keyCode===13?(u.raiseEvent("click",{originalEvent:d.originalEvent}),u.raiseEvent("release",{originalEvent:d.originalEvent}),d.preventDefault=!0):d.preventDefault=!1}}),l(this,t.ButtonState.REST)},t.extend(t.Button.prototype,t.EventSource.prototype,{notifyGroupEnter:function(){a(this,t.ButtonState.GROUP)},notifyGroupExit:function(){l(this,t.ButtonState.REST)},disable:function(){this.notifyGroupExit(),this.element.disabled=!0,this.tracker.setTracking(!1),t.setElementOpacity(this.element,.2,!0)},enable:function(){this.element.disabled=!1,this.tracker.setTracking(!0),t.setElementOpacity(this.element,1,!0),this.notifyGroupEnter()},destroy:function(){this.imgRest&&(this.element.removeChild(this.imgRest),this.imgRest=null),this.imgGroup&&(this.element.removeChild(this.imgGroup),this.imgGroup=null),this.imgHover&&(this.element.removeChild(this.imgHover),this.imgHover=null),this.imgDown&&(this.element.removeChild(this.imgDown),this.imgDown=null),this.removeAllHandlers(),this.tracker.destroy(),this.element=null}});function n(c){t.requestAnimationFrame(function(){r(c)})}function r(c){var u,d,h;c.shouldFade&&(u=t.now(),d=u-c.fadeBeginTime,h=1-d/c.fadeLength,h=Math.min(1,h),h=Math.max(0,h),c.imgGroup&&t.setElementOpacity(c.imgGroup,h,!0),h>0&&n(c))}function s(c){c.shouldFade=!0,c.fadeBeginTime=t.now()+c.fadeDelay,window.setTimeout(function(){n(c)},c.fadeDelay)}function o(c){c.shouldFade=!1,c.imgGroup&&t.setElementOpacity(c.imgGroup,1,!0)}function a(c,u){c.element.disabled||(u>=t.ButtonState.GROUP&&c.currentState===t.ButtonState.REST&&(o(c),c.currentState=t.ButtonState.GROUP),u>=t.ButtonState.HOVER&&c.currentState===t.ButtonState.GROUP&&(c.imgHover&&(c.imgHover.style.visibility=""),c.currentState=t.ButtonState.HOVER),u>=t.ButtonState.DOWN&&c.currentState===t.ButtonState.HOVER&&(c.imgDown&&(c.imgDown.style.visibility=""),c.currentState=t.ButtonState.DOWN))}function l(c,u){c.element.disabled||(u<=t.ButtonState.HOVER&&c.currentState===t.ButtonState.DOWN&&(c.imgDown&&(c.imgDown.style.visibility="hidden"),c.currentState=t.ButtonState.HOVER),u<=t.ButtonState.GROUP&&c.currentState===t.ButtonState.HOVER&&(c.imgHover&&(c.imgHover.style.visibility="hidden"),c.currentState=t.ButtonState.GROUP),u<=t.ButtonState.REST&&c.currentState===t.ButtonState.GROUP&&(s(c),c.currentState=t.ButtonState.REST))}}(e),function(t){t.ButtonGroup=function(n){t.extend(!0,this,{buttons:[],clickTimeThreshold:t.DEFAULT_SETTINGS.clickTimeThreshold,clickDistThreshold:t.DEFAULT_SETTINGS.clickDistThreshold,labelText:""},n);var r=this.buttons.concat([]),s=this,o;if(this.element=n.element||t.makeNeutralElement("div"),!n.group)for(this.element.style.display="inline-block",o=0;o<r.length;o++)this.element.appendChild(r[o].element);t.setElementTouchActionNone(this.element),this.tracker=new t.MouseTracker({userData:"ButtonGroup.tracker",element:this.element,clickTimeThreshold:this.clickTimeThreshold,clickDistThreshold:this.clickDistThreshold,enterHandler:function(a){var l;for(l=0;l<s.buttons.length;l++)s.buttons[l].notifyGroupEnter()},leaveHandler:function(a){var l;if(!a.insideElementPressed)for(l=0;l<s.buttons.length;l++)s.buttons[l].notifyGroupExit()}})},t.ButtonGroup.prototype={addButton:function(n){this.buttons.push(n),this.element.appendChild(n.element)},emulateEnter:function(){this.tracker.enterHandler({eventSource:this.tracker})},emulateLeave:function(){this.tracker.leaveHandler({eventSource:this.tracker})},destroy:function(){for(;this.buttons.length;){var n=this.buttons.pop();this.element.removeChild(n.element),n.destroy()}this.tracker.destroy(),this.element=null}}}(e),function(t){t.Rect=function(n,r,s,o,a){this.x=typeof n=="number"?n:0,this.y=typeof r=="number"?r:0,this.width=typeof s=="number"?s:0,this.height=typeof o=="number"?o:0,this.degrees=typeof a=="number"?a:0,this.degrees=t.positiveModulo(this.degrees,360);var l,c;this.degrees>=270?(l=this.getTopRight(),this.x=l.x,this.y=l.y,c=this.height,this.height=this.width,this.width=c,this.degrees-=270):this.degrees>=180?(l=this.getBottomRight(),this.x=l.x,this.y=l.y,this.degrees-=180):this.degrees>=90&&(l=this.getBottomLeft(),this.x=l.x,this.y=l.y,c=this.height,this.height=this.width,this.width=c,this.degrees-=90)},t.Rect.fromSummits=function(n,r,s){var o=n.distanceTo(r),a=n.distanceTo(s),l=r.minus(n),c=Math.atan(l.y/l.x);return l.x<0?c+=Math.PI:l.y<0&&(c+=2*Math.PI),new t.Rect(n.x,n.y,o,a,c/Math.PI*180)},t.Rect.prototype={clone:function(){return new t.Rect(this.x,this.y,this.width,this.height,this.degrees)},getAspectRatio:function(){return this.width/this.height},getTopLeft:function(){return new t.Point(this.x,this.y)},getBottomRight:function(){return new t.Point(this.x+this.width,this.y+this.height).rotate(this.degrees,this.getTopLeft())},getTopRight:function(){return new t.Point(this.x+this.width,this.y).rotate(this.degrees,this.getTopLeft())},getBottomLeft:function(){return new t.Point(this.x,this.y+this.height).rotate(this.degrees,this.getTopLeft())},getCenter:function(){return new t.Point(this.x+this.width/2,this.y+this.height/2).rotate(this.degrees,this.getTopLeft())},getSize:function(){return new t.Point(this.width,this.height)},equals:function(n){return n instanceof t.Rect&&this.x===n.x&&this.y===n.y&&this.width===n.width&&this.height===n.height&&this.degrees===n.degrees},times:function(n){return new t.Rect(this.x*n,this.y*n,this.width*n,this.height*n,this.degrees)},translate:function(n){return new t.Rect(this.x+n.x,this.y+n.y,this.width,this.height,this.degrees)},union:function(n){var r=this.getBoundingBox(),s=n.getBoundingBox(),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),l=Math.max(r.x+r.width,s.x+s.width),c=Math.max(r.y+r.height,s.y+s.height);return new t.Rect(o,a,l-o,c-a)},intersection:function(n){var r=1e-10,s=[],o=this.getTopLeft();n.containsPoint(o,r)&&s.push(o);var a=this.getTopRight();n.containsPoint(a,r)&&s.push(a);var l=this.getBottomLeft();n.containsPoint(l,r)&&s.push(l);var c=this.getBottomRight();n.containsPoint(c,r)&&s.push(c);var u=n.getTopLeft();this.containsPoint(u,r)&&s.push(u);var d=n.getTopRight();this.containsPoint(d,r)&&s.push(d);var h=n.getBottomLeft();this.containsPoint(h,r)&&s.push(h);var f=n.getBottomRight();this.containsPoint(f,r)&&s.push(f);for(var p=this._getSegments(),g=n._getSegments(),m=0;m<p.length;m++)for(var v=p[m],y=0;y<g.length;y++){var S=g[y],x=E(v[0],v[1],S[0],S[1]);x&&s.push(x)}function E(N,B,K,q){var H=B.minus(N),X=q.minus(K),F=-X.x*H.y+H.x*X.y;if(F===0)return null;var U=(H.x*(N.y-K.y)-H.y*(N.x-K.x))/F,j=(X.x*(N.y-K.y)-X.y*(N.x-K.x))/F;return-r<=U&&U<=1-r&&-r<=j&&j<=1-r?new t.Point(N.x+j*H.x,N.y+j*H.y):null}if(s.length===0)return null;for(var C=s[0].x,b=s[0].x,I=s[0].y,D=s[0].y,P=1;P<s.length;P++){var k=s[P];k.x<C&&(C=k.x),k.x>b&&(b=k.x),k.y<I&&(I=k.y),k.y>D&&(D=k.y)}return new t.Rect(C,I,b-C,D-I)},_getSegments:function(){var n=this.getTopLeft(),r=this.getTopRight(),s=this.getBottomLeft(),o=this.getBottomRight();return[[n,r],[r,o],[o,s],[s,n]]},rotate:function(n,r){if(n=t.positiveModulo(n,360),n===0)return this.clone();r=r||this.getCenter();var s=this.getTopLeft().rotate(n,r),o=this.getTopRight().rotate(n,r),a=o.minus(s);a=a.apply(function(c){var u=1e-15;return Math.abs(c)<u?0:c});var l=Math.atan(a.y/a.x);return a.x<0?l+=Math.PI:a.y<0&&(l+=2*Math.PI),new t.Rect(s.x,s.y,this.width,this.height,l/Math.PI*180)},getBoundingBox:function(){if(this.degrees===0)return this.clone();var n=this.getTopLeft(),r=this.getTopRight(),s=this.getBottomLeft(),o=this.getBottomRight(),a=Math.min(n.x,r.x,s.x,o.x),l=Math.max(n.x,r.x,s.x,o.x),c=Math.min(n.y,r.y,s.y,o.y),u=Math.max(n.y,r.y,s.y,o.y);return new t.Rect(a,c,l-a,u-c)},getIntegerBoundingBox:function(){var n=this.getBoundingBox(),r=Math.floor(n.x),s=Math.floor(n.y),o=Math.ceil(n.width+n.x-r),a=Math.ceil(n.height+n.y-s);return new t.Rect(r,s,o,a)},containsPoint:function(n,r){r=r||0;var s=this.getTopLeft(),o=this.getTopRight(),a=this.getBottomLeft(),l=o.minus(s),c=a.minus(s);return(n.x-s.x)*l.x+(n.y-s.y)*l.y>=-r&&(n.x-o.x)*l.x+(n.y-o.y)*l.y<=r&&(n.x-s.x)*c.x+(n.y-s.y)*c.y>=-r&&(n.x-a.x)*c.x+(n.y-a.y)*c.y<=r},toString:function(){return"["+Math.round(this.x*100)/100+", "+Math.round(this.y*100)/100+", "+Math.round(this.width*100)/100+"x"+Math.round(this.height*100)/100+", "+Math.round(this.degrees*100)/100+"deg]"}}}(e),function(t){var n={};t.ReferenceStrip=function(h){var f=this,p=h.viewer,g=t.getElementSize(p.element),m,v,y;for(h.id||(h.id="referencestrip-"+t.now(),this.element=t.makeNeutralElement("div"),this.element.id=h.id,this.element.className="referencestrip"),h=t.extend(!0,{sizeRatio:t.DEFAULT_SETTINGS.referenceStripSizeRatio,position:t.DEFAULT_SETTINGS.referenceStripPosition,scroll:t.DEFAULT_SETTINGS.referenceStripScroll,clickTimeThreshold:t.DEFAULT_SETTINGS.clickTimeThreshold},h,{element:this.element}),t.extend(this,h),n[this.id]={animating:!1},this.minPixelRatio=this.viewer.minPixelRatio,this.element.tabIndex=0,v=this.element.style,v.marginTop="0px",v.marginRight="0px",v.marginBottom="0px",v.marginLeft="0px",v.left="0px",v.bottom="0px",v.border="0px",v.background="#000",v.position="relative",t.setElementTouchActionNone(this.element),t.setElementOpacity(this.element,.8),this.viewer=p,this.tracker=new t.MouseTracker({userData:"ReferenceStrip.tracker",element:this.element,clickHandler:t.delegate(this,r),dragHandler:t.delegate(this,s),scrollHandler:t.delegate(this,o),enterHandler:t.delegate(this,l),leaveHandler:t.delegate(this,c),keyDownHandler:t.delegate(this,u),keyHandler:t.delegate(this,d),preProcessEventHandler:function(S){S.eventType==="wheel"&&(S.preventDefault=!0)}}),h.width&&h.height?(this.element.style.width=h.width+"px",this.element.style.height=h.height+"px",p.addControl(this.element,{anchor:t.ControlAnchor.BOTTOM_LEFT})):h.scroll==="horizontal"?(this.element.style.width=g.x*h.sizeRatio*p.tileSources.length+12*p.tileSources.length+"px",this.element.style.height=g.y*h.sizeRatio+"px",p.addControl(this.element,{anchor:t.ControlAnchor.BOTTOM_LEFT})):(this.element.style.height=g.y*h.sizeRatio*p.tileSources.length+12*p.tileSources.length+"px",this.element.style.width=g.x*h.sizeRatio+"px",p.addControl(this.element,{anchor:t.ControlAnchor.TOP_LEFT})),this.panelWidth=g.x*this.sizeRatio+8,this.panelHeight=g.y*this.sizeRatio+8,this.panels=[],this.miniViewers={},y=0;y<p.tileSources.length;y++)m=t.makeNeutralElement("div"),m.id=this.element.id+"-"+y,m.style.width=f.panelWidth+"px",m.style.height=f.panelHeight+"px",m.style.display="inline",m.style.float="left",m.style.cssFloat="left",m.style.styleFloat="left",m.style.padding="2px",t.setElementTouchActionNone(m),t.setElementPointerEventsNone(m),this.element.appendChild(m),m.activePanel=!1,this.panels.push(m);a(this,this.scroll==="vertical"?g.y:g.x,0),this.setFocus(0)},t.ReferenceStrip.prototype={setFocus:function(h){var f=this.element.querySelector("#"+this.element.id+"-"+h),p=t.getElementSize(this.viewer.canvas),g=Number(this.element.style.width.replace("px","")),m=Number(this.element.style.height.replace("px","")),v=-Number(this.element.style.marginLeft.replace("px","")),y=-Number(this.element.style.marginTop.replace("px","")),S;this.currentSelected!==f&&(this.currentSelected&&(this.currentSelected.style.background="#000"),this.currentSelected=f,this.currentSelected.style.background="#999",this.scroll==="horizontal"?(S=Number(h)*(this.panelWidth+3),S>v+p.x-this.panelWidth?(S=Math.min(S,g-p.x),this.element.style.marginLeft=-S+"px",a(this,p.x,-S)):S<v&&(S=Math.max(0,S-p.x/2),this.element.style.marginLeft=-S+"px",a(this,p.x,-S))):(S=Number(h)*(this.panelHeight+3),S>y+p.y-this.panelHeight?(S=Math.min(S,m-p.y),this.element.style.marginTop=-S+"px",a(this,p.y,-S)):S<y&&(S=Math.max(0,S-p.y/2),this.element.style.marginTop=-S+"px",a(this,p.y,-S))),this.currentPage=h,l.call(this,{eventSource:this.tracker}))},update:function(){return!!n[this.id].animating},destroy:function(){if(this.miniViewers)for(var h in this.miniViewers)this.miniViewers[h].destroy();this.tracker.destroy(),this.element&&this.viewer.removeControl(this.element)}};function r(h){if(h.quick){var f;this.scroll==="horizontal"?f=Math.floor(h.position.x/(this.panelWidth+4)):f=Math.floor(h.position.y/this.panelHeight),this.viewer.goToPage(f)}this.element.focus()}function s(h){if(this.dragging=!0,this.element){var f=Number(this.element.style.marginLeft.replace("px","")),p=Number(this.element.style.marginTop.replace("px","")),g=Number(this.element.style.width.replace("px","")),m=Number(this.element.style.height.replace("px","")),v=t.getElementSize(this.viewer.canvas);this.scroll==="horizontal"?-h.delta.x>0?f>-(g-v.x)&&(this.element.style.marginLeft=f+h.delta.x*2+"px",a(this,v.x,f+h.delta.x*2)):-h.delta.x<0&&f<0&&(this.element.style.marginLeft=f+h.delta.x*2+"px",a(this,v.x,f+h.delta.x*2)):-h.delta.y>0?p>-(m-v.y)&&(this.element.style.marginTop=p+h.delta.y*2+"px",a(this,v.y,p+h.delta.y*2)):-h.delta.y<0&&p<0&&(this.element.style.marginTop=p+h.delta.y*2+"px",a(this,v.y,p+h.delta.y*2))}}function o(h){if(this.element){var f=Number(this.element.style.marginLeft.replace("px","")),p=Number(this.element.style.marginTop.replace("px","")),g=Number(this.element.style.width.replace("px","")),m=Number(this.element.style.height.replace("px","")),v=t.getElementSize(this.viewer.canvas);this.scroll==="horizontal"?h.scroll>0?f>-(g-v.x)&&(this.element.style.marginLeft=f-h.scroll*60+"px",a(this,v.x,f-h.scroll*60)):h.scroll<0&&f<0&&(this.element.style.marginLeft=f-h.scroll*60+"px",a(this,v.x,f-h.scroll*60)):h.scroll<0?p>v.y-m&&(this.element.style.marginTop=p+h.scroll*60+"px",a(this,v.y,p+h.scroll*60)):h.scroll>0&&p<0&&(this.element.style.marginTop=p+h.scroll*60+"px",a(this,v.y,p+h.scroll*60)),h.preventDefault=!0}}function a(h,f,p){var g,m,v,y,S,x;for(h.scroll==="horizontal"?g=h.panelWidth:g=h.panelHeight,m=Math.ceil(f/g)+5,v=Math.ceil((Math.abs(p)+f)/g)+1,m=v-m,m=m<0?0:m,S=m;S<v&&S<h.panels.length;S++)if(x=h.panels[S],!x.activePanel){var E,C=h.viewer.tileSources[S];C.referenceStripThumbnailUrl?E={type:"image",url:C.referenceStripThumbnailUrl}:E=C,y=new t.Viewer({id:x.id,tileSources:[E],element:x,navigatorSizeRatio:h.sizeRatio,showNavigator:!1,mouseNavEnabled:!1,showNavigationControl:!1,showSequenceControl:!1,immediateRender:!0,blendTime:0,animationTime:0,loadTilesWithAjax:h.viewer.loadTilesWithAjax,ajaxHeaders:h.viewer.ajaxHeaders,useCanvas:h.useCanvas}),t.setElementPointerEventsNone(y.canvas),t.setElementPointerEventsNone(y.container),y.innerTracker.setTracking(!1),y.outerTracker.setTracking(!1),h.miniViewers[x.id]=y,x.activePanel=!0}}function l(h){var f=h.eventSource.element;this.scroll==="horizontal"?f.style.marginBottom="0px":f.style.marginLeft="0px"}function c(h){var f=h.eventSource.element;this.scroll==="horizontal"?f.style.marginBottom="-"+t.getElementSize(f).y/2+"px":f.style.marginLeft="-"+t.getElementSize(f).x/2+"px"}function u(h){if(!h.ctrl&&!h.alt&&!h.meta)switch(h.keyCode){case 38:o.call(this,{eventSource:this.tracker,position:null,scroll:1,shift:null}),h.preventDefault=!0;break;case 40:o.call(this,{eventSource:this.tracker,position:null,scroll:-1,shift:null}),h.preventDefault=!0;break;case 37:o.call(this,{eventSource:this.tracker,position:null,scroll:-1,shift:null}),h.preventDefault=!0;break;case 39:o.call(this,{eventSource:this.tracker,position:null,scroll:1,shift:null}),h.preventDefault=!0;break;default:h.preventDefault=!1;break}else h.preventDefault=!1}function d(h){if(!h.ctrl&&!h.alt&&!h.meta)switch(h.keyCode){case 61:o.call(this,{eventSource:this.tracker,position:null,scroll:1,shift:null}),h.preventDefault=!0;break;case 45:o.call(this,{eventSource:this.tracker,position:null,scroll:-1,shift:null}),h.preventDefault=!0;break;case 48:case 119:case 87:o.call(this,{eventSource:this.tracker,position:null,scroll:1,shift:null}),h.preventDefault=!0;break;case 115:case 83:o.call(this,{eventSource:this.tracker,position:null,scroll:-1,shift:null}),h.preventDefault=!0;break;case 97:o.call(this,{eventSource:this.tracker,position:null,scroll:-1,shift:null}),h.preventDefault=!0;break;case 100:o.call(this,{eventSource:this.tracker,position:null,scroll:1,shift:null}),h.preventDefault=!0;break;default:h.preventDefault=!1;break}else h.preventDefault=!1}}(e),function(t){t.DisplayRect=function(n,r,s,o,a,l){t.Rect.apply(this,[n,r,s,o]),this.minLevel=a,this.maxLevel=l},t.extend(t.DisplayRect.prototype,t.Rect.prototype)}(e),function(t){t.Spring=function(r){var s=arguments;typeof r!="object"&&(r={initial:s.length&&typeof s[0]=="number"?s[0]:void 0,springStiffness:s.length>1?s[1].springStiffness:5,animationTime:s.length>1?s[1].animationTime:1.5}),t.console.assert(typeof r.springStiffness=="number"&&r.springStiffness!==0,"[OpenSeadragon.Spring] options.springStiffness must be a non-zero number"),t.console.assert(typeof r.animationTime=="number"&&r.animationTime>=0,"[OpenSeadragon.Spring] options.animationTime must be a number greater than or equal to 0"),r.exponential&&(this._exponential=!0,delete r.exponential),t.extend(!0,this,r),this.current={value:typeof this.initial=="number"?this.initial:this._exponential?0:1,time:t.now()},t.console.assert(!this._exponential||this.current.value!==0,"[OpenSeadragon.Spring] value must be non-zero for exponential springs"),this.start={value:this.current.value,time:this.current.time},this.target={value:this.current.value,time:this.current.time},this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},t.Spring.prototype={resetTo:function(r){t.console.assert(!this._exponential||r!==0,"[OpenSeadragon.Spring.resetTo] target must be non-zero for exponential springs"),this.start.value=this.target.value=this.current.value=r,this.start.time=this.target.time=this.current.time=t.now(),this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},springTo:function(r){t.console.assert(!this._exponential||r!==0,"[OpenSeadragon.Spring.springTo] target must be non-zero for exponential springs"),this.start.value=this.current.value,this.start.time=this.current.time,this.target.value=r,this.target.time=this.start.time+1e3*this.animationTime,this._exponential&&(this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value))},shiftBy:function(r){this.start.value+=r,this.target.value+=r,this._exponential&&(t.console.assert(this.target.value!==0&&this.start.value!==0,"[OpenSeadragon.Spring.shiftBy] spring value must be non-zero for exponential springs"),this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value))},setExponential:function(r){this._exponential=r,this._exponential&&(t.console.assert(this.current.value!==0&&this.target.value!==0&&this.start.value!==0,"[OpenSeadragon.Spring.setExponential] spring value must be non-zero for exponential springs"),this.start._logValue=Math.log(this.start.value),this.target._logValue=Math.log(this.target.value),this.current._logValue=Math.log(this.current.value))},update:function(){this.current.time=t.now();var r,s;this._exponential?(r=this.start._logValue,s=this.target._logValue):(r=this.start.value,s=this.target.value);var o=this.current.time>=this.target.time?s:r+(s-r)*n(this.springStiffness,(this.current.time-this.start.time)/(this.target.time-this.start.time)),a=this.current.value;return this._exponential?this.current.value=Math.exp(o):this.current.value=o,a!==this.current.value},isAtTargetValue:function(){return this.current.value===this.target.value}};function n(r,s){return(1-Math.exp(r*-s))/(1-Math.exp(-r))}}(e),function(t){t.ImageJob=function(r){t.extend(!0,this,{timeout:t.DEFAULT_SETTINGS.timeout,jobId:null,tries:0},r),this.data=null,this.userData={},this.errorMsg=null},t.ImageJob.prototype={start:function(){this.tries++;var r=this,s=this.abort;this.jobId=window.setTimeout(function(){r.finish(null,null,"Image load exceeded timeout ("+r.timeout+" ms)")},this.timeout),this.abort=function(){r.source.downloadTileAbort(r),typeof s=="function"&&s()},this.source.downloadTileStart(this)},finish:function(r,s,o){this.data=r,this.request=s,this.errorMsg=o,this.jobId&&window.clearTimeout(this.jobId),this.callback(this)}},t.ImageLoader=function(r){t.extend(!0,this,{jobLimit:t.DEFAULT_SETTINGS.imageLoaderLimit,timeout:t.DEFAULT_SETTINGS.timeout,jobQueue:[],failedTiles:[],jobsInProgress:0},r)},t.ImageLoader.prototype={addJob:function(r){if(!r.source){t.console.error("ImageLoader.prototype.addJob() requires [options.source]. TileSource since new API defines how images are fetched. Creating a dummy TileSource.");var s=t.TileSource.prototype;r.source={downloadTileStart:s.downloadTileStart,downloadTileAbort:s.downloadTileAbort}}var o=this,a=function(u){n(o,u,r.callback)},l={src:r.src,tile:r.tile||{},source:r.source,loadWithAjax:r.loadWithAjax,ajaxHeaders:r.loadWithAjax?r.ajaxHeaders:null,crossOriginPolicy:r.crossOriginPolicy,ajaxWithCredentials:r.ajaxWithCredentials,postData:r.postData,callback:a,abort:r.abort,timeout:this.timeout},c=new t.ImageJob(l);!this.jobLimit||this.jobsInProgress<this.jobLimit?(c.start(),this.jobsInProgress++):this.jobQueue.push(c)},clear:function(){for(var r=0;r<this.jobQueue.length;r++){var s=this.jobQueue[r];typeof s.abort=="function"&&s.abort()}this.jobQueue=[]}};function n(r,s,o){s.errorMsg!==""&&(s.data===null||s.data===void 0)&&s.tries<1+r.tileRetryMax&&r.failedTiles.push(s);var a;r.jobsInProgress--,(!r.jobLimit||r.jobsInProgress<r.jobLimit)&&r.jobQueue.length>0&&(a=r.jobQueue.shift(),a.start(),r.jobsInProgress++),r.tileRetryMax>0&&r.jobQueue.length===0&&(!r.jobLimit||r.jobsInProgress<r.jobLimit)&&r.failedTiles.length>0&&(a=r.failedTiles.shift(),setTimeout(function(){a.start()},r.tileRetryDelay),r.jobsInProgress++),o(s.data,s.errorMsg,s.request)}}(e),function(t){t.Tile=function(n,r,s,o,a,l,c,u,d,h,f,p){this.level=n,this.x=r,this.y=s,this.bounds=o,this.sourceBounds=h,this.exists=a,this._url=l,this.postData=f,this.context2D=c,this.loadWithAjax=u,this.ajaxHeaders=d,p===void 0&&(t.console.warn("Tile constructor needs 'cacheKey' variable: creation tile cache in Tile class is deprecated. TileSource.prototype.getTileHashKey will be used."),p=t.TileSource.prototype.getTileHashKey(n,r,s,l,d,f)),this.cacheKey=p,this.loaded=!1,this.loading=!1,this.element=null,this.imgElement=null,this.style=null,this.position=null,this.size=null,this.flipped=!1,this.blendStart=null,this.opacity=null,this.squaredDistance=null,this.visibility=null,this.hasTransparency=!1,this.beingDrawn=!1,this.lastTouchTime=0,this.isRightMost=!1,this.isBottomMost=!1},t.Tile.prototype={toString:function(){return this.level+"/"+this.x+"_"+this.y},_hasTransparencyChannel:function(){return console.warn("Tile.prototype._hasTransparencyChannel() has been deprecated and will be removed in the future. Use TileSource.prototype.hasTransparency() instead."),!!this.context2D||this.getUrl().match(".png")},drawHTML:function(n){if(!this.cacheImageRecord){t.console.warn("[Tile.drawHTML] attempting to draw tile %s when it's not cached",this.toString());return}if(!this.loaded){t.console.warn("Attempting to draw tile %s when it's not yet loaded.",this.toString());return}if(!this.element){var r=this.getImage();if(!r)return;this.element=t.makeNeutralElement("div"),this.imgElement=r.cloneNode(),this.imgElement.style.msInterpolationMode="nearest-neighbor",this.imgElement.style.width="100%",this.imgElement.style.height="100%",this.style=this.element.style,this.style.position="absolute"}this.element.parentNode!==n&&n.appendChild(this.element),this.imgElement.parentNode!==this.element&&this.element.appendChild(this.imgElement),this.style.top=this.position.y+"px",this.style.left=this.position.x+"px",this.style.height=this.size.y+"px",this.style.width=this.size.x+"px",this.flipped&&(this.style.transform="scaleX(-1)"),t.setElementOpacity(this.element,this.opacity)},get image(){return t.console.error("[Tile.image] property has been deprecated. Use [Tile.prototype.getImage] instead."),this.getImage()},get url(){return t.console.error("[Tile.url] property has been deprecated. Use [Tile.prototype.getUrl] instead."),this.getUrl()},getImage:function(){return this.cacheImageRecord.getImage()},getUrl:function(){return typeof this._url=="function"?this._url():this._url},getCanvasContext:function(){return this.context2D||this.cacheImageRecord.getRenderedContext()},drawCanvas:function(n,r,s,o,a,l){var c=this.position.times(t.pixelDensityRatio),u=this.size.times(t.pixelDensityRatio),d;if(!this.context2D&&!this.cacheImageRecord){t.console.warn("[Tile.drawCanvas] attempting to draw tile %s when it's not cached",this.toString());return}if(d=this.getCanvasContext(),!this.loaded||!d){t.console.warn("Attempting to draw tile %s when it's not yet loaded.",this.toString());return}n.save(),n.globalAlpha=this.opacity,typeof s=="number"&&s!==1&&(c=c.times(s),u=u.times(s)),o instanceof t.Point&&(c=c.plus(o)),n.globalAlpha===1&&this.hasTransparency&&(a&&(c.x=Math.round(c.x),c.y=Math.round(c.y),u.x=Math.round(u.x),u.y=Math.round(u.y)),n.clearRect(c.x,c.y,u.x,u.y)),r({context:n,tile:this,rendered:d});var h,f;this.sourceBounds?(h=Math.min(this.sourceBounds.width,d.canvas.width),f=Math.min(this.sourceBounds.height,d.canvas.height)):(h=d.canvas.width,f=d.canvas.height),n.translate(c.x+u.x/2,0),this.flipped&&n.scale(-1,1),n.drawImage(d.canvas,0,0,h,f,-u.x/2,c.y,u.x,u.y),n.restore()},getScaleForEdgeSmoothing:function(){var n;if(this.cacheImageRecord)n=this.cacheImageRecord.getRenderedContext();else if(this.context2D)n=this.context2D;else return t.console.warn("[Tile.drawCanvas] attempting to get tile scale %s when tile's not cached",this.toString()),1;return n.canvas.width/(this.size.x*t.pixelDensityRatio)},getTranslationForEdgeSmoothing:function(n,r,s){var o=Math.max(1,Math.ceil((s.x-r.x)/2)),a=Math.max(1,Math.ceil((s.y-r.y)/2));return new t.Point(o,a).minus(this.position.times(t.pixelDensityRatio).times(n||1).apply(function(l){return l%1}))},unload:function(){this.imgElement&&this.imgElement.parentNode&&this.imgElement.parentNode.removeChild(this.imgElement),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this.element=null,this.imgElement=null,this.loaded=!1,this.loading=!1}}}(e),function(t){t.OverlayPlacement=t.Placement,t.OverlayRotationMode=t.freezeObject({NO_ROTATION:1,EXACT:2,BOUNDING_BOX:3}),t.Overlay=function(n,r,s){var o;t.isPlainObject(n)?o=n:o={element:n,location:r,placement:s},this.element=o.element,this.style=o.element.style,this._init(o)},t.Overlay.prototype={_init:function(n){this.location=n.location,this.placement=n.placement===void 0?t.Placement.TOP_LEFT:n.placement,this.onDraw=n.onDraw,this.checkResize=n.checkResize===void 0?!0:n.checkResize,this.width=n.width===void 0?null:n.width,this.height=n.height===void 0?null:n.height,this.rotationMode=n.rotationMode||t.OverlayRotationMode.EXACT,this.location instanceof t.Rect&&(this.width=this.location.width,this.height=this.location.height,this.location=this.location.getTopLeft(),this.placement=t.Placement.TOP_LEFT),this.scales=this.width!==null&&this.height!==null,this.bounds=new t.Rect(this.location.x,this.location.y,this.width,this.height),this.position=this.location},adjust:function(n,r){var s=t.Placement.properties[this.placement];s&&(s.isHorizontallyCentered?n.x-=r.x/2:s.isRight&&(n.x-=r.x),s.isVerticallyCentered?n.y-=r.y/2:s.isBottom&&(n.y-=r.y))},destroy:function(){var n=this.element,r=this.style;n.parentNode&&(n.parentNode.removeChild(n),n.prevElementParent&&(r.display="none",document.body.appendChild(n))),this.onDraw=null,r.top="",r.left="",r.position="",this.width!==null&&(r.width=""),this.height!==null&&(r.height="");var s=t.getCssPropertyWithVendorPrefix("transformOrigin"),o=t.getCssPropertyWithVendorPrefix("transform");s&&o&&(r[s]="",r[o]="")},drawHTML:function(n,r){var s=this.element;s.parentNode!==n&&(s.prevElementParent=s.parentNode,s.prevNextSibling=s.nextSibling,n.appendChild(s),this.style.position="absolute",this.size=t.getElementSize(s));var o=this._getOverlayPositionAndSize(r),a=o.position,l=this.size=o.size,c=o.rotate;if(this.onDraw)this.onDraw(a,l,this.element);else{var u=this.style;u.left=a.x+"px",u.top=a.y+"px",this.width!==null&&(u.width=l.x+"px"),this.height!==null&&(u.height=l.y+"px");var d=t.getCssPropertyWithVendorPrefix("transformOrigin"),h=t.getCssPropertyWithVendorPrefix("transform");d&&h&&(c?(u[d]=this._getTransformOrigin(),u[h]="rotate("+c+"deg)"):(u[d]="",u[h]="")),u.display="block"}},_getOverlayPositionAndSize:function(n){var r=n.pixelFromPoint(this.location,!0),s=this._getSizeInPixels(n);this.adjust(r,s);var o=0;if(n.getRotation(!0)&&this.rotationMode!==t.OverlayRotationMode.NO_ROTATION)if(this.rotationMode===t.OverlayRotationMode.BOUNDING_BOX&&this.width!==null&&this.height!==null){var a=new t.Rect(r.x,r.y,s.x,s.y),l=this._getBoundingBox(a,n.getRotation(!0));r=l.getTopLeft(),s=l.getSize()}else o=n.getRotation(!0);return{position:r,size:s,rotate:o}},_getSizeInPixels:function(n){var r=this.size.x,s=this.size.y;if(this.width!==null||this.height!==null){var o=n.deltaPixelsFromPointsNoRotate(new t.Point(this.width||0,this.height||0),!0);this.width!==null&&(r=o.x),this.height!==null&&(s=o.y)}if(this.checkResize&&(this.width===null||this.height===null)){var a=this.size=t.getElementSize(this.element);this.width===null&&(r=a.x),this.height===null&&(s=a.y)}return new t.Point(r,s)},_getBoundingBox:function(n,r){var s=this._getPlacementPoint(n);return n.rotate(r,s).getBoundingBox()},_getPlacementPoint:function(n){var r=new t.Point(n.x,n.y),s=t.Placement.properties[this.placement];return s&&(s.isHorizontallyCentered?r.x+=n.width/2:s.isRight&&(r.x+=n.width),s.isVerticallyCentered?r.y+=n.height/2:s.isBottom&&(r.y+=n.height)),r},_getTransformOrigin:function(){var n="",r=t.Placement.properties[this.placement];return r&&(r.isLeft?n="left":r.isRight&&(n="right"),r.isTop?n+=" top":r.isBottom&&(n+=" bottom")),n},update:function(n,r){var s=t.isPlainObject(n)?n:{location:n,placement:r};this._init({location:s.location||this.location,placement:s.placement!==void 0?s.placement:this.placement,onDraw:s.onDraw||this.onDraw,checkResize:s.checkResize||this.checkResize,width:s.width!==void 0?s.width:this.width,height:s.height!==void 0?s.height:this.height,rotationMode:s.rotationMode||this.rotationMode})},getBounds:function(n){t.console.assert(n,"A viewport must now be passed to Overlay.getBounds.");var r=this.width,s=this.height;if(r===null||s===null){var o=n.deltaPointsFromPixelsNoRotate(this.size,!0);r===null&&(r=o.x),s===null&&(s=o.y)}var a=this.location.clone();return this.adjust(a,new t.Point(r,s)),this._adjustBoundsForRotation(n,new t.Rect(a.x,a.y,r,s))},_adjustBoundsForRotation:function(n,r){if(!n||n.getRotation(!0)===0||this.rotationMode===t.OverlayRotationMode.EXACT)return r;if(this.rotationMode===t.OverlayRotationMode.BOUNDING_BOX){if(this.width===null||this.height===null)return r;var s=this._getOverlayPositionAndSize(n);return n.viewerElementToViewportRectangle(new t.Rect(s.position.x,s.position.y,s.size.x,s.size.y))}return r.rotate(-n.getRotation(!0),this._getPlacementPoint(r))}}}(e),function(t){t.Drawer=function(n){t.console.assert(n.viewer,"[Drawer] options.viewer is required");var r=arguments;if(t.isPlainObject(n)||(n={source:r[0],viewport:r[1],element:r[2]}),t.console.assert(n.viewport,"[Drawer] options.viewport is required"),t.console.assert(n.element,"[Drawer] options.element is required"),n.source&&t.console.error("[Drawer] options.source is no longer accepted; use TiledImage instead"),this.viewer=n.viewer,this.viewport=n.viewport,this.debugGridColor=typeof n.debugGridColor=="string"?[n.debugGridColor]:n.debugGridColor||t.DEFAULT_SETTINGS.debugGridColor,n.opacity&&t.console.error("[Drawer] options.opacity is no longer accepted; set the opacity on the TiledImage instead"),this.useCanvas=t.supportsCanvas&&(this.viewer?this.viewer.useCanvas:!0),this.container=t.getElement(n.element),this.canvas=t.makeNeutralElement(this.useCanvas?"canvas":"div"),this.context=this.useCanvas?this.canvas.getContext("2d"):null,this.sketchCanvas=null,this.sketchContext=null,this.element=this.container,this.container.dir="ltr",this.useCanvas){var s=this._calculateCanvasSize();this.canvas.width=s.x,this.canvas.height=s.y}this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.position="absolute",t.setElementOpacity(this.canvas,this.opacity,!0),t.setElementPointerEventsNone(this.canvas),t.setElementTouchActionNone(this.canvas),this.container.style.textAlign="left",this.container.appendChild(this.canvas),this._imageSmoothingEnabled=!0},t.Drawer.prototype={addOverlay:function(n,r,s,o){return t.console.error("drawer.addOverlay is deprecated. Use viewer.addOverlay instead."),this.viewer.addOverlay(n,r,s,o),this},updateOverlay:function(n,r,s){return t.console.error("drawer.updateOverlay is deprecated. Use viewer.updateOverlay instead."),this.viewer.updateOverlay(n,r,s),this},removeOverlay:function(n){return t.console.error("drawer.removeOverlay is deprecated. Use viewer.removeOverlay instead."),this.viewer.removeOverlay(n),this},clearOverlays:function(){return t.console.error("drawer.clearOverlays is deprecated. Use viewer.clearOverlays instead."),this.viewer.clearOverlays(),this},viewportCoordToDrawerCoord:function(n){var r=this.viewport.pixelFromPointNoRotate(n,!0);return new t.Point(r.x*t.pixelDensityRatio,r.y*t.pixelDensityRatio)},clipWithPolygons:function(n,r){if(this.useCanvas){var s=this._getContext(r);s.beginPath(),n.forEach(function(o){o.forEach(function(a,l){s[l===0?"moveTo":"lineTo"](a.x,a.y)})}),s.clip()}},setOpacity:function(n){t.console.error("drawer.setOpacity is deprecated. Use tiledImage.setOpacity instead.");for(var r=this.viewer.world,s=0;s<r.getItemCount();s++)r.getItemAt(s).setOpacity(n);return this},getOpacity:function(){t.console.error("drawer.getOpacity is deprecated. Use tiledImage.getOpacity instead.");for(var n=this.viewer.world,r=0,s=0;s<n.getItemCount();s++){var o=n.getItemAt(s).getOpacity();o>r&&(r=o)}return r},needsUpdate:function(){return t.console.error("[Drawer.needsUpdate] this function is deprecated. Use World.needsDraw instead."),this.viewer.world.needsDraw()},numTilesLoaded:function(){return t.console.error("[Drawer.numTilesLoaded] this function is deprecated. Use TileCache.numTilesLoaded instead."),this.viewer.tileCache.numTilesLoaded()},reset:function(){return t.console.error("[Drawer.reset] this function is deprecated. Use World.resetItems instead."),this.viewer.world.resetItems(),this},update:function(){return t.console.error("[Drawer.update] this function is deprecated. Use Drawer.clear and World.draw instead."),this.clear(),this.viewer.world.draw(),this},canRotate:function(){return this.useCanvas},destroy:function(){this.canvas.width=1,this.canvas.height=1,this.sketchCanvas=null,this.sketchContext=null},clear:function(){if(this.canvas.innerHTML="",this.useCanvas){var n=this._calculateCanvasSize();if((this.canvas.width!==n.x||this.canvas.height!==n.y)&&(this.canvas.width=n.x,this.canvas.height=n.y,this._updateImageSmoothingEnabled(this.context),this.sketchCanvas!==null)){var r=this._calculateSketchCanvasSize();this.sketchCanvas.width=r.x,this.sketchCanvas.height=r.y,this._updateImageSmoothingEnabled(this.sketchContext)}this._clear()}},_clear:function(n,r){if(this.useCanvas){var s=this._getContext(n);if(r)s.clearRect(r.x,r.y,r.width,r.height);else{var o=s.canvas;s.clearRect(0,0,o.width,o.height)}}},viewportToDrawerRectangle:function(n){var r=this.viewport.pixelFromPointNoRotate(n.getTopLeft(),!0),s=this.viewport.deltaPixelsFromPointsNoRotate(n.getSize(),!0);return new t.Rect(r.x*t.pixelDensityRatio,r.y*t.pixelDensityRatio,s.x*t.pixelDensityRatio,s.y*t.pixelDensityRatio)},drawTile:function(n,r,s,o,a,l,c){if(t.console.assert(n,"[Drawer.drawTile] tile is required"),t.console.assert(r,"[Drawer.drawTile] drawingHandler is required"),this.useCanvas){var u=this._getContext(s);o=o||1,n.drawCanvas(u,r,o,a,l,c)}else n.drawHTML(this.canvas)},_getContext:function(n){var r=this.context;if(n){if(this.sketchCanvas===null){this.sketchCanvas=document.createElement("canvas");var s=this._calculateSketchCanvasSize();if(this.sketchCanvas.width=s.x,this.sketchCanvas.height=s.y,this.sketchContext=this.sketchCanvas.getContext("2d"),this.viewport.getRotation()===0){var o=this;this.viewer.addHandler("rotate",function a(){if(o.viewport.getRotation()!==0){o.viewer.removeHandler("rotate",a);var l=o._calculateSketchCanvasSize();o.sketchCanvas.width=l.x,o.sketchCanvas.height=l.y}})}this._updateImageSmoothingEnabled(this.sketchContext)}r=this.sketchContext}return r},saveContext:function(n){this.useCanvas&&this._getContext(n).save()},restoreContext:function(n){this.useCanvas&&this._getContext(n).restore()},setClip:function(n,r){if(this.useCanvas){var s=this._getContext(r);s.beginPath(),s.rect(n.x,n.y,n.width,n.height),s.clip()}},drawRectangle:function(n,r,s){if(this.useCanvas){var o=this._getContext(s);o.save(),o.fillStyle=r,o.fillRect(n.x,n.y,n.width,n.height),o.restore()}},blendSketch:function(n,r,s,o){var a=n;if(t.isPlainObject(a)||(a={opacity:n,scale:r,translate:s,compositeOperation:o}),!(!this.useCanvas||!this.sketchCanvas)){n=a.opacity,o=a.compositeOperation;var l=a.bounds;if(this.context.save(),this.context.globalAlpha=n,o&&(this.context.globalCompositeOperation=o),l)l.x<0&&(l.width+=l.x,l.x=0),l.x+l.width>this.canvas.width&&(l.width=this.canvas.width-l.x),l.y<0&&(l.height+=l.y,l.y=0),l.y+l.height>this.canvas.height&&(l.height=this.canvas.height-l.y),this.context.drawImage(this.sketchCanvas,l.x,l.y,l.width,l.height,l.x,l.y,l.width,l.height);else{r=a.scale||1,s=a.translate;var c=s instanceof t.Point?s:new t.Point(0,0),u=0,d=0;if(s){var h=this.sketchCanvas.width-this.canvas.width,f=this.sketchCanvas.height-this.canvas.height;u=Math.round(h/2),d=Math.round(f/2)}this.context.drawImage(this.sketchCanvas,c.x-u*r,c.y-d*r,(this.canvas.width+2*u)*r,(this.canvas.height+2*d)*r,-u,-d,this.canvas.width+2*u,this.canvas.height+2*d)}this.context.restore()}},drawDebugInfo:function(n,r,s,o){if(this.useCanvas){var a=this.viewer.world.getIndexOfItem(o)%this.debugGridColor.length,l=this.context;l.save(),l.lineWidth=2*t.pixelDensityRatio,l.font="small-caps bold "+13*t.pixelDensityRatio+"px arial",l.strokeStyle=this.debugGridColor[a],l.fillStyle=this.debugGridColor[a],this.viewport.getRotation(!0)%360!==0&&this._offsetForRotation({degrees:this.viewport.getRotation(!0)}),o.getRotation(!0)%360!==0&&this._offsetForRotation({degrees:o.getRotation(!0),point:o.viewport.pixelFromPointNoRotate(o._getRotationPoint(!0),!0)}),o.viewport.getRotation(!0)%360===0&&o.getRotation(!0)%360===0&&o._drawer.viewer.viewport.getFlip()&&o._drawer._flip(),l.strokeRect(n.position.x*t.pixelDensityRatio,n.position.y*t.pixelDensityRatio,n.size.x*t.pixelDensityRatio,n.size.y*t.pixelDensityRatio);var c=(n.position.x+n.size.x/2)*t.pixelDensityRatio,u=(n.position.y+n.size.y/2)*t.pixelDensityRatio;l.translate(c,u),l.rotate(Math.PI/180*-this.viewport.getRotation(!0)),l.translate(-c,-u),n.x===0&&n.y===0&&(l.fillText("Zoom: "+this.viewport.getZoom(),n.position.x*t.pixelDensityRatio,(n.position.y-30)*t.pixelDensityRatio),l.fillText("Pan: "+this.viewport.getBounds().toString(),n.position.x*t.pixelDensityRatio,(n.position.y-20)*t.pixelDensityRatio)),l.fillText("Level: "+n.level,(n.position.x+10)*t.pixelDensityRatio,(n.position.y+20)*t.pixelDensityRatio),l.fillText("Column: "+n.x,(n.position.x+10)*t.pixelDensityRatio,(n.position.y+30)*t.pixelDensityRatio),l.fillText("Row: "+n.y,(n.position.x+10)*t.pixelDensityRatio,(n.position.y+40)*t.pixelDensityRatio),l.fillText("Order: "+s+" of "+r,(n.position.x+10)*t.pixelDensityRatio,(n.position.y+50)*t.pixelDensityRatio),l.fillText("Size: "+n.size.toString(),(n.position.x+10)*t.pixelDensityRatio,(n.position.y+60)*t.pixelDensityRatio),l.fillText("Position: "+n.position.toString(),(n.position.x+10)*t.pixelDensityRatio,(n.position.y+70)*t.pixelDensityRatio),this.viewport.getRotation(!0)%360!==0&&this._restoreRotationChanges(),o.getRotation(!0)%360!==0&&this._restoreRotationChanges(),o.viewport.getRotation(!0)%360===0&&o.getRotation(!0)%360===0&&o._drawer.viewer.viewport.getFlip()&&o._drawer._flip(),l.restore()}},debugRect:function(n){if(this.useCanvas){var r=this.context;r.save(),r.lineWidth=2*t.pixelDensityRatio,r.strokeStyle=this.debugGridColor[0],r.fillStyle=this.debugGridColor[0],r.strokeRect(n.x*t.pixelDensityRatio,n.y*t.pixelDensityRatio,n.width*t.pixelDensityRatio,n.height*t.pixelDensityRatio),r.restore()}},setImageSmoothingEnabled:function(n){this.useCanvas&&(this._imageSmoothingEnabled=n,this._updateImageSmoothingEnabled(this.context),this.viewer.forceRedraw())},_updateImageSmoothingEnabled:function(n){n.msImageSmoothingEnabled=this._imageSmoothingEnabled,n.imageSmoothingEnabled=this._imageSmoothingEnabled},getCanvasSize:function(n){var r=this._getContext(n).canvas;return new t.Point(r.width,r.height)},getCanvasCenter:function(){return new t.Point(this.canvas.width/2,this.canvas.height/2)},_offsetForRotation:function(n){var r=n.point?n.point.times(t.pixelDensityRatio):this.getCanvasCenter(),s=this._getContext(n.useSketch);s.save(),s.translate(r.x,r.y),this.viewer.viewport.flipped?(s.rotate(Math.PI/180*-n.degrees),s.scale(-1,1)):s.rotate(Math.PI/180*n.degrees),s.translate(-r.x,-r.y)},_flip:function(n){n=n||{};var r=n.point?n.point.times(t.pixelDensityRatio):this.getCanvasCenter(),s=this._getContext(n.useSketch);s.translate(r.x,0),s.scale(-1,1),s.translate(-r.x,0)},_restoreRotationChanges:function(n){var r=this._getContext(n);r.restore()},_calculateCanvasSize:function(){var n=t.pixelDensityRatio,r=this.viewport.getContainerSize();return{x:Math.round(r.x*n),y:Math.round(r.y*n)}},_calculateSketchCanvasSize:function(){var n=this._calculateCanvasSize();if(this.viewport.getRotation()===0)return n;var r=Math.ceil(Math.sqrt(n.x*n.x+n.y*n.y));return{x:r,y:r}}}}(e),function(t){t.Viewport=function(n){var r=arguments;r.length&&r[0]instanceof t.Point&&(n={containerSize:r[0],contentSize:r[1],config:r[2]}),n.config&&(t.extend(!0,n,n.config),delete n.config),this._margins=t.extend({left:0,top:0,right:0,bottom:0},n.margins||{}),delete n.margins,n.initialDegrees=n.degrees,delete n.degrees,t.extend(!0,this,{containerSize:null,contentSize:null,zoomPoint:null,rotationPivot:null,viewer:null,springStiffness:t.DEFAULT_SETTINGS.springStiffness,animationTime:t.DEFAULT_SETTINGS.animationTime,minZoomImageRatio:t.DEFAULT_SETTINGS.minZoomImageRatio,maxZoomPixelRatio:t.DEFAULT_SETTINGS.maxZoomPixelRatio,visibilityRatio:t.DEFAULT_SETTINGS.visibilityRatio,wrapHorizontal:t.DEFAULT_SETTINGS.wrapHorizontal,wrapVertical:t.DEFAULT_SETTINGS.wrapVertical,defaultZoomLevel:t.DEFAULT_SETTINGS.defaultZoomLevel,minZoomLevel:t.DEFAULT_SETTINGS.minZoomLevel,maxZoomLevel:t.DEFAULT_SETTINGS.maxZoomLevel,initialDegrees:t.DEFAULT_SETTINGS.degrees,flipped:t.DEFAULT_SETTINGS.flipped,homeFillsViewer:t.DEFAULT_SETTINGS.homeFillsViewer,silenceMultiImageWarnings:t.DEFAULT_SETTINGS.silenceMultiImageWarnings},n),this._updateContainerInnerSize(),this.centerSpringX=new t.Spring({initial:0,springStiffness:this.springStiffness,animationTime:this.animationTime}),this.centerSpringY=new t.Spring({initial:0,springStiffness:this.springStiffness,animationTime:this.animationTime}),this.zoomSpring=new t.Spring({exponential:!0,initial:1,springStiffness:this.springStiffness,animationTime:this.animationTime}),this.degreesSpring=new t.Spring({initial:n.initialDegrees,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._oldCenterX=this.centerSpringX.current.value,this._oldCenterY=this.centerSpringY.current.value,this._oldZoom=this.zoomSpring.current.value,this._oldDegrees=this.degreesSpring.current.value,this._setContentBounds(new t.Rect(0,0,1,1),1),this.goHome(!0),this.update()},t.Viewport.prototype={get degrees(){return t.console.warn("Accessing [Viewport.degrees] is deprecated. Use viewport.getRotation instead."),this.getRotation()},set degrees(n){t.console.warn("Setting [Viewport.degrees] is deprecated. Use viewport.rotateTo, viewport.rotateBy, or viewport.setRotation instead."),this.rotateTo(n)},resetContentSize:function(n){return t.console.assert(n,"[Viewport.resetContentSize] contentSize is required"),t.console.assert(n instanceof t.Point,"[Viewport.resetContentSize] contentSize must be an OpenSeadragon.Point"),t.console.assert(n.x>0,"[Viewport.resetContentSize] contentSize.x must be greater than 0"),t.console.assert(n.y>0,"[Viewport.resetContentSize] contentSize.y must be greater than 0"),this._setContentBounds(new t.Rect(0,0,1,n.y/n.x),n.x),this},setHomeBounds:function(n,r){t.console.error("[Viewport.setHomeBounds] this function is deprecated; The content bounds should not be set manually."),this._setContentBounds(n,r)},_setContentBounds:function(n,r){t.console.assert(n,"[Viewport._setContentBounds] bounds is required"),t.console.assert(n instanceof t.Rect,"[Viewport._setContentBounds] bounds must be an OpenSeadragon.Rect"),t.console.assert(n.width>0,"[Viewport._setContentBounds] bounds.width must be greater than 0"),t.console.assert(n.height>0,"[Viewport._setContentBounds] bounds.height must be greater than 0"),this._contentBoundsNoRotate=n.clone(),this._contentSizeNoRotate=this._contentBoundsNoRotate.getSize().times(r),this._contentBounds=n.rotate(this.getRotation()).getBoundingBox(),this._contentSize=this._contentBounds.getSize().times(r),this._contentAspectRatio=this._contentSize.x/this._contentSize.y,this.viewer&&this.viewer.raiseEvent("reset-size",{contentSize:this._contentSizeNoRotate.clone(),contentFactor:r,homeBounds:this._contentBoundsNoRotate.clone(),contentBounds:this._contentBounds.clone()})},getHomeZoom:function(){if(this.defaultZoomLevel)return this.defaultZoomLevel;var n=this._contentAspectRatio/this.getAspectRatio(),r;return this.homeFillsViewer?r=n>=1?n:1:r=n>=1?1:n,r/this._contentBounds.width},getHomeBounds:function(){return this.getHomeBoundsNoRotate().rotate(-this.getRotation())},getHomeBoundsNoRotate:function(){var n=this._contentBounds.getCenter(),r=1/this.getHomeZoom(),s=r/this.getAspectRatio();return new t.Rect(n.x-r/2,n.y-s/2,r,s)},goHome:function(n){return this.viewer&&this.viewer.raiseEvent("home",{immediately:n}),this.fitBounds(this.getHomeBounds(),n)},getMinZoom:function(){var n=this.getHomeZoom(),r=this.minZoomLevel?this.minZoomLevel:this.minZoomImageRatio*n;return r},getMaxZoom:function(){var n=this.maxZoomLevel;return n||(n=this._contentSize.x*this.maxZoomPixelRatio/this._containerInnerSize.x,n/=this._contentBounds.width),Math.max(n,this.getHomeZoom())},getAspectRatio:function(){return this._containerInnerSize.x/this._containerInnerSize.y},getContainerSize:function(){return new t.Point(this.containerSize.x,this.containerSize.y)},getMargins:function(){return t.extend({},this._margins)},setMargins:function(n){t.console.assert(t.type(n)==="object","[Viewport.setMargins] margins must be an object"),this._margins=t.extend({left:0,top:0,right:0,bottom:0},n),this._updateContainerInnerSize(),this.viewer&&this.viewer.forceRedraw()},getBounds:function(n){return this.getBoundsNoRotate(n).rotate(-this.getRotation(n))},getBoundsNoRotate:function(n){var r=this.getCenter(n),s=1/this.getZoom(n),o=s/this.getAspectRatio();return new t.Rect(r.x-s/2,r.y-o/2,s,o)},getBoundsWithMargins:function(n){return this.getBoundsNoRotateWithMargins(n).rotate(-this.getRotation(n),this.getCenter(n))},getBoundsNoRotateWithMargins:function(n){var r=this.getBoundsNoRotate(n),s=this._containerInnerSize.x*this.getZoom(n);return r.x-=this._margins.left/s,r.y-=this._margins.top/s,r.width+=(this._margins.left+this._margins.right)/s,r.height+=(this._margins.top+this._margins.bottom)/s,r},getCenter:function(n){var r=new t.Point(this.centerSpringX.current.value,this.centerSpringY.current.value),s=new t.Point(this.centerSpringX.target.value,this.centerSpringY.target.value),o,a,l,c,u,d,h,f;return n?r:this.zoomPoint?(o=this.pixelFromPoint(this.zoomPoint,!0),a=this.getZoom(),l=1/a,c=l/this.getAspectRatio(),u=new t.Rect(r.x-l/2,r.y-c/2,l,c),d=this._pixelFromPoint(this.zoomPoint,u),h=d.minus(o).rotate(-this.getRotation(!0)),f=h.divide(this._containerInnerSize.x*a),s.plus(f)):s},getZoom:function(n){return n?this.zoomSpring.current.value:this.zoomSpring.target.value},_applyZoomConstraints:function(n){return Math.max(Math.min(n,this.getMaxZoom()),this.getMinZoom())},_applyBoundaryConstraints:function(n){var r=this.viewportToViewerElementRectangle(n).getBoundingBox(),s=this.viewportToViewerElementRectangle(this._contentBoundsNoRotate).getBoundingBox(),o=!1,a=!1;if(!this.wrapHorizontal){var l=r.x+r.width,c=s.x+s.width,u,d,h;r.width>s.width?u=this.visibilityRatio*s.width:u=this.visibilityRatio*r.width,d=s.x-l+u,h=c-r.x-u,u>s.width?(r.x+=(d+h)/2,o=!0):h<0?(r.x+=h,o=!0):d>0&&(r.x+=d,o=!0)}if(!this.wrapVertical){var f=r.y+r.height,p=s.y+s.height,g,m,v;r.height>s.height?g=this.visibilityRatio*s.height:g=this.visibilityRatio*r.height,m=s.y-f+g,v=p-r.y-g,g>s.height?(r.y+=(m+v)/2,a=!0):v<0?(r.y+=v,a=!0):m>0&&(r.y+=m,a=!0)}var y=o||a,S=y?this.viewerElementToViewportRectangle(r):n.clone();return S.xConstrained=o,S.yConstrained=a,S.constraintApplied=y,S},_raiseConstraintsEvent:function(n){this.viewer&&this.viewer.raiseEvent("constrain",{immediately:n})},applyConstraints:function(n){var r=this.getZoom(),s=this._applyZoomConstraints(r);r!==s&&this.zoomTo(s,this.zoomPoint,n);var o=this.getConstrainedBounds(!1);return o.constraintApplied&&(this.fitBounds(o,n),this._raiseConstraintsEvent(n)),this},ensureVisible:function(n){return this.applyConstraints(n)},_fitBounds:function(n,r){r=r||{};var s=r.immediately||!1,o=r.constraints||!1,a=this.getAspectRatio(),l=n.getCenter(),c=new t.Rect(n.x,n.y,n.width,n.height,n.degrees+this.getRotation()).getBoundingBox();c.getAspectRatio()>=a?c.height=c.width/a:c.width=c.height*a,c.x=l.x-c.width/2,c.y=l.y-c.height/2;var u=1/c.width;if(s)return this.panTo(l,!0),this.zoomTo(u,null,!0),o&&this.applyConstraints(!0),this;var d=this.getCenter(!0),h=this.getZoom(!0);this.panTo(d,!0),this.zoomTo(h,null,!0);var f=this.getBounds(),p=this.getZoom();if(p===0||Math.abs(u/p-1)<1e-8)return this.zoomTo(u,null,!0),this.panTo(l,s),o&&this.applyConstraints(!1),this;if(o){this.panTo(l,!1),u=this._applyZoomConstraints(u),this.zoomTo(u,null,!1);var g=this.getConstrainedBounds();this.panTo(d,!0),this.zoomTo(h,null,!0),this.fitBounds(g)}else{var m=c.rotate(-this.getRotation()),v=m.getTopLeft().times(u).minus(f.getTopLeft().times(p)).divide(u-p);this.zoomTo(u,v,s)}return this},fitBounds:function(n,r){return this._fitBounds(n,{immediately:r,constraints:!1})},fitBoundsWithConstraints:function(n,r){return this._fitBounds(n,{immediately:r,constraints:!0})},fitVertically:function(n){var r=new t.Rect(this._contentBounds.x+this._contentBounds.width/2,this._contentBounds.y,0,this._contentBounds.height);return this.fitBounds(r,n)},fitHorizontally:function(n){var r=new t.Rect(this._contentBounds.x,this._contentBounds.y+this._contentBounds.height/2,this._contentBounds.width,0);return this.fitBounds(r,n)},getConstrainedBounds:function(n){var r,s;return r=this.getBounds(n),s=this._applyBoundaryConstraints(r),s},panBy:function(n,r){var s=new t.Point(this.centerSpringX.target.value,this.centerSpringY.target.value);return this.panTo(s.plus(n),r)},panTo:function(n,r){return r?(this.centerSpringX.resetTo(n.x),this.centerSpringY.resetTo(n.y)):(this.centerSpringX.springTo(n.x),this.centerSpringY.springTo(n.y)),this.viewer&&this.viewer.raiseEvent("pan",{center:n,immediately:r}),this},zoomBy:function(n,r,s){return this.zoomTo(this.zoomSpring.target.value*n,r,s)},zoomTo:function(n,r,s){var o=this;return this.zoomPoint=r instanceof t.Point&&!isNaN(r.x)&&!isNaN(r.y)?r:null,s?this._adjustCenterSpringsForZoomPoint(function(){o.zoomSpring.resetTo(n)}):this.zoomSpring.springTo(n),this.viewer&&this.viewer.raiseEvent("zoom",{zoom:n,refPoint:r,immediately:s}),this},setRotation:function(n,r){return this.rotateTo(n,null,r)},getRotation:function(n){return n?this.degreesSpring.current.value:this.degreesSpring.target.value},setRotationWithPivot:function(n,r,s){return this.rotateTo(n,r,s)},rotateTo:function(n,r,s){if(!this.viewer||!this.viewer.drawer.canRotate())return this;if(this.degreesSpring.target.value===n&&this.degreesSpring.isAtTargetValue())return this;if(this.rotationPivot=r instanceof t.Point&&!isNaN(r.x)&&!isNaN(r.y)?r:null,s)if(this.rotationPivot){var o=n-this._oldDegrees;if(!o)return this.rotationPivot=null,this;this._rotateAboutPivot(n)}else this.degreesSpring.resetTo(n);else{var a=t.positiveModulo(this.degreesSpring.current.value,360),l=t.positiveModulo(n,360),c=l-a;c>180?l-=360:c<-180&&(l+=360);var u=a-l;this.degreesSpring.resetTo(n+u),this.degreesSpring.springTo(n)}return this._setContentBounds(this.viewer.world.getHomeBounds(),this.viewer.world.getContentFactor()),this.viewer.forceRedraw(),this.viewer.raiseEvent("rotate",{degrees:n,immediately:!!s,pivot:this.rotationPivot||this.getCenter()}),this},rotateBy:function(n,r,s){return this.rotateTo(this.degreesSpring.target.value+n,r,s)},resize:function(n,r){var s=this.getBoundsNoRotate(),o=s,a;this.containerSize.x=n.x,this.containerSize.y=n.y,this._updateContainerInnerSize(),r&&(a=n.x/this.containerSize.x,o.width=s.width*a,o.height=o.width/this.getAspectRatio()),this.viewer&&this.viewer.raiseEvent("resize",{newContainerSize:n,maintain:r});var l=this.fitBounds(o,!0);return this.viewer&&this.viewer.raiseEvent("after-resize",{newContainerSize:n,maintain:r}),l},_updateContainerInnerSize:function(){this._containerInnerSize=new t.Point(Math.max(1,this.containerSize.x-(this._margins.left+this._margins.right)),Math.max(1,this.containerSize.y-(this._margins.top+this._margins.bottom)))},update:function(){var n=this;this._adjustCenterSpringsForZoomPoint(function(){n.zoomSpring.update()}),this.degreesSpring.isAtTargetValue()&&(this.rotationPivot=null),this.centerSpringX.update(),this.centerSpringY.update(),this.rotationPivot?this._rotateAboutPivot(!0):this.degreesSpring.update();var r=this.centerSpringX.current.value!==this._oldCenterX||this.centerSpringY.current.value!==this._oldCenterY||this.zoomSpring.current.value!==this._oldZoom||this.degreesSpring.current.value!==this._oldDegrees;return this._oldCenterX=this.centerSpringX.current.value,this._oldCenterY=this.centerSpringY.current.value,this._oldZoom=this.zoomSpring.current.value,this._oldDegrees=this.degreesSpring.current.value,r},_rotateAboutPivot:function(n){var r=n===!0,s=this.rotationPivot.minus(this.getCenter());this.centerSpringX.shiftBy(s.x),this.centerSpringY.shiftBy(s.y),r?this.degreesSpring.update():this.degreesSpring.resetTo(n);var o=this.degreesSpring.current.value-this._oldDegrees,a=s.rotate(o*-1).times(-1);this.centerSpringX.shiftBy(a.x),this.centerSpringY.shiftBy(a.y)},_adjustCenterSpringsForZoomPoint:function(n){if(this.zoomPoint){var r=this.pixelFromPoint(this.zoomPoint,!0);n();var s=this.pixelFromPoint(this.zoomPoint,!0),o=s.minus(r),a=this.deltaPointsFromPixels(o,!0);this.centerSpringX.shiftBy(a.x),this.centerSpringY.shiftBy(a.y),this.zoomSpring.isAtTargetValue()&&(this.zoomPoint=null)}else n()},deltaPixelsFromPointsNoRotate:function(n,r){return n.times(this._containerInnerSize.x*this.getZoom(r))},deltaPixelsFromPoints:function(n,r){return this.deltaPixelsFromPointsNoRotate(n.rotate(this.getRotation(r)),r)},deltaPointsFromPixelsNoRotate:function(n,r){return n.divide(this._containerInnerSize.x*this.getZoom(r))},deltaPointsFromPixels:function(n,r){return this.deltaPointsFromPixelsNoRotate(n,r).rotate(-this.getRotation(r))},pixelFromPointNoRotate:function(n,r){return this._pixelFromPointNoRotate(n,this.getBoundsNoRotate(r))},pixelFromPoint:function(n,r){return this._pixelFromPoint(n,this.getBoundsNoRotate(r))},_pixelFromPointNoRotate:function(n,r){return n.minus(r.getTopLeft()).times(this._containerInnerSize.x/r.width).plus(new t.Point(this._margins.left,this._margins.top))},_pixelFromPoint:function(n,r){return this._pixelFromPointNoRotate(n.rotate(this.getRotation(!0),this.getCenter(!0)),r)},pointFromPixelNoRotate:function(n,r){var s=this.getBoundsNoRotate(r);return n.minus(new t.Point(this._margins.left,this._margins.top)).divide(this._containerInnerSize.x/s.width).plus(s.getTopLeft())},pointFromPixel:function(n,r){return this.pointFromPixelNoRotate(n,r).rotate(-this.getRotation(r),this.getCenter(r))},_viewportToImageDelta:function(n,r){var s=this._contentBoundsNoRotate.width;return new t.Point(n*this._contentSizeNoRotate.x/s,r*this._contentSizeNoRotate.x/s)},viewportToImageCoordinates:function(n,r){if(n instanceof t.Point)return this.viewportToImageCoordinates(n.x,n.y);if(this.viewer){var s=this.viewer.world.getItemCount();if(s>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.viewportToImageCoordinates] is not accurate with multi-image; use TiledImage.viewportToImageCoordinates instead.");else if(s===1){var o=this.viewer.world.getItemAt(0);return o.viewportToImageCoordinates(n,r,!0)}}return this._viewportToImageDelta(n-this._contentBoundsNoRotate.x,r-this._contentBoundsNoRotate.y)},_imageToViewportDelta:function(n,r){var s=this._contentBoundsNoRotate.width;return new t.Point(n/this._contentSizeNoRotate.x*s,r/this._contentSizeNoRotate.x*s)},imageToViewportCoordinates:function(n,r){if(n instanceof t.Point)return this.imageToViewportCoordinates(n.x,n.y);if(this.viewer){var s=this.viewer.world.getItemCount();if(s>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.imageToViewportCoordinates] is not accurate with multi-image; use TiledImage.imageToViewportCoordinates instead.");else if(s===1){var o=this.viewer.world.getItemAt(0);return o.imageToViewportCoordinates(n,r,!0)}}var a=this._imageToViewportDelta(n,r);return a.x+=this._contentBoundsNoRotate.x,a.y+=this._contentBoundsNoRotate.y,a},imageToViewportRectangle:function(n,r,s,o){var a=n;if(a instanceof t.Rect||(a=new t.Rect(n,r,s,o)),this.viewer){var l=this.viewer.world.getItemCount();if(l>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.imageToViewportRectangle] is not accurate with multi-image; use TiledImage.imageToViewportRectangle instead.");else if(l===1){var c=this.viewer.world.getItemAt(0);return c.imageToViewportRectangle(n,r,s,o,!0)}}var u=this.imageToViewportCoordinates(a.x,a.y),d=this._imageToViewportDelta(a.width,a.height);return new t.Rect(u.x,u.y,d.x,d.y,a.degrees)},viewportToImageRectangle:function(n,r,s,o){var a=n;if(a instanceof t.Rect||(a=new t.Rect(n,r,s,o)),this.viewer){var l=this.viewer.world.getItemCount();if(l>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.viewportToImageRectangle] is not accurate with multi-image; use TiledImage.viewportToImageRectangle instead.");else if(l===1){var c=this.viewer.world.getItemAt(0);return c.viewportToImageRectangle(n,r,s,o,!0)}}var u=this.viewportToImageCoordinates(a.x,a.y),d=this._viewportToImageDelta(a.width,a.height);return new t.Rect(u.x,u.y,d.x,d.y,a.degrees)},viewerElementToImageCoordinates:function(n){var r=this.pointFromPixel(n,!0);return this.viewportToImageCoordinates(r)},imageToViewerElementCoordinates:function(n){var r=this.imageToViewportCoordinates(n);return this.pixelFromPoint(r,!0)},windowToImageCoordinates:function(n){t.console.assert(this.viewer,"[Viewport.windowToImageCoordinates] the viewport must have a viewer.");var r=n.minus(t.getElementPosition(this.viewer.element));return this.viewerElementToImageCoordinates(r)},imageToWindowCoordinates:function(n){t.console.assert(this.viewer,"[Viewport.imageToWindowCoordinates] the viewport must have a viewer.");var r=this.imageToViewerElementCoordinates(n);return r.plus(t.getElementPosition(this.viewer.element))},viewerElementToViewportCoordinates:function(n){return this.pointFromPixel(n,!0)},viewportToViewerElementCoordinates:function(n){return this.pixelFromPoint(n,!0)},viewerElementToViewportRectangle:function(n){return t.Rect.fromSummits(this.pointFromPixel(n.getTopLeft(),!0),this.pointFromPixel(n.getTopRight(),!0),this.pointFromPixel(n.getBottomLeft(),!0))},viewportToViewerElementRectangle:function(n){return t.Rect.fromSummits(this.pixelFromPoint(n.getTopLeft(),!0),this.pixelFromPoint(n.getTopRight(),!0),this.pixelFromPoint(n.getBottomLeft(),!0))},windowToViewportCoordinates:function(n){t.console.assert(this.viewer,"[Viewport.windowToViewportCoordinates] the viewport must have a viewer.");var r=n.minus(t.getElementPosition(this.viewer.element));return this.viewerElementToViewportCoordinates(r)},viewportToWindowCoordinates:function(n){t.console.assert(this.viewer,"[Viewport.viewportToWindowCoordinates] the viewport must have a viewer.");var r=this.viewportToViewerElementCoordinates(n);return r.plus(t.getElementPosition(this.viewer.element))},viewportToImageZoom:function(n){if(this.viewer){var r=this.viewer.world.getItemCount();if(r>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.viewportToImageZoom] is not accurate with multi-image.");else if(r===1){var s=this.viewer.world.getItemAt(0);return s.viewportToImageZoom(n)}}var o=this._contentSizeNoRotate.x,a=this._containerInnerSize.x,l=this._contentBoundsNoRotate.width,c=a/o*l;return n*c},imageToViewportZoom:function(n){if(this.viewer){var r=this.viewer.world.getItemCount();if(r>1)this.silenceMultiImageWarnings||t.console.error("[Viewport.imageToViewportZoom] is not accurate with multi-image.");else if(r===1){var s=this.viewer.world.getItemAt(0);return s.imageToViewportZoom(n)}}var o=this._contentSizeNoRotate.x,a=this._containerInnerSize.x,l=this._contentBoundsNoRotate.width,c=o/a/l;return n*c},toggleFlip:function(){return this.setFlip(!this.getFlip()),this},getFlip:function(){return this.flipped},setFlip:function(n){return this.flipped===n?this:(this.flipped=n,this.viewer.navigator&&this.viewer.navigator.setFlip(this.getFlip()),this.viewer.forceRedraw(),this.viewer.raiseEvent("flip",{flipped:n}),this)}}}(e),function(t){t.TiledImage=function(a){var l=this;t.console.assert(a.tileCache,"[TiledImage] options.tileCache is required"),t.console.assert(a.drawer,"[TiledImage] options.drawer is required"),t.console.assert(a.viewer,"[TiledImage] options.viewer is required"),t.console.assert(a.imageLoader,"[TiledImage] options.imageLoader is required"),t.console.assert(a.source,"[TiledImage] options.source is required"),t.console.assert(!a.clip||a.clip instanceof t.Rect,"[TiledImage] options.clip must be an OpenSeadragon.Rect if present"),t.EventSource.call(this),this._tileCache=a.tileCache,delete a.tileCache,this._drawer=a.drawer,delete a.drawer,this._imageLoader=a.imageLoader,delete a.imageLoader,a.clip instanceof t.Rect&&(this._clip=a.clip.clone()),delete a.clip;var c=a.x||0;delete a.x;var u=a.y||0;delete a.y,this.normHeight=a.source.dimensions.y/a.source.dimensions.x,this.contentAspectX=a.source.dimensions.x/a.source.dimensions.y;var d=1;a.width?(d=a.width,delete a.width,a.height&&(t.console.error("specifying both width and height to a tiledImage is not supported"),delete a.height)):a.height&&(d=a.height/this.normHeight,delete a.height);var h=a.fitBounds;delete a.fitBounds;var f=a.fitBoundsPlacement||e.Placement.CENTER;delete a.fitBoundsPlacement;var p=a.degrees||0;delete a.degrees;var g=a.ajaxHeaders;delete a.ajaxHeaders,t.extend(!0,this,{viewer:null,tilesMatrix:{},coverage:{},loadingCoverage:{},lastDrawn:[],lastResetTime:0,_midDraw:!1,_needsDraw:!0,_hasOpaqueTile:!1,_tilesLoading:0,springStiffness:t.DEFAULT_SETTINGS.springStiffness,animationTime:t.DEFAULT_SETTINGS.animationTime,minZoomImageRatio:t.DEFAULT_SETTINGS.minZoomImageRatio,wrapHorizontal:t.DEFAULT_SETTINGS.wrapHorizontal,wrapVertical:t.DEFAULT_SETTINGS.wrapVertical,immediateRender:t.DEFAULT_SETTINGS.immediateRender,blendTime:t.DEFAULT_SETTINGS.blendTime,alwaysBlend:t.DEFAULT_SETTINGS.alwaysBlend,minPixelRatio:t.DEFAULT_SETTINGS.minPixelRatio,smoothTileEdgesMinZoom:t.DEFAULT_SETTINGS.smoothTileEdgesMinZoom,iOSDevice:t.DEFAULT_SETTINGS.iOSDevice,debugMode:t.DEFAULT_SETTINGS.debugMode,crossOriginPolicy:t.DEFAULT_SETTINGS.crossOriginPolicy,ajaxWithCredentials:t.DEFAULT_SETTINGS.ajaxWithCredentials,placeholderFillStyle:t.DEFAULT_SETTINGS.placeholderFillStyle,opacity:t.DEFAULT_SETTINGS.opacity,preload:t.DEFAULT_SETTINGS.preload,compositeOperation:t.DEFAULT_SETTINGS.compositeOperation,subPixelRoundingForTransparency:t.DEFAULT_SETTINGS.subPixelRoundingForTransparency},a),this._preload=this.preload,delete this.preload,this._fullyLoaded=!1,this._xSpring=new t.Spring({initial:c,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._ySpring=new t.Spring({initial:u,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._scaleSpring=new t.Spring({initial:d,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._degreesSpring=new t.Spring({initial:p,springStiffness:this.springStiffness,animationTime:this.animationTime}),this._updateForScale(),h&&this.fitBounds(h,f,!0),this._drawingHandler=function(m){l.viewer.raiseEvent("tile-drawing",t.extend({tiledImage:l},m))},this._ownAjaxHeaders={},this.setAjaxHeaders(g,!1)},t.extend(t.TiledImage.prototype,t.EventSource.prototype,{needsDraw:function(){return this._needsDraw},getFullyLoaded:function(){return this._fullyLoaded},_setFullyLoaded:function(a){a!==this._fullyLoaded&&(this._fullyLoaded=a,this.raiseEvent("fully-loaded-change",{fullyLoaded:this._fullyLoaded}))},reset:function(){this._tileCache.clearTilesFor(this),this.lastResetTime=t.now(),this._needsDraw=!0},update:function(){var a=this._xSpring.update(),l=this._ySpring.update(),c=this._scaleSpring.update(),u=this._degreesSpring.update();return a||l||c||u?(this._updateForScale(),this._needsDraw=!0,!0):!1},draw:function(){this.opacity!==0||this._preload?(this._midDraw=!0,this._updateViewport(),this._midDraw=!1):this._needsDraw=!1},destroy:function(){this.reset(),this.source.destroy&&this.source.destroy()},getBounds:function(a){return this.getBoundsNoRotate(a).rotate(this.getRotation(a),this._getRotationPoint(a))},getBoundsNoRotate:function(a){return a?new t.Rect(this._xSpring.current.value,this._ySpring.current.value,this._worldWidthCurrent,this._worldHeightCurrent):new t.Rect(this._xSpring.target.value,this._ySpring.target.value,this._worldWidthTarget,this._worldHeightTarget)},getWorldBounds:function(){return t.console.error("[TiledImage.getWorldBounds] is deprecated; use TiledImage.getBounds instead"),this.getBounds()},getClippedBounds:function(a){var l=this.getBoundsNoRotate(a);if(this._clip){var c=a?this._worldWidthCurrent:this._worldWidthTarget,u=c/this.source.dimensions.x,d=this._clip.times(u);l=new t.Rect(l.x+d.x,l.y+d.y,d.width,d.height)}return l.rotate(this.getRotation(a),this._getRotationPoint(a))},getTileBounds:function(a,l,c){var u=this.source.getNumTiles(a),d=(u.x+l%u.x)%u.x,h=(u.y+c%u.y)%u.y,f=this.source.getTileBounds(a,d,h);return this.getFlip()&&(f.x=1-f.x-f.width),f.x+=(l-d)/u.x,f.y+=this._worldHeightCurrent/this._worldWidthCurrent*((c-h)/u.y),f},getContentSize:function(){return new t.Point(this.source.dimensions.x,this.source.dimensions.y)},getSizeInWindowCoordinates:function(){var a=this.imageToWindowCoordinates(new t.Point(0,0)),l=this.imageToWindowCoordinates(this.getContentSize());return new t.Point(l.x-a.x,l.y-a.y)},_viewportToImageDelta:function(a,l,c){var u=c?this._scaleSpring.current.value:this._scaleSpring.target.value;return new t.Point(a*(this.source.dimensions.x/u),l*(this.source.dimensions.y*this.contentAspectX/u))},viewportToImageCoordinates:function(a,l,c){var u;return a instanceof t.Point?(c=l,u=a):u=new t.Point(a,l),u=u.rotate(-this.getRotation(c),this._getRotationPoint(c)),c?this._viewportToImageDelta(u.x-this._xSpring.current.value,u.y-this._ySpring.current.value):this._viewportToImageDelta(u.x-this._xSpring.target.value,u.y-this._ySpring.target.value)},_imageToViewportDelta:function(a,l,c){var u=c?this._scaleSpring.current.value:this._scaleSpring.target.value;return new t.Point(a/this.source.dimensions.x*u,l/this.source.dimensions.y/this.contentAspectX*u)},imageToViewportCoordinates:function(a,l,c){a instanceof t.Point&&(c=l,l=a.y,a=a.x);var u=this._imageToViewportDelta(a,l);return c?(u.x+=this._xSpring.current.value,u.y+=this._ySpring.current.value):(u.x+=this._xSpring.target.value,u.y+=this._ySpring.target.value),u.rotate(this.getRotation(c),this._getRotationPoint(c))},imageToViewportRectangle:function(a,l,c,u,d){var h=a;h instanceof t.Rect?d=l:h=new t.Rect(a,l,c,u);var f=this.imageToViewportCoordinates(h.getTopLeft(),d),p=this._imageToViewportDelta(h.width,h.height,d);return new t.Rect(f.x,f.y,p.x,p.y,h.degrees+this.getRotation(d))},viewportToImageRectangle:function(a,l,c,u,d){var h=a;a instanceof t.Rect?d=l:h=new t.Rect(a,l,c,u);var f=this.viewportToImageCoordinates(h.getTopLeft(),d),p=this._viewportToImageDelta(h.width,h.height,d);return new t.Rect(f.x,f.y,p.x,p.y,h.degrees-this.getRotation(d))},viewerElementToImageCoordinates:function(a){var l=this.viewport.pointFromPixel(a,!0);return this.viewportToImageCoordinates(l)},imageToViewerElementCoordinates:function(a){var l=this.imageToViewportCoordinates(a);return this.viewport.pixelFromPoint(l,!0)},windowToImageCoordinates:function(a){var l=a.minus(e.getElementPosition(this.viewer.element));return this.viewerElementToImageCoordinates(l)},imageToWindowCoordinates:function(a){var l=this.imageToViewerElementCoordinates(a);return l.plus(e.getElementPosition(this.viewer.element))},_viewportToTiledImageRectangle:function(a){var l=this._scaleSpring.current.value;return a=a.rotate(-this.getRotation(!0),this._getRotationPoint(!0)),new t.Rect((a.x-this._xSpring.current.value)/l,(a.y-this._ySpring.current.value)/l,a.width/l,a.height/l,a.degrees)},viewportToImageZoom:function(a){var l=this._scaleSpring.current.value*this.viewport._containerInnerSize.x/this.source.dimensions.x;return l*a},imageToViewportZoom:function(a){var l=this._scaleSpring.current.value*this.viewport._containerInnerSize.x/this.source.dimensions.x;return a/l},setPosition:function(a,l){var c=this._xSpring.target.value===a.x&&this._ySpring.target.value===a.y;if(l){if(c&&this._xSpring.current.value===a.x&&this._ySpring.current.value===a.y)return;this._xSpring.resetTo(a.x),this._ySpring.resetTo(a.y),this._needsDraw=!0}else{if(c)return;this._xSpring.springTo(a.x),this._ySpring.springTo(a.y),this._needsDraw=!0}c||this._raiseBoundsChange()},setWidth:function(a,l){this._setScale(a,l)},setHeight:function(a,l){this._setScale(a/this.normHeight,l)},setCroppingPolygons:function(a){var l=function(u){return u instanceof t.Point||typeof u.x=="number"&&typeof u.y=="number"},c=function(u){return u.map(function(d){try{if(l(d))return{x:d.x,y:d.y};throw new Error}catch{throw new Error("A Provided cropping polygon point is not supported")}})};try{if(!t.isArray(a))throw new Error("Provided cropping polygon is not an array");this._croppingPolygons=a.map(function(u){return c(u)})}catch(u){t.console.error("[TiledImage.setCroppingPolygons] Cropping polygon format not supported"),t.console.error(u),this._croppingPolygons=null}},resetCroppingPolygons:function(){this._croppingPolygons=null},fitBounds:function(a,l,c){l=l||t.Placement.CENTER;var u=t.Placement.properties[l],d=this.contentAspectX,h=0,f=0,p=1,g=1;if(this._clip&&(d=this._clip.getAspectRatio(),p=this._clip.width/this.source.dimensions.x,g=this._clip.height/this.source.dimensions.y,a.getAspectRatio()>d?(h=this._clip.x/this._clip.height*a.height,f=this._clip.y/this._clip.height*a.height):(h=this._clip.x/this._clip.width*a.width,f=this._clip.y/this._clip.width*a.width)),a.getAspectRatio()>d){var m=a.height/g,v=0;u.isHorizontallyCentered?v=(a.width-a.height*d)/2:u.isRight&&(v=a.width-a.height*d),this.setPosition(new t.Point(a.x-h+v,a.y-f),c),this.setHeight(m,c)}else{var y=a.width/p,S=0;u.isVerticallyCentered?S=(a.height-a.width/d)/2:u.isBottom&&(S=a.height-a.width/d),this.setPosition(new t.Point(a.x-h,a.y-f+S),c),this.setWidth(y,c)}},getClip:function(){return this._clip?this._clip.clone():null},setClip:function(a){t.console.assert(!a||a instanceof t.Rect,"[TiledImage.setClip] newClip must be an OpenSeadragon.Rect or null"),a instanceof t.Rect?this._clip=a.clone():this._clip=null,this._needsDraw=!0,this.raiseEvent("clip-change")},getFlip:function(){return!!this.flipped},setFlip:function(a){this.flipped=!!a,this._needsDraw=!0,this._raiseBoundsChange()},getOpacity:function(){return this.opacity},setOpacity:function(a){a!==this.opacity&&(this.opacity=a,this._needsDraw=!0,this.raiseEvent("opacity-change",{opacity:this.opacity}))},getPreload:function(){return this._preload},setPreload:function(a){this._preload=!!a,this._needsDraw=!0},getRotation:function(a){return a?this._degreesSpring.current.value:this._degreesSpring.target.value},setRotation:function(a,l){this._degreesSpring.target.value===a&&this._degreesSpring.isAtTargetValue()||(l?this._degreesSpring.resetTo(a):this._degreesSpring.springTo(a),this._needsDraw=!0,this._raiseBoundsChange())},_getRotationPoint:function(a){return this.getBoundsNoRotate(a).getCenter()},getCompositeOperation:function(){return this.compositeOperation},setCompositeOperation:function(a){a!==this.compositeOperation&&(this.compositeOperation=a,this._needsDraw=!0,this.raiseEvent("composite-operation-change",{compositeOperation:this.compositeOperation}))},setAjaxHeaders:function(a,l){if(a===null&&(a={}),!t.isPlainObject(a)){console.error("[TiledImage.setAjaxHeaders] Ignoring invalid headers, must be a plain object");return}this._ownAjaxHeaders=a,this._updateAjaxHeaders(l)},_updateAjaxHeaders:function(a){if(a===void 0&&(a=!0),t.isPlainObject(this.viewer.ajaxHeaders)?this.ajaxHeaders=t.extend({},this.viewer.ajaxHeaders,this._ownAjaxHeaders):this.ajaxHeaders=this._ownAjaxHeaders,a){var l,c,u,d;for(var h in this.tilesMatrix){l=this.source.getNumTiles(h);for(var f in this.tilesMatrix[h]){c=(l.x+f%l.x)%l.x;for(var p in this.tilesMatrix[h][f])if(u=(l.y+p%l.y)%l.y,d=this.tilesMatrix[h][f][p],d.loadWithAjax=this.loadTilesWithAjax,d.loadWithAjax){var g=this.source.getTileAjaxHeaders(h,c,u);d.ajaxHeaders=t.extend({},this.ajaxHeaders,g)}else d.ajaxHeaders=null}}for(var m=0;m<this._imageLoader.jobQueue.length;m++){var v=this._imageLoader.jobQueue[m];v.loadWithAjax=v.tile.loadWithAjax,v.ajaxHeaders=v.tile.loadWithAjax?v.tile.ajaxHeaders:null}}},_setScale:function(a,l){var c=this._scaleSpring.target.value===a;if(l){if(c&&this._scaleSpring.current.value===a)return;this._scaleSpring.resetTo(a),this._updateForScale(),this._needsDraw=!0}else{if(c)return;this._scaleSpring.springTo(a),this._updateForScale(),this._needsDraw=!0}c||this._raiseBoundsChange()},_updateForScale:function(){this._worldWidthTarget=this._scaleSpring.target.value,this._worldHeightTarget=this.normHeight*this._scaleSpring.target.value,this._worldWidthCurrent=this._scaleSpring.current.value,this._worldHeightCurrent=this.normHeight*this._scaleSpring.current.value},_raiseBoundsChange:function(){this.raiseEvent("bounds-change")},_isBottomItem:function(){return this.viewer.world.getItemAt(0)===this},_getLevelsInterval:function(){var a=Math.max(this.source.minLevel,Math.floor(Math.log(this.minZoomImageRatio)/Math.log(2))),l=this.viewport.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(0),!0).x*this._scaleSpring.current.value,c=Math.min(Math.abs(this.source.maxLevel),Math.abs(Math.floor(Math.log(l/this.minPixelRatio)/Math.log(2))));return c=Math.max(c,this.source.minLevel||0),a=Math.min(a,c),{lowestLevel:a,highestLevel:c}},_updateViewport:function(){for(this._needsDraw=!1,this._tilesLoading=0,this.loadingCoverage={};this.lastDrawn.length>0;){var a=this.lastDrawn.pop();a.beingDrawn=!1}var l=this.viewport,c=this._viewportToTiledImageRectangle(l.getBoundsWithMargins(!0));if(!this.wrapHorizontal&&!this.wrapVertical){var u=this._viewportToTiledImageRectangle(this.getClippedBounds(!0));if(c=c.intersection(u),c===null)return}for(var d=this._getLevelsInterval(),h=d.lowestLevel,f=d.highestLevel,p=null,g=!1,m=t.now(),v=f;v>=h;v--){var y=!1,S=l.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(v),!0).x*this._scaleSpring.current.value;if(v===h||!g&&S>=this.minPixelRatio)y=!0,g=!0;else if(!g)continue;var x=l.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(v),!1).x*this._scaleSpring.current.value,E=l.deltaPixelsFromPointsNoRotate(this.source.getPixelRatio(Math.max(this.source.getClosestLevel(),0)),!1).x*this._scaleSpring.current.value,C=this.immediateRender?1:E,b=Math.min(1,(S-.5)/.5),I=C/Math.abs(C-x);if(p=this._updateLevel(g,y,v,b,I,c,m,p),this._providesCoverage(this.coverage,v))break}this._drawTiles(this.lastDrawn),p&&!p.context2D?(this._loadTile(p,m),this._needsDraw=!0,this._setFullyLoaded(!1)):this._setFullyLoaded(this._tilesLoading===0)},_getCornerTiles:function(a,l,c){var u,d;this.wrapHorizontal?(u=t.positiveModulo(l.x,1),d=t.positiveModulo(c.x,1)):(u=Math.max(0,l.x),d=Math.min(1,c.x));var h,f,p=1/this.source.aspectRatio;this.wrapVertical?(h=t.positiveModulo(l.y,p),f=t.positiveModulo(c.y,p)):(h=Math.max(0,l.y),f=Math.min(p,c.y));var g=this.source.getTileAtPoint(a,new t.Point(u,h)),m=this.source.getTileAtPoint(a,new t.Point(d,f)),v=this.source.getNumTiles(a);return this.wrapHorizontal&&(g.x+=v.x*Math.floor(l.x),m.x+=v.x*Math.floor(c.x)),this.wrapVertical&&(g.y+=v.y*Math.floor(l.y/p),m.y+=v.y*Math.floor(c.y/p)),{topLeft:g,bottomRight:m}},_updateLevel:function(a,l,c,u,d,h,f,p){var g=h.getBoundingBox().getTopLeft(),m=h.getBoundingBox().getBottomRight();this.viewer&&this.viewer.raiseEvent("update-level",{tiledImage:this,havedrawn:a,level:c,opacity:u,visibility:d,drawArea:h,topleft:g,bottomright:m,currenttime:f,best:p}),this._resetCoverage(this.coverage,c),this._resetCoverage(this.loadingCoverage,c);var v=this._getCornerTiles(c,g,m),y=v.topLeft,S=v.bottomRight,x=this.source.getNumTiles(c),E=this.viewport.pixelFromPoint(this.viewport.getCenter());this.getFlip()&&(S.x+=1,this.wrapHorizontal||(S.x=Math.min(S.x,x.x-1)));for(var C=y.x;C<=S.x;C++)for(var b=y.y;b<=S.y;b++){var I;if(this.getFlip()){var D=(x.x+C%x.x)%x.x;I=C+x.x-D-D-1}else I=C;h.intersection(this.getTileBounds(c,I,b))!==null&&(p=this._updateTile(l,a,I,b,c,u,d,E,x,f,p))}return p},_updateTile:function(a,l,c,u,d,h,f,p,g,m,v){var y=this._getTile(c,u,d,m,g,this._worldWidthCurrent,this._worldHeightCurrent),S=l;this.viewer&&this.viewer.raiseEvent("update-tile",{tiledImage:this,tile:y}),this._setCoverage(this.coverage,d,c,u,!1);var x=y.loaded||y.loading||this._isCovered(this.loadingCoverage,d,c,u);if(this._setCoverage(this.loadingCoverage,d,c,u,x),!y.exists||(a&&!S&&(this._isCovered(this.coverage,d,c,u)?this._setCoverage(this.coverage,d,c,u,!0):S=!0),!S))return v;if(this._positionTile(y,this.source.tileOverlap,this.viewport,p,f),!y.loaded)if(y.context2D)this._setTileLoaded(y);else{var E=this._tileCache.getImageRecord(y.cacheKey);E&&this._setTileLoaded(y,E.getData())}if(y.loaded){var C=this._blendTile(y,c,u,d,h,m);C&&(this._needsDraw=!0)}else y.loading?this._tilesLoading++:x||(v=this._compareTiles(v,y));return v},_getTile:function(a,l,c,u,d,h,f){var p,g,m,v,y,S,x,E,C,b,I=this.tilesMatrix,D=this.source;return I[c]||(I[c]={}),I[c][a]||(I[c][a]={}),(!I[c][a][l]||!I[c][a][l].flipped!=!this.flipped)&&(p=(d.x+a%d.x)%d.x,g=(d.y+l%d.y)%d.y,m=this.getTileBounds(c,a,l),v=D.getTileBounds(c,p,g,!0),y=D.tileExists(c,p,g),S=D.getTileUrl(c,p,g),x=D.getTilePostData(c,p,g),this.loadTilesWithAjax?(E=D.getTileAjaxHeaders(c,p,g),t.isPlainObject(this.ajaxHeaders)&&(E=t.extend({},this.ajaxHeaders,E))):E=null,C=D.getContext2D?D.getContext2D(c,p,g):void 0,b=new t.Tile(c,a,l,m,y,S,C,this.loadTilesWithAjax,E,v,x,D.getTileHashKey(c,p,g,S,E,x)),this.getFlip()?p===0&&(b.isRightMost=!0):p===d.x-1&&(b.isRightMost=!0),g===d.y-1&&(b.isBottomMost=!0),b.flipped=this.flipped,I[c][a][l]=b),b=I[c][a][l],b.lastTouchTime=u,b},_loadTile:function(a,l){var c=this;a.loading=!0,this._imageLoader.addJob({src:a.getUrl(),tile:a,source:this.source,postData:a.postData,loadWithAjax:a.loadWithAjax,ajaxHeaders:a.ajaxHeaders,crossOriginPolicy:this.crossOriginPolicy,ajaxWithCredentials:this.ajaxWithCredentials,callback:function(u,d,h){c._onTileLoad(a,l,u,d,h)},abort:function(){a.loading=!1}})},_onTileLoad:function(a,l,c,u,d){if(c)a.exists=!0;else{t.console.error("Tile %s failed to load: %s - error: %s",a,a.getUrl(),u),this.viewer.raiseEvent("tile-load-failed",{tile:a,tiledImage:this,time:l,message:u,tileRequest:d}),a.loading=!1,a.exists=!1;return}if(l<this.lastResetTime){t.console.warn("Ignoring tile %s loaded before reset: %s",a,a.getUrl()),a.loading=!1;return}var h=this,f=function(){var p=h.source,g=p.getClosestLevel();h._setTileLoaded(a,c,g,d)};this._midDraw?window.setTimeout(f,1):f()},_setTileLoaded:function(a,l,c,u){var d=0,h=!1,f=this;function p(){return h&&t.console.error("Event 'tile-loaded' argument getCompletionCallback must be called synchronously. Its return value should be called asynchronously."),d++,g}function g(){d--,d===0&&(a.loading=!1,a.loaded=!0,a.hasTransparency=f.source.hasTransparency(a.context2D,a.getUrl(),a.ajaxHeaders,a.postData),a.context2D||f._tileCache.cacheTile({data:l,tile:a,cutoff:c,tiledImage:f}),f._needsDraw=!0)}var m=p();this.viewer.raiseEvent("tile-loaded",{tile:a,tiledImage:this,tileRequest:u,get image(){return t.console.error("[tile-loaded] event 'image' has been deprecated. Use 'data' property instead."),l},data:l,getCompletionCallback:p}),h=!0,m()},_positionTile:function(a,l,c,u,d){var h=a.bounds.getTopLeft();h.x*=this._scaleSpring.current.value,h.y*=this._scaleSpring.current.value,h.x+=this._xSpring.current.value,h.y+=this._ySpring.current.value;var f=a.bounds.getSize();f.x*=this._scaleSpring.current.value,f.y*=this._scaleSpring.current.value;var p=c.pixelFromPointNoRotate(h,!0),g=c.pixelFromPointNoRotate(h,!1),m=c.deltaPixelsFromPointsNoRotate(f,!0),v=c.deltaPixelsFromPointsNoRotate(f,!1),y=g.plus(v.divide(2)),S=u.squaredDistanceTo(y);l||(m=m.plus(new t.Point(1,1))),a.isRightMost&&this.wrapHorizontal&&(m.x+=.75),a.isBottomMost&&this.wrapVertical&&(m.y+=.75),a.position=p,a.size=m,a.squaredDistance=S,a.visibility=d},_blendTile:function(a,l,c,u,d,h){var f=1e3*this.blendTime,p,g;if(a.blendStart||(a.blendStart=h),p=h-a.blendStart,g=f?Math.min(1,p/f):1,this.alwaysBlend&&(g*=d),a.opacity=g,this.lastDrawn.push(a),g===1)this._setCoverage(this.coverage,u,l,c,!0),this._hasOpaqueTile=!0;else if(p<f)return!0;return!1},_compareTiles:function(a,l){return!a||l.visibility>a.visibility||l.visibility===a.visibility&&l.squaredDistance<a.squaredDistance?l:a},_drawTiles:function(a){if(!(this.opacity===0||a.length===0&&!this.placeholderFillStyle)){var l=a[0],c;l&&(c=this.opacity<1||this.compositeOperation&&this.compositeOperation!=="source-over"||!this._isBottomItem()&&this.source.hasTransparency(l.context2D,l.getUrl(),l.ajaxHeaders,l.postData));var u,d,h=this.viewport.getZoom(!0),f=this.viewportToImageZoom(h);a.length>1&&f>this.smoothTileEdgesMinZoom&&!this.iOSDevice&&this.getRotation(!0)%360===0&&t.supportsCanvas&&this.viewer.useCanvas&&(c=!0,u=l.getScaleForEdgeSmoothing(),d=l.getTranslationForEdgeSmoothing(u,this._drawer.getCanvasSize(!1),this._drawer.getCanvasSize(!0)));var p;c&&(u||(p=this.viewport.viewportToViewerElementRectangle(this.getClippedBounds(!0)).getIntegerBoundingBox(),this._drawer.viewer.viewport.getFlip()&&(this.viewport.getRotation(!0)%360!==0||this.getRotation(!0)%360!==0)&&(p.x=this._drawer.viewer.container.clientWidth-(p.x+p.width)),p=p.times(t.pixelDensityRatio)),this._drawer._clear(!0,p)),u||(this.viewport.getRotation(!0)%360!==0&&this._drawer._offsetForRotation({degrees:this.viewport.getRotation(!0),useSketch:c}),this.getRotation(!0)%360!==0&&this._drawer._offsetForRotation({degrees:this.getRotation(!0),point:this.viewport.pixelFromPointNoRotate(this._getRotationPoint(!0),!0),useSketch:c}),this.viewport.getRotation(!0)%360===0&&this.getRotation(!0)%360===0&&this._drawer.viewer.viewport.getFlip()&&this._drawer._flip());var g=!1;if(this._clip){this._drawer.saveContext(c);var m=this.imageToViewportRectangle(this._clip,!0);m=m.rotate(-this.getRotation(!0),this._getRotationPoint(!0));var v=this._drawer.viewportToDrawerRectangle(m);u&&(v=v.times(u)),d&&(v=v.translate(d)),this._drawer.setClip(v,c),g=!0}if(this._croppingPolygons){var y=this;this._drawer.saveContext(c);try{var S=this._croppingPolygons.map(function(P){return P.map(function(k){var N=y.imageToViewportCoordinates(k.x,k.y,!0).rotate(-y.getRotation(!0),y._getRotationPoint(!0)),B=y._drawer.viewportCoordToDrawerCoord(N);return u&&(B=B.times(u)),d&&(B=B.plus(d)),B})});this._drawer.clipWithPolygons(S,c)}catch(P){t.console.error(P)}g=!0}if(this.placeholderFillStyle&&this._hasOpaqueTile===!1){var x=this._drawer.viewportToDrawerRectangle(this.getBounds(!0));u&&(x=x.times(u)),d&&(x=x.translate(d));var E=null;typeof this.placeholderFillStyle=="function"?E=this.placeholderFillStyle(this,this._drawer.context):E=this.placeholderFillStyle,this._drawer.drawRectangle(x,E,c)}var C=o(this.subPixelRoundingForTransparency),b=!1;if(C===t.SUBPIXEL_ROUNDING_OCCURRENCES.ALWAYS)b=!0;else if(C===t.SUBPIXEL_ROUNDING_OCCURRENCES.ONLY_AT_REST){var I=this.viewer&&this.viewer.isAnimating();b=!I}for(var D=a.length-1;D>=0;D--)l=a[D],this._drawer.drawTile(l,this._drawingHandler,c,u,d,b,this.source),l.beingDrawn=!0,this.viewer&&this.viewer.raiseEvent("tile-drawn",{tiledImage:this,tile:l});g&&this._drawer.restoreContext(c),u||(this.getRotation(!0)%360!==0&&this._drawer._restoreRotationChanges(c),this.viewport.getRotation(!0)%360!==0&&this._drawer._restoreRotationChanges(c)),c&&(u&&(this.viewport.getRotation(!0)%360!==0&&this._drawer._offsetForRotation({degrees:this.viewport.getRotation(!0),useSketch:!1}),this.getRotation(!0)%360!==0&&this._drawer._offsetForRotation({degrees:this.getRotation(!0),point:this.viewport.pixelFromPointNoRotate(this._getRotationPoint(!0),!0),useSketch:!1})),this._drawer.blendSketch({opacity:this.opacity,scale:u,translate:d,compositeOperation:this.compositeOperation,bounds:p}),u&&(this.getRotation(!0)%360!==0&&this._drawer._restoreRotationChanges(!1),this.viewport.getRotation(!0)%360!==0&&this._drawer._restoreRotationChanges(!1))),u||this.viewport.getRotation(!0)%360===0&&this.getRotation(!0)%360===0&&this._drawer.viewer.viewport.getFlip()&&this._drawer._flip(),this._drawDebugInfo(a)}},_drawDebugInfo:function(a){if(this.debugMode)for(var l=a.length-1;l>=0;l--){var c=a[l];try{this._drawer.drawDebugInfo(c,a.length,l,this)}catch(u){t.console.error(u)}}},_providesCoverage:function(a,l,c,u){var d,h,f,p;if(!a[l])return!1;if(c===void 0||u===void 0){d=a[l];for(f in d)if(Object.prototype.hasOwnProperty.call(d,f)){h=d[f];for(p in h)if(Object.prototype.hasOwnProperty.call(h,p)&&!h[p])return!1}return!0}return a[l][c]===void 0||a[l][c][u]===void 0||a[l][c][u]===!0},_isCovered:function(a,l,c,u){return c===void 0||u===void 0?this._providesCoverage(a,l+1):this._providesCoverage(a,l+1,2*c,2*u)&&this._providesCoverage(a,l+1,2*c,2*u+1)&&this._providesCoverage(a,l+1,2*c+1,2*u)&&this._providesCoverage(a,l+1,2*c+1,2*u+1)},_setCoverage:function(a,l,c,u,d){if(!a[l]){t.console.warn("Setting coverage for a tile before its level's coverage has been reset: %s",l);return}a[l][c]||(a[l][c]={}),a[l][c][u]=d},_resetCoverage:function(a,l){a[l]={}}});var n=t.SUBPIXEL_ROUNDING_OCCURRENCES.NEVER;function r(a){return a!==t.SUBPIXEL_ROUNDING_OCCURRENCES.ALWAYS&&a!==t.SUBPIXEL_ROUNDING_OCCURRENCES.ONLY_AT_REST&&a!==t.SUBPIXEL_ROUNDING_OCCURRENCES.NEVER}function s(a){return r(a)?n:a}function o(a){if(typeof a=="number")return s(a);if(!a||!t.Browser)return n;var l=a[t.Browser.vendor];return r(l)&&(l=a["*"]),s(l)}}(e),function(t){var n=function(s){t.console.assert(s,"[TileCache.cacheTile] options is required"),t.console.assert(s.tile,"[TileCache.cacheTile] options.tile is required"),t.console.assert(s.tiledImage,"[TileCache.cacheTile] options.tiledImage is required"),this.tile=s.tile,this.tiledImage=s.tiledImage},r=function(s){t.console.assert(s,"[ImageRecord] options is required"),t.console.assert(s.data,"[ImageRecord] options.data is required"),this._tiles=[],s.create.apply(null,[this,s.data,s.ownerTile]),this._destroyImplementation=s.destroy.bind(null,this),this.getImage=s.getImage.bind(null,this),this.getData=s.getData.bind(null,this),this.getRenderedContext=s.getRenderedContext.bind(null,this)};r.prototype={destroy:function(){this._destroyImplementation(),this._tiles=null},addTile:function(s){t.console.assert(s,"[ImageRecord.addTile] tile is required"),this._tiles.push(s)},removeTile:function(s){for(var o=0;o<this._tiles.length;o++)if(this._tiles[o]===s){this._tiles.splice(o,1);return}t.console.warn("[ImageRecord.removeTile] trying to remove unknown tile",s)},getTileCount:function(){return this._tiles.length}},t.TileCache=function(s){s=s||{},this._maxImageCacheCount=s.maxImageCacheCount||t.DEFAULT_SETTINGS.maxImageCacheCount,this._tilesLoaded=[],this._imagesLoaded=[],this._imagesLoadedCount=0},t.TileCache.prototype={numTilesLoaded:function(){return this._tilesLoaded.length},cacheTile:function(s){t.console.assert(s,"[TileCache.cacheTile] options is required"),t.console.assert(s.tile,"[TileCache.cacheTile] options.tile is required"),t.console.assert(s.tile.cacheKey,"[TileCache.cacheTile] options.tile.cacheKey is required"),t.console.assert(s.tiledImage,"[TileCache.cacheTile] options.tiledImage is required");var o=s.cutoff||0,a=this._tilesLoaded.length,l=this._imagesLoaded[s.tile.cacheKey];if(l||(s.data||(t.console.error("[TileCache.cacheTile] options.image was renamed to options.data. '.image' attribute has been deprecated and will be removed in the future."),s.data=s.image),t.console.assert(s.data,"[TileCache.cacheTile] options.data is required to create an ImageRecord"),l=this._imagesLoaded[s.tile.cacheKey]=new r({data:s.data,ownerTile:s.tile,create:s.tiledImage.source.createTileCache,destroy:s.tiledImage.source.destroyTileCache,getImage:s.tiledImage.source.getTileCacheDataAsImage,getData:s.tiledImage.source.getTileCacheData,getRenderedContext:s.tiledImage.source.getTileCacheDataAsContext2D}),this._imagesLoadedCount++),l.addTile(s.tile),s.tile.cacheImageRecord=l,this._imagesLoadedCount>this._maxImageCacheCount){for(var c=null,u=-1,d=null,h,f,p,g,m,v,y=this._tilesLoaded.length-1;y>=0;y--)if(v=this._tilesLoaded[y],h=v.tile,!(h.level<=o||h.beingDrawn)){if(!c){c=h,u=y,d=v;continue}g=h.lastTouchTime,f=c.lastTouchTime,m=h.level,p=c.level,(g<f||g===f&&m>p)&&(c=h,u=y,d=v)}c&&u>=0&&(this._unloadTile(d),a=u)}this._tilesLoaded[a]=new n({tile:s.tile,tiledImage:s.tiledImage})},clearTilesFor:function(s){t.console.assert(s,"[TileCache.clearTilesFor] tiledImage is required");for(var o,a=0;a<this._tilesLoaded.length;++a)o=this._tilesLoaded[a],o.tiledImage===s&&(this._unloadTile(o),this._tilesLoaded.splice(a,1),a--)},getImageRecord:function(s){return t.console.assert(s,"[TileCache.getImageRecord] cacheKey is required"),this._imagesLoaded[s]},_unloadTile:function(s){t.console.assert(s,"[TileCache._unloadTile] tileRecord is required");var o=s.tile,a=s.tiledImage;o.unload(),o.cacheImageRecord=null;var l=this._imagesLoaded[o.cacheKey];l.removeTile(o),l.getTileCount()||(l.destroy(),delete this._imagesLoaded[o.cacheKey],this._imagesLoadedCount--),a.viewer.raiseEvent("tile-unloaded",{tile:o,tiledImage:a})}}}(e),function(t){t.World=function(n){var r=this;t.console.assert(n.viewer,"[World] options.viewer is required"),t.EventSource.call(this),this.viewer=n.viewer,this._items=[],this._needsDraw=!1,this._autoRefigureSizes=!0,this._needsSizesFigured=!1,this._delegatedFigureSizes=function(s){r._autoRefigureSizes?r._figureSizes():r._needsSizesFigured=!0},this._figureSizes()},t.extend(t.World.prototype,t.EventSource.prototype,{addItem:function(n,r){if(t.console.assert(n,"[World.addItem] item is required"),t.console.assert(n instanceof t.TiledImage,"[World.addItem] only TiledImages supported at this time"),r=r||{},r.index!==void 0){var s=Math.max(0,Math.min(this._items.length,r.index));this._items.splice(s,0,n)}else this._items.push(n);this._autoRefigureSizes?this._figureSizes():this._needsSizesFigured=!0,this._needsDraw=!0,n.addHandler("bounds-change",this._delegatedFigureSizes),n.addHandler("clip-change",this._delegatedFigureSizes),this.raiseEvent("add-item",{item:n})},getItemAt:function(n){return t.console.assert(n!==void 0,"[World.getItemAt] index is required"),this._items[n]},getIndexOfItem:function(n){return t.console.assert(n,"[World.getIndexOfItem] item is required"),t.indexOf(this._items,n)},getItemCount:function(){return this._items.length},setItemIndex:function(n,r){t.console.assert(n,"[World.setItemIndex] item is required"),t.console.assert(r!==void 0,"[World.setItemIndex] index is required");var s=this.getIndexOfItem(n);if(r>=this._items.length)throw new Error("Index bigger than number of layers.");r===s||s===-1||(this._items.splice(s,1),this._items.splice(r,0,n),this._needsDraw=!0,this.raiseEvent("item-index-change",{item:n,previousIndex:s,newIndex:r}))},removeItem:function(n){t.console.assert(n,"[World.removeItem] item is required");var r=t.indexOf(this._items,n);r!==-1&&(n.removeHandler("bounds-change",this._delegatedFigureSizes),n.removeHandler("clip-change",this._delegatedFigureSizes),n.destroy(),this._items.splice(r,1),this._figureSizes(),this._needsDraw=!0,this._raiseRemoveItem(n))},removeAll:function(){this.viewer._cancelPendingImages();var n,r;for(r=0;r<this._items.length;r++)n=this._items[r],n.removeHandler("bounds-change",this._delegatedFigureSizes),n.removeHandler("clip-change",this._delegatedFigureSizes),n.destroy();var s=this._items;for(this._items=[],this._figureSizes(),this._needsDraw=!0,r=0;r<s.length;r++)n=s[r],this._raiseRemoveItem(n)},resetItems:function(){for(var n=0;n<this._items.length;n++)this._items[n].reset()},update:function(){for(var n=!1,r=0;r<this._items.length;r++)n=this._items[r].update()||n;return n},draw:function(){for(var n=0;n<this._items.length;n++)this._items[n].draw();this._needsDraw=!1},needsDraw:function(){for(var n=0;n<this._items.length;n++)if(this._items[n].needsDraw())return!0;return this._needsDraw},getHomeBounds:function(){return this._homeBounds.clone()},getContentFactor:function(){return this._contentFactor},setAutoRefigureSizes:function(n){this._autoRefigureSizes=n,n&this._needsSizesFigured&&(this._figureSizes(),this._needsSizesFigured=!1)},arrange:function(n){n=n||{};var r=n.immediately||!1,s=n.layout||t.DEFAULT_SETTINGS.collectionLayout,o=n.rows||t.DEFAULT_SETTINGS.collectionRows,a=n.columns||t.DEFAULT_SETTINGS.collectionColumns,l=n.tileSize||t.DEFAULT_SETTINGS.collectionTileSize,c=n.tileMargin||t.DEFAULT_SETTINGS.collectionTileMargin,u=l+c,d;!n.rows&&a?d=a:d=Math.ceil(this._items.length/o);var h=0,f=0,p,g,m,v,y;this.setAutoRefigureSizes(!1);for(var S=0;S<this._items.length;S++)S&&S%d===0&&(s==="horizontal"?(f+=u,h=0):(h+=u,f=0)),p=this._items[S],g=p.getBounds(),g.width>g.height?m=l:m=l*(g.width/g.height),v=m*(g.height/g.width),y=new t.Point(h+(l-m)/2,f+(l-v)/2),p.setPosition(y,r),p.setWidth(m,r),s==="horizontal"?h+=u:f+=u;this.setAutoRefigureSizes(!0)},_figureSizes:function(){var n=this._homeBounds?this._homeBounds.clone():null,r=this._contentSize?this._contentSize.clone():null,s=this._contentFactor||0;if(!this._items.length)this._homeBounds=new t.Rect(0,0,1,1),this._contentSize=new t.Point(1,1),this._contentFactor=1;else{var o=this._items[0],a=o.getBounds();this._contentFactor=o.getContentSize().x/a.width;for(var l=o.getClippedBounds().getBoundingBox(),c=l.x,u=l.y,d=l.x+l.width,h=l.y+l.height,f=1;f<this._items.length;f++)o=this._items[f],a=o.getBounds(),this._contentFactor=Math.max(this._contentFactor,o.getContentSize().x/a.width),l=o.getClippedBounds().getBoundingBox(),c=Math.min(c,l.x),u=Math.min(u,l.y),d=Math.max(d,l.x+l.width),h=Math.max(h,l.y+l.height);this._homeBounds=new t.Rect(c,u,d-c,h-u),this._contentSize=new t.Point(this._homeBounds.width*this._contentFactor,this._homeBounds.height*this._contentFactor)}(this._contentFactor!==s||!this._homeBounds.equals(n)||!this._contentSize.equals(r))&&this.raiseEvent("metrics-change",{})},_raiseRemoveItem:function(n){this.raiseEvent("remove-item",{item:n})}})}(e)})(Oy);var NL=Oy.exports;const Ia=Dy(NL);let Es=window.OpenSeadragon;if(!Es&&(Es=Ia,!Es))throw new Error("OpenSeadragon is missing.");const My="http://www.w3.org/2000/svg";Es.Viewer&&(Es.Viewer.prototype.svgOverlay=function(){return this._svgOverlayInfo?this._svgOverlayInfo:(this._svgOverlayInfo=new Fy(this),this._svgOverlayInfo)});const Fy=function(i){const e=this;this._viewer=i,this._containerWidth=0,this._containerHeight=0,this._svg=document.createElementNS(My,"svg"),this._svg.style.position="absolute",this._svg.style.left=0,this._svg.style.top=0,this._svg.style.width="100%",this._svg.style.height="100%",this._viewer.canvas.appendChild(this._svg),this._node=document.createElementNS(My,"g"),this._svg.appendChild(this._node),this._viewer.addHandler("animation",function(){e.resize()}),this._viewer.addHandler("open",function(){e.resize()}),this._viewer.addHandler("rotate",function(){e.resize()}),this._viewer.addHandler("flip",function(){e.resize()}),this._viewer.addHandler("resize",function(){e.resize()}),this.resize()};Fy.prototype={node:function(){return this._node},resize:function(){this._containerWidth!==this._viewer.container.clientWidth&&(this._containerWidth=this._viewer.container.clientWidth,this._svg.setAttribute("width",this._containerWidth)),this._containerHeight!==this._viewer.container.clientHeight&&(this._containerHeight=this._viewer.container.clientHeight,this._svg.setAttribute("height",this._containerHeight));const i=this._viewer.viewport.pixelFromPoint(new Es.Point(0,0),!0),e=this._viewer.viewport.getZoom(!0),t=this._viewer.viewport.getRotation(),n=this._viewer.viewport.getFlip(),r=this._viewer.viewport._containerInnerSize.x;let s=r*e;const o=s;n&&(s=-s,i.x=-i.x+r),this._node.setAttribute("transform","translate("+i.x+","+i.y+") scale("+s+","+o+") rotate("+t+")")},onClick:function(i,e){new Es.MouseTracker({element:i,clickHandler:e}).setTracking(!0)}};const BL=i=>{var n;if(!i)return"LTR";const e=["ar","fa","ur","ps","dv","sd","ug","ku","he","yi","jrb","jpr","nqo"],t=Array.isArray(i)?(n=i[0])==null?void 0:n.split("-")[0]:i==null?void 0:i.split("-")[0];return e.includes(t)?"RTL":"LTR"},Ny=i=>{var t,n,r,s,o,a,l,c;let e={id:typeof i=="string"?i:i.source};if(typeof i=="string"){if(i.includes("#xywh=")){const u=i.split("#xywh=");if(u&&u[1]){const[d,h,f,p]=u[1].split(",").map(g=>Number(g));e={id:u[0],rect:{x:d,y:h,w:f,h:p}}}}else if(i.includes("#t=")||i.includes("&t=")){const u=i.includes("#t=")?"#t=":"&t=",d=i.split(u);d&&d[1]&&(e={id:d[0],t:d[1]})}}else if(typeof i=="object")if(((t=i.selector)==null?void 0:t.type)==="PointSelector")e={id:i.source,point:{x:i.selector.x,y:i.selector.y}};else if(((n=i.selector)==null?void 0:n.type)==="SvgSelector")e={id:i.source,svg:i.selector.value};else if(((r=i.selector)==null?void 0:r.type)==="FragmentSelector"){const u=typeof i.source=="string"?i.source:(s=i.source)==null?void 0:s.id;if((o=i.selector)!=null&&o.value.includes("xywh=")&&u){const d=(a=i.selector)==null?void 0:a.value.split("xywh=");if(d&&d[1]){const[h,f,p,g]=d[1].split(",").map(m=>Number(m));e={id:u,rect:{x:h,y:f,w:p,h:g}}}}else if((l=i.selector)!=null&&l.value.includes("t=")&&u){const d=i.selector.value.split("t=");d&&d[1]&&(e={id:u,t:d[1]})}}else{const u=typeof i.source=="string"?i.source:(c=i.source)==null?void 0:c.id;if(u!=null&&u.includes("&t=")){const d=u.split("&t=");d[1]&&(e={id:d[0],t:d[1]})}}return e};function UL(i){return i?Array.isArray(i)?i:[i]:[]}function $L(i,e){if(!i)return!1;if(!e)return!0;if(e.length===0)return!1;const t=UL(i.motivation);return t.length===0?!1:t.some(n=>e.includes(n))}function Pa(i){"@babel/helpers - typeof";return Pa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pa(i)}function HL(i,e){if(Pa(i)!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(Pa(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function zL(i){var e=HL(i,"string");return Pa(e)=="symbol"?e:e+""}function Lr(i,e,t){return(e=zL(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function ir(i){return Array.isArray(i)?i:i?[i]:[]}function In(i){for(let e in i)(i[e]===void 0||i[e]===null)&&delete i[e];return i}const By="http://library.stanford.edu/iiif/image-api/compliance.html#level0",Uy="http://library.stanford.edu/iiif/image-api/compliance.html#level1",$y="http://library.stanford.edu/iiif/image-api/compliance.html#level2",Hy="http://library.stanford.edu/iiif/image-api/conformance.html#level0",zy="http://library.stanford.edu/iiif/image-api/conformance.html#level1",Vy="http://library.stanford.edu/iiif/image-api/conformance.html#level2",Gy="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",Wy="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1",jy="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2",Ky="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0",qy="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1",Yy="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2",Xy="http://iiif.io/api/image/1/level0.json",Zy="http://iiif.io/api/image/1/profiles/level0.json",Qy="http://iiif.io/api/image/1/level1.json",Jy="http://iiif.io/api/image/1/profiles/level1.json",eS="http://iiif.io/api/image/1/level2.json",tS="http://iiif.io/api/image/1/profiles/level2.json",iS="http://iiif.io/api/image/2/level0.json",nS="http://iiif.io/api/image/2/profiles/level0.json",rS="http://iiif.io/api/image/2/level1.json",sS="http://iiif.io/api/image/2/profiles/level1.json",oS="http://iiif.io/api/image/2/level2.json",aS="http://iiif.io/api/image/2/profiles/level2.json",lS="level0",cS="level1",uS="level2",dS="http://iiif.io/api/image/2/level0",hS="http://iiif.io/api/image/2/level1",fS="http://iiif.io/api/image/2/level2",yc=[fS,$y,Vy,jy,Yy,eS,tS,oS,aS,uS],tf=[...yc,hS,Uy,zy,Wy,qy,Qy,Jy,rS,sS,cS],pS=[dS,hS,fS,By,Uy,$y,Hy,zy,Vy,Gy,Wy,jy,Ky,qy,Yy,Xy,Zy,Qy,Jy,eS,tS,iS,nS,rS,sS,oS,aS,lS,cS,uS],VL=pS,gS=[dS,By,Hy,Gy,Ky,Xy,Zy,iS,nS,lS],GL={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["sizeByWhListed"]},WL={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPx","regionSquare","sizeByWhListed","sizeByH","sizeByW","sizeByWh"]},jL={extraFormats:["jpg","png"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPct","regionByPx","regionSquare","rotationBy90s","sizeByWhListed","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"]},mS=["sc:Collection","sc:Manifest","sc:Canvas","sc:AnnotationList","oa:Annotation","sc:Range","sc:Layer","sc:Sequence","oa:Choice","Service","ContentResource"];function KL(i){if(i==null)throw Error("Null or undefined is not a valid entity.");if(Array.isArray(i))throw Error("Array is not a valid entity");if(typeof i!="object")throw Error(`${typeof i} is not a valid entity`);if(typeof i["@type"]=="string"){let e=mS.indexOf(i["@type"]);if(e!==-1)return mS[e]}if(i.profile)return"Service";if(i.format||i["@type"])return"ContentResource";throw Error("Resource type is not known")}var qL=class uL{constructor(e,t={}){Lr(this,"traversals",void 0),Lr(this,"options",void 0),this.traversals={collection:[],manifest:[],canvas:[],annotationList:[],sequence:[],annotation:[],contentResource:[],choice:[],range:[],service:[],layer:[],...e},this.options={convertPropsToArray:!0,mergeMemberProperties:!0,allowUndefinedReturn:!1,...t}}static all(e){return new uL({collection:[e],manifest:[e],canvas:[e],annotationList:[e],sequence:[e],annotation:[e],contentResource:[e],choice:[e],range:[e],service:[e],layer:[e]})}traverseCollection(e){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseCollectionItems(e))),this.traversals.collection)}traverseCollectionItems(e){if(this.options.mergeMemberProperties){let t=[...(e.manifests||[]).map(s=>typeof s=="string"?{"@id":s,"@type":"sc:Manifest"}:s),...(e.collections||[]).map(s=>typeof s=="string"?{"@id":s,"@type":"sc:Collection"}:s),...e.members||[]],n=[],r=t.filter(s=>n.includes(s["@id"])?!1:(n.push(s["@id"]),!0));delete e.collections,delete e.manifests,e.members=r}return e.manifests&&(e.manifests=e.manifests.map(t=>this.traverseManifest(typeof t=="string"?{"@id":t,"@type":"sc:Manifest"}:t))),e.collections&&(e.collections=e.collections.map(t=>this.traverseCollection(typeof t=="string"?{"@id":t,"@type":"sc:Collection"}:t))),e.members&&(e.members=e.members.map(t=>typeof t=="string"?t:t["@type"]==="sc:Collection"?this.traverseCollection(t):t["@type"]==="sc:Manifest"?this.traverseManifest(t):this.traverseUnknown(t))),e}traverseManifest(e){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseManifestItems(e))),this.traversals.manifest)}traverseManifestItems(e){return e.sequences&&(e.sequences=e.sequences.map(t=>this.traverseSequence(t))),e.structures&&(e.structures=e.structures.map(t=>this.traverseRange(t))),e}traverseSequence(e){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseSequenceItems(e))),this.traversals.sequence)}traverseSequenceItems(e){return e.canvases&&(e.canvases=e.canvases.map(t=>this.traverseCanvas(t))),e}traverseCanvas(e){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseCanvasItems(e))),this.traversals.canvas)}traverseCanvasItems(e){return e.images&&(e.images=e.images.map(t=>this.traverseAnnotation(t))),e.otherContent&&(e.otherContent=e.otherContent.map(t=>this.traverseAnnotationList(t))),e}traverseRange(e){return e["@type"]!=="sc:Range"&&(e["@type"]="sc:Range"),this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseRangeItems(e))),this.traversals.range)}traverseRangeItems(e){if(this.options.mergeMemberProperties){let t=[...(e.ranges||[]).map(n=>typeof n=="string"?{"@id":n,"@type":"sc:Range"}:n),...(e.canvases||[]).map(n=>typeof n=="string"?{"@id":n,"@type":"sc:Canvas"}:n),...e.members||[]];delete e.ranges,delete e.canvases,e.members=t.length?t.map(n=>this.traverseUnknown(n)):void 0}return e}traverseAnnotationList(e){let t=typeof e=="string"?{"@id":e,"@type":"sc:AnnotationList"}:e;return this.traverseType(this.traverseDescriptive(this.traverseAnnotationListItems(t)),this.traversals.annotationList)}traverseAnnotationListItems(e){return e.resources&&(e.resources=e.resources.map(t=>this.traverseAnnotation(t))),e}traverseAnnotation(e){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseAnnotationItems(e))),this.traversals.annotation)}traverseAnnotationItems(e){return e.resource&&(Array.isArray(e.resource)?e.resource=e.resource.map(t=>this.traverseContentResource(t)):e.resource=this.traverseContentResource(e.resource)),e.on,e}traverseLayer(e){return this.traverseType(this.traverseLinking(this.traverseLayerItems(e)),this.traversals.layer)}traverseLayerItems(e){return e.otherContent&&(e.otherContent=e.otherContent.map(t=>this.traverseAnnotationList(t))),e}traverseChoice(e){return this.traverseType(this.traverseChoiceItems(e),this.traversals.choice)}traverseChoiceItems(e){return e.default&&e.default!=="rdf:nil"&&(e.default=this.traverseContentResource(e.default)),e.item&&e.item!=="rdf:nil"&&(e.item=e.item.map(t=>this.traverseContentResource(t))),e}traverseService(e){return this.traverseType(this.traverseLinking(e),this.traversals.service)}traverseContentResource(e){return e["@type"]==="oa:Choice"?this.traverseChoice(e):this.traverseType(this.traverseDescriptive(this.traverseLinking(e)),this.traversals.contentResource)}traverseUnknown(e){if(!e["@type"]||typeof e=="string")return e;switch(KL(e)){case"sc:Collection":return this.traverseCollection(e);case"sc:Manifest":return this.traverseManifest(e);case"sc:Canvas":return this.traverseCanvas(e);case"sc:Sequence":return this.traverseSequence(e);case"sc:Range":return this.traverseRange(e);case"oa:Annotation":return this.traverseAnnotation(e);case"sc:AnnotationList":return this.traverseAnnotationList(e);case"sc:Layer":return this.traverseLayer(e);case"Service":return this.traverseService(e);case"oa:Choice":return this.traverseChoice(e);case"ContentResource":return this.traverseContentResource(e)}return e.profile?this.traverseService(e):e}traverseImageResource(e){let t=Array.isArray(e),n=Array.isArray(e)?e:[e],r=[];for(let s of n)typeof s=="string"?r.push(this.traverseContentResource({"@id":s,"@type":"dctypes:Image"})):r.push(this.traverseContentResource(s));return!t&&!this.options.convertPropsToArray?r[0]:r}traverseDescriptive(e){return e.thumbnail&&(e.thumbnail=this.traverseImageResource(e.thumbnail)),e.logo&&(e.logo=this.traverseImageResource(e.logo)),e}traverseOneOrMoreServices(e){let t=Array.isArray(e),n=Array.isArray(e)?e:[e],r=[];for(let s of n)r.push(this.traverseService(s));return!t&&!this.options.convertPropsToArray?r[0]:r}traverseLinking(e){return e.related&&(e.related=this.traverseOneOrManyType(e.related,this.traversals.contentResource)),e.rendering&&(e.rendering=this.traverseOneOrManyType(e.rendering,this.traversals.contentResource)),e.service&&(e.service=this.traverseOneOrMoreServices(e.service)),e.seeAlso&&(e.seeAlso=this.traverseOneOrManyType(e.seeAlso,this.traversals.contentResource)),e.within&&(typeof e.within=="string"||(e.within=this.traverseOneOrManyType(e.within,this.traversals.contentResource))),e.startCanvas&&(typeof e.startCanvas=="string"?e.startCanvas=this.traverseType({"@id":e.startCanvas,"@type":"sc:Canvas"},this.traversals.canvas):e.startCanvas&&this.traverseType(e.startCanvas,this.traversals.canvas)),e.contentLayer&&(typeof e.contentLayer=="string"?e.contentLayer=this.traverseLayer({"@id":e.contentLayer,"@type":"sc:Layer"}):e.contentLayer=this.traverseLayer(e.contentLayer)),e}traverseOneOrManyType(e,t){if(!Array.isArray(e))if(this.options.convertPropsToArray)e=[e];else return this.traverseType(e,t);return e.map(n=>this.traverseType(n,t))}traverseType(e,t){return t.reduce((n,r)=>{let s=r(n);return s===void 0&&!this.options.allowUndefinedReturn?n:s},e)}};const YL=["http://iiif.io/api/image/2/level1","http://iiif.io/api/image/2/level2","http://library.stanford.edu/iiif/image-api/compliance.html#level1","http://library.stanford.edu/iiif/image-api/compliance.html#level2","http://library.stanford.edu/iiif/image-api/conformance.html#level1","http://library.stanford.edu/iiif/image-api/conformance.html#level2","http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1","http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2","http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1","http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2","http://iiif.io/api/image/1/level1.json","http://iiif.io/api/image/1/profiles/level1.json","http://iiif.io/api/image/1/level2.json","http://iiif.io/api/image/1/profiles/level2.json","http://iiif.io/api/image/2/level1.json","http://iiif.io/api/image/2/profiles/level1.json","http://iiif.io/api/image/2/level2.json","http://iiif.io/api/image/2/profiles/level2.json","level1","level2"],nf={attributionLabel:"Attribution",providerId:"http://example.org/provider",providerName:""};function XL(i){if(typeof i=="string")return[i];if(!i)return[];let e=Array.isArray(i)?i:[i],t=[];for(let n of e){if(typeof n=="string"){t.push(n);continue}t.push({"@language":n["@language"]||n.language,"@value":n["@value"]||n.value})}return t}function ws(i,e="none"){if(!i)return{none:[""]};let t=XL(i),n={};for(let r of t){if(typeof r=="string"){n[e]=n[e]?n[e]:[],n[e].push(r||"");continue}if(!r["@language"]){n[e]=n[e]?n[e]:[],n[e].push(r["@value"]||"");continue}let s=r["@language"];n[s]=n[s]?n[s]:[],n[s].push(r["@value"]||"")}return Object.keys(n).length===0?{none:[""]}:n}function vS(i){if(Array.isArray(i))return vS(i.find(e=>typeof e=="string"));if(yc.indexOf(i)!==-1)return"level2";if(YL.indexOf(i)!==-1)return"level1";if(VL.indexOf(i)!==-1)return"level0";if(typeof i=="string")return i}function ZL(i){let e=Array.isArray(i)?i:[i];for(let t of e)switch(t){case"http://iiif.io/api/image/2/context.json":case"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2":return"ImageService2";case"http://iiif.io/api/image/1/context.json":case"http://library.stanford.edu/iiif/image-api/1.1/context.json":return"ImageService1";case"http://iiif.io/api/annex/openannotation/context.json":return"ImageApiSelector"}}function QL(i){switch(i){case"http://iiif.io/api/image/2/level0.json":case"http://iiif.io/api/image/2/level1.json":case"http://iiif.io/api/image/2/level2.json":return"ImageService2";case"http://iiif.io/api/auth/1/kiosk":case"http://iiif.io/api/auth/1/login":case"http://iiif.io/api/auth/1/clickthrough":case"http://iiif.io/api/auth/1/external":case"http://iiif.io/api/auth/0/kiosk":case"http://iiif.io/api/auth/0/login":case"http://iiif.io/api/auth/0/clickthrough":case"http://iiif.io/api/auth/0/external":return"AuthCookieService1";case"http://iiif.io/api/auth/1/token":case"http://iiif.io/api/auth/0/token":return"AuthTokenService1";case"http://iiif.io/api/auth/1/logout":case"http://iiif.io/api/auth/0/logout":return"AuthLogoutService1";case"http://iiif.io/api/search/1/search":case"http://iiif.io/api/search/0/search":return"SearchService1";case"http://iiif.io/api/search/1/autocomplete":case"http://iiif.io/api/search/0/autocomplete":return"AutoCompleteService1"}}function yS(i){for(let e of["sc","oa","dcterms","dctypes","iiif"])if(i.startsWith(`${e}:`))return i.slice(e.length+1);return i}const JL=["Collection","Manifest","Annotation","AnnotationPage","Range","Service"];function rf(i){let e=i["@id"]||i.id,t=i["@type"]||i.type,n=i.profile||void 0,r=i["@context"]||void 0;if(n){let s=QL(n);if(s)return s}if(r){let s=ZL(r);if(s)return s}if(t){if(Array.isArray(t)){if(t.indexOf("oa:CssStylesheet")!==-1)return"CssStylesheet";if(t.indexOf("cnt:ContentAsText")!==-1)return"TextualBody";t=t[0]}for(let s of["sc","oa","dcterms","dctypes","iiif"])if(t.startsWith(`${s}:`)){t=t.slice(s.length+1);break}switch(t){case"Layer":return"AnnotationCollection";case"AnnotationList":return"AnnotationPage";case"cnt:ContentAsText":return"TextualBody"}}if(t&&JL.indexOf(t)!==-1)return t;if(i.format){if(i.format.startsWith("image/"))return"Image";if(i.format.startsWith("text/")||i.format==="application/pdf")return"Text";if(i.format.startsWith("application/"))return"Dataset"}return e&&(e.endsWith(".jpg")||e.endsWith(".png")||e.endsWith(".jpeg"))?"Image":t||"unknown"}const ek=/http(s)?:\/\/(creativecommons.org|rightsstatements.org)[^"'\\<\n]+/gm;function tk(i){let e=i.match(ek);return e?e[0]:i}function ik(i,e="Rights/License",t="none"){let n=null,r=[],s=Array.isArray(i)?i:[i];for(let o of s){let a=o?tk(o):void 0;if(a&&(a.indexOf("creativecommons.org")!==-1||a.indexOf("rightsstatements.org")!==-1)){n=a.startsWith("https://")?`http://${a.slice(8)}`:a;continue}a&&r.push({label:{[t]:[e]},value:{[t]:[a]}})}return[n,r]}const nk=["http://iiif.io/api/presentation/2/context.json","http://iiif.io/api/image/2/context.json","http://iiif.io/api/image/1/context.json","http://library.stanford.edu/iiif/image-api/1.1/context.json","http://iiif.io/api/search/1/context.json","http://iiif.io/api/search/0/context.json","http://iiif.io/api/auth/1/context.json","http://iiif.io/api/auth/0/context.json","http://iiif.io/api/annex/openannotation/context.json"];function rk(i){if(i){let e=Array.isArray(i)?i:[i],t=[];for(let n of e)n==="http://iiif.io/api/presentation/2/context.json"&&t.push("http://iiif.io/api/presentation/3/context.json"),nk.indexOf(n)===-1&&t.push(n);if(e.length)return t.length===1?t[0]:t}}function sk(i){return i?i.map(e=>({label:ws(e.label),value:ws(e.value)})):[]}let SS=0;function xS(i,e){let t=encodeURI(i.id||i["@id"]||"").trim();return t&&e?`${t}/${e}`:t||(SS++,`http://example.org/${i["@type"]}${e?`/${e}`:""}/${SS}`)}function nr(i){let e=[...i.behavior||[]];i.viewingHint&&e.push(i.viewingHint);let t;return Array.isArray(i.motivation)?t=i.motivation.map(yS):i.motivation&&(t=yS(i.motivation)),{"@context":i["@context"]?rk(i["@context"]):void 0,id:(i["@id"]||xS(i)).trim(),type:rf(i),behavior:e.length?e:void 0,height:i.height?i.height:void 0,width:i.width?i.width:void 0,motivation:t,viewingDirection:i.viewingDirection,profile:i.profile,format:i.format?i.format:void 0,duration:void 0,timeMode:void 0}}function rr(i){let[e,t]=ik(i.license),n=[...i.metadata?sk(i.metadata):[],...t];return{rights:e,metadata:n.length?n:void 0,label:i.label?ws(i.label):void 0,requiredStatement:i.attribution?{label:ws(nf.attributionLabel),value:ws(i.attribution)}:void 0,navDate:i.navDate,summary:i.description?ws(i.description):void 0,thumbnail:ok(i.thumbnail)}}function ok(i){return i&&(Array.isArray(i)?i:[i]).map(t=>typeof t=="string"?{id:t,type:"Image"}:(t.type==="unknown"&&(t.type="Image"),t))}function ak(i){if(!i.within)return;let e=Array.isArray(i.within)?i.within:[i.within],t=[];for(let n of e)if(typeof n=="string"){if(n)switch(i["@type"]){case"sc:Manifest":t.push({id:n,type:"Collection"});break}}else n["@id"]&&t.push({id:n["@id"],type:rf(n)});return t.length?t:void 0}function kr(i){let e=i.related?Array.isArray(i.related)?i.related:[i.related]:[],t=i.contentLayer;return{provider:i.logo||e.length?[{id:nf.providerId,type:"Agent",homepage:e.length?[e[0]]:void 0,logo:i.logo?Array.isArray(i.logo)?i.logo:[i.logo]:void 0,label:ws(nf.providerName)}]:void 0,partOf:ak(i),rendering:i.rendering,seeAlso:i.seeAlso,start:i.startCanvas,service:i.service?ir(i.service):void 0,supplementary:t?[t]:void 0}}function lk(i){return{chars:i.chars,format:i.format?i.format:void 0,language:i.language}}function sf(i,e){return i?typeof i=="string"?{id:i,type:e}:typeof(i==null?void 0:i["@id"])=="string"?{id:i["@id"],type:e}:typeof i.id=="string"?{id:i.id,type:e}:null:null}function ck(i){let e={};if(i.first){let t=sf(i.first,"Collection");t&&(e.first=t)}if((i.total||i.total===0)&&(e.total=i.total),i.prev){let t=sf(i.prev,"Collection");t&&(e.prev=t)}if(i.next){let t=sf(i.next,"Collection");t&&(e.next=t)}return e}function uk(i){let e=[];for(let t of i){let n={...t};n.items&&n.items.length===0&&delete n.items,e.push(n)}return e}function dk(i){return In({...nr(i),...rr(i),...kr(i),...ck(i),items:uk(i.members)})}function hk(i){let e=[],t=[],n,r;for(let o of i.sequences||[])o.canvases.length&&e.push(...o.canvases),o.behavior&&t.push(...o.behavior),o.viewingDirection&&(r=o.viewingDirection),o.startCanvas&&(n=o.startCanvas);let s=nr(i);return t.length&&(s.behavior?s.behavior.push(...t):s.behavior=t),In({...s,...rr(i),...kr(i),viewingDirection:r,start:n,items:e,structures:fk(i.structures)})}function fk(i){if(!i)return i;let e=new Map;for(let n of i)e.set(n.id,n);let t=[];for(let n of i)if(n.items){let r=n.items.map(s=>typeof s=="string"?(t.push(s),e.get(s)||s):s&&s.id?(t.push(s.id),e.get(s.id)||s):s);n.items=r}return i.filter(n=>t.indexOf(n.id)===-1)}function pk(i){return In({...nr(i),...rr(i),...kr(i),annotations:i.otherContent&&i.otherContent.length?i.otherContent:void 0,items:i.images&&i.images.length?[{id:xS(i,"annotation-page"),type:"AnnotationPage",items:i.images}]:void 0})}function gk(i){return In({...nr(i),...rr(i),...kr(i),items:i.resources&&i.resources.length?i.resources:void 0})}function mk(i){return!i.canvases||i.canvases.length===0?{canvases:[],behavior:[]}:{canvases:i.canvases,behavior:i.viewingHint?[i.viewingHint]:[],viewingDirection:i.viewingDirection,startCanvas:i.startCanvas}}function vk(i){function e(t){if(Array.isArray(t)){if(t.length>1)return{type:"List",items:t.map(e)};t=t[0]}if(typeof t=="string")return encodeURI(t).trim();if("@type"in t){let n;if(typeof t.full=="string")n=t.full;else if(t.full["@type"]==="dctypes:Image")n={id:t.full["@id"],type:"Image"};else if(t.full["@type"]==="sc:Canvas")n={id:t.full["@id"],type:"Canvas"};else throw Error(`Unsupported source type on annotation: ${t.full["@type"]}`);return{type:"SpecificResource",source:n,selector:of(t.selector)}}else return encodeURI(t["@id"]).trim()}return In({...nr(i),...rr(i),...kr(i),target:e(i.on),body:Array.isArray(i.resource)?i.resource.map(TS):TS(i.resource)})}function TS(i){return i.type==="Choice"?i:ES(i)}function ES(i){let e=i;return In({...nr(e),...rr(e),...kr(e),...lk(e)})}function yk(i){let e=[];return i.default&&i.default!=="rdf:nil"&&e.push(i.default),i.item&&i.item!=="rdf:nil"&&e.push(...i.item),In({...nr(i),...rr(i),items:e})}function Sk(i){return In({...nr(i),...rr(i),...kr(i),items:i.members})}function xk(i){let{"@id":e,"@type":t,"@context":n,profile:r,...s}=i,o={};return e&&(o["@id"]=e),o["@type"]=rf(i),o["@type"]==="unknown"&&(n&&n.length&&(o["@context"]=n),o["@type"]="Service"),r&&(o.profile=vS(r)),In({...o,...s})}function Tk(i){return In({...nr(i),...rr(i),...kr(i)})}const Ek=new qL({collection:[dk],manifest:[hk],canvas:[pk],annotationList:[gk],sequence:[mk],annotation:[vk],contentResource:[ES],choice:[yk],range:[Sk],service:[xk],layer:[Tk]});function wS(i){return i&&i["@context"]&&(i["@context"]==="http://iiif.io/api/presentation/2/context.json"||i["@context"].indexOf("http://iiif.io/api/presentation/2/context.json")!==-1||i["@context"]==="http://www.shared-canvas.org/ns/context.json")||i["@context"]==="http://iiif.io/api/image/2/context.json"||i["@id"]&&i["@type"]==="sc:Collection"||i["@id"]&&i["@type"]==="sc:Manifest"?(i["@context"]||(i["@context"]="http://iiif.io/api/presentation/2/context.json"),Ek.traverseUnknown(i)):i}function of(i){if((Array.isArray(i["@type"])&&i["@type"].includes("oa:SvgSelector")||i["@type"]=="oa:SvgSelector")&&("chars"in i||"value"in i))return{type:"SvgSelector",value:"chars"in i?i.chars:i.value};if(i["@type"]==="oa:FragmentSelector")return{type:"FragmentSelector",value:i.value};if(i["@type"]==="oa:Choice")return[of(i.default),...(Array.isArray(i.item)?i.item:[i.item]).map(of)];if(i["@type"]=="iiif:ImageApiSelector")return{type:"ImageApiSelector",region:"region"in i?i.region:void 0,rotation:"rotation"in i?i.rotation:void 0};throw Error(`Unsupported selector type: ${i["@type"]}`)}const Sc={},La={get(i){return i},setMetaValue([i,e,t],n){let r=La.getResourceMeta(i,e),s=r?r[t]:void 0,o=typeof n=="function"?n(s):n;Sc[i]={...Sc[i]||{},[e]:{...(Sc[i]||{})[e]||{},[t]:o}}},getResourceMeta:(i,e)=>{let t=Sc[i];if(t)return e?t[e]:t},async load(i){let e=typeof i=="string"?i:i.id;return fetch(e).then(t=>t.json())},requestStatus(i){}};function ka(i){"@babel/helpers - typeof";return ka=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ka(i)}function wk(i,e){if(ka(i)!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(ka(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function bk(i){var e=wk(i,"string");return ka(e)=="symbol"?e:e+""}function qi(i,e,t){return(e=bk(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}const _k={},bS=i=>{let e,t=new Set,n=(u,d)=>{let h=typeof u=="function"?u(e):u;if(!Object.is(h,e)){let f=e;e=d??(typeof h!="object"||!h)?h:Object.assign({},e,h),t.forEach(p=>p(e,f))}},r=()=>e,s=()=>c,o=u=>(t.add(u),()=>t.delete(u)),a=()=>{(_k?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()},l={setState:n,getState:r,getInitialState:s,subscribe:o,destroy:a},c=e=i(n,r,l);return l},_S=i=>i?bS(i):bS;function AS(i){return{all:i||(i=new Map),on:function(e,t){var n=i.get(e);n?n.push(t):i.set(e,[t])},off:function(e,t){var n=i.get(e);n&&(t?n.splice(n.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var n=i.get(e);n&&n.slice().map(function(r){r(t)}),(n=i.get("*"))&&n.slice().map(function(r){r(e,t)})}}}function Ak(i){try{if(i==="full")return{full:!0};if(i==="square")return{square:!0};let e=i.startsWith("pct:"),t=i.substr(e?4:0).split(","),n=t.map(r=>parseFloat(r));return{x:n[0],y:n[1],w:n[2],h:n[3],percent:e}}catch{throw Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+i)}}function Rk(i){let e={upscaled:!1,max:!1,confined:!1};if(i[0]==="^"&&(e.upscaled=!0,i=i.slice(1)),i==="max"||i==="full")return e.max=!0,e.serialiseAsFull=i==="full",e;if(i[0]==="!"&&(e.confined=!0,i=i.slice(1)),i[0]==="p")return e.percentScale=parseFloat(i.slice(4)),e;let t=i.split(",").map(n=>n.trim());return t.length&&(t[0]!==""&&(e.width=parseInt(t[0],10)),t[1]!==""&&(e.height=parseInt(t[1],10))),e}function Ck(i){let e={angle:0};if(i[0]==="!"&&(e.mirror=!0,i=i.substr(1)),e.angle=parseFloat(i)%360,Number.isNaN(e.angle))throw Error(`Invalid rotation ${i}`);return e}function Ik(i,e=""){let t=i.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!t)throw Error(`Invalid or unknown input ${i}`);let n=t[2],r=t[3],s=t[4];if(s[0]==="/"&&(s=s.substring(1)),e.length>0){if(e[0]==="/"&&(e=e.substring(1)),e!==s.substring(0,e.length))throw Error(`Path does not start with prefix (path: ${s}, prefix: ${e})`);s=s.substring(e.length)}return{scheme:n,server:r,path:s,prefix:e}}function Pk(i,e=""){let{path:t,scheme:n,server:r,prefix:s}=Ik(i,e),o=t.split("/").reverse(),[a,l,c,u,...d]=o,h=d.reverse().filter(Boolean).join("/");if(o.length===1||a==="")return{type:"base",scheme:n,server:r,prefix:s,identifier:h};if(a==="info.json"){let[,...g]=o;return{type:"info",scheme:n,server:r,prefix:s,identifier:g.reverse().filter(Boolean).join("/")}}if(n===void 0||r===void 0||t===void 0||u===void 0||c===void 0||l===void 0||a===void 0)throw Error("Invalid image service URL");let[f="",p=""]=a.split(".");return{type:"image",scheme:n,server:r,prefix:s,identifier:h,originalPath:t,region:Ak(u),size:Rk(c),rotation:Ck(l),quality:f,format:p}}function Lk(i){return yc.indexOf(i)!==-1?jL:tf.indexOf(i)!==-1?WL:GL}function kk(i){let e=i?Array.isArray(i.profile)?i.profile:[i.profile]:[],t={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let n of e)if(typeof n=="string"&&(n=Lk(n)),!!n){if(n.formats)for(let r of n.formats)t.extraFormats.indexOf(r)===-1&&t.extraFormats.push(r);if(n.qualities)for(let r of n.qualities)t.extraQualities.indexOf(r)===-1&&t.extraQualities.push(r);if(n.supports)for(let r of n.supports)t.extraFeatures.indexOf(r)===-1&&t.extraFeatures.push(r);if(n.maxHeight&&(t.maxHeight=n.maxHeight),n.maxWidth&&(t.maxWidth=n.maxWidth),n.maxArea&&(t.maxArea=n.maxArea),n.extraFormats)for(let r of n.extraFormats)t.extraFormats.indexOf(r)===-1&&t.extraFormats.push(r);if(n.extraQualities)for(let r of n.extraQualities)t.extraQualities.indexOf(r)===-1&&t.extraQualities.push(r);if(n.extraFeatures)for(let r of n.extraFeatures)t.extraFeatures.indexOf(r)===-1&&t.extraFeatures.push(r);n.maxHeight&&(t.maxHeight=n.maxHeight),n.maxWidth&&(t.maxWidth=n.maxWidth),n.maxArea&&(t.maxArea=n.maxArea)}if(i.extraFormats)for(let n of i.extraFormats)t.extraFormats.indexOf(n)===-1&&t.extraFormats.push(n);if(i.extraFeatures)for(let n of i.extraFeatures)t.extraFeatures.indexOf(n)===-1&&t.extraFeatures.push(n);if(i.extraQualities)for(let n of i.extraQualities)t.extraQualities.indexOf(n)===-1&&t.extraQualities.push(n);return t}function RS(i){let e=Array.isArray(i.profile)?i.profile:[i.profile];for(let t of e)if(typeof t=="string"&&gS.indexOf(t)!==-1)return!0;return!1}function yt(i){if(i["@id"])return i["@id"];if(i.id)return i.id}function xc(i){if(!i||!i.profile||!yt(i))return!1;let e=Array.isArray(i.profile)?i.profile:[i.profile];for(let t of e)if(typeof t=="string"&&pS.indexOf(t)!==-1)return!0;return!1}function Dk(i){if(!xc(i))return!1;let e=Array.isArray(i.profile)?i.profile:[i.profile];for(let t of e)if(typeof t=="string"){if(tf.indexOf(t)!==-1)return!0}else{let n=[...t.supports||[],...t.extraFeatures||[]];if(n.indexOf("regionByPx")!==-1&&(n.indexOf("sizeByW")!==-1||n.indexOf("sizeByWh")!==-1))return!0}return!1}function Ok({x:i=0,y:e=0,w:t,h:n,full:r,square:s,percent:o}){return"full"}function Mk({max:i,percentScale:e,upscaled:t,confined:n,width:r,height:s,serialiseAsFull:o,version:a}){let l=[];return t&&l.push("^"),i?(l.push(o?"full":"max"),l.join("")):(n&&l.push("!"),e&&l.push(`pct:${e}`),r&&l.push(`${r}`),l.push(","),s&&a===3&&l.push(`${s}`),l.join(""))}function Fk(i){return`${i.mirror?"!":""}${(i.angle||0)%360}`}function Nk(i,e){let t=i.prefix.startsWith("/")?i.prefix.substring(1):i.prefix,n=`${i.scheme}://${i.server}/${t?`${t}/`:""}${i.identifier}`,{size:r}=i,{region:s,rotation:o,format:a,quality:l}=i;return[n,Ok(s),Mk(r),Fk(o),`${l}.${a}`].filter(Boolean).join("/")}function bs(i){return i.endsWith("info.json")?i:i.endsWith("/")?`${i}info.json`:`${i}/info.json`}function Bk(i){let e=Pk(bs(i.id));if(e.type!=="info")throw Error("Invalid service URL");let t=kk(i);return{identifier:e.identifier,originalPath:"",server:e.server,prefix:e.prefix,scheme:e.scheme,type:"image",quality:t.extraQualities.indexOf("default")===-1?t.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function Uk(i,e,t){let n=t.length,r=[];for(let s=0;s<n;s++){let o=t[s];if(!o)continue;let a=o.width;r.push(i/a)}return r}function $k(i,e,t){let n=t.length,r=[];for(let s=0;s<n;s++){let o=t[s];o&&r.push({width:Math.floor(i/o),height:Math.floor(e/o)})}return r}function af(i,e){if(e&&e.profile){let t=e.profile;if(t){let n=Array.isArray(t)?t:[t];if(n.includes(`level${i}`)||n.includes(`http://iiif.io/api/image/2/level${i}.json`)||n.includes(`http://iiif.io/api/image/1/level${i}.json`)||n.includes(`http://iiif.io/api/image/1/profiles/level${i}.json`))return!0;if(i===2){for(let r of n)if(yc.includes(r))return!0}if(i===1){for(let r of n)if(tf.includes(r))return!0}if(i===0){for(let r of n)if(gS.includes(r))return!0}}}return!1}function lf(i){return xc(i)?af(2,i)?2:af(1,i)?1:af(0,i)?0:null:null}function CS(i){let e=i.service?Array.isArray(i.service)?i.service:[i.service]:[],t=e.length,n=[];for(let r=0;r<t;r++)xc(e[r])&&n.push(e[r]);return n}function Hk(i){if(i["@type"])return i["@type"];if(i.type)return i.type}function po(i){let e=i.replace(/(https?:\/\/)?(www.)?/i,"");return e.indexOf("/")===-1?e:e.split("/")[0]}function zk(i,e,t){let n=i>e?i:e,r=t.length,s=[];for(let o=0;o<r;o++){let a=t[o];if(!a||a.scaleFactors.length===0)continue;let l=a.scaleFactors[0];if(!l)continue;let c=n/l,u=[l];for(;c>=a.width;)l*=2,u.push(l),c/=2;s.push({...a,scaleFactors:u})}return s}function cf(i,e,t){let n=Bk({"@context":i.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:bs(yt(i)),profile:i.level===null||i.level===void 0?"level0":`level${i.level}`,type:i.version===3?"ImageService3":"ImageService2"});return n.size.max=!1,n.size.width=e,n.size.height=t,{id:Nk(n),type:"fixed",width:e,height:t||i.height/(i.width||1)*e,unsafe:i.width>e}}function Vk(i,e,t){let n=i.width?i.width:i.maxWidth;return t.height<=i.maxHeight&&t.width<=i.maxWidth&&t.height>=i.minHeight&&t.width>=i.minWidth&&(!e||Math.abs(t.width-n)<Math.abs(e.width-n))}function Gk(i,e){let t=[],n=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},i),r=(u,d=0)=>n.explain?t.push(Array(d).fill(0).map(h=>" ").join("")+u().trim()):void 0,s=[],o=[],a=null;r(()=>`Using configuration: ${JSON.stringify(n,null,2)}`);let l=(u,d)=>{if(r(()=>"Swapping choice",3),Vk(n,d,u)){if(n.preferFixedSize&&u.unsafe){r(()=>`We found an image that was marked as unsafe, but it was the best size. (${u.id})`,4),o.push(u);return}n.returnAllOptions&&d&&o.push(d),r(()=>`We found a new image that was the best size. (${u.id})`,4),a=u}else n.returnAllOptions&&o.push(u)};r(()=>`The input shows we have ${e.length} list(s) of candidates to choose from.`);let c=e.length;for(let u=0;u<c;u++){let d=e[u]();r(()=>`Candidate group ${u}: ${JSON.stringify(d,null,2)}`,1);let h=d.length;r(()=>`Checking candidate list number ${u} and found ${h} potential ways of creating image(s)`,1);for(let f=0;f<h;f++){let p=d[f];if(r(()=>`-> Checking candidate ${f}`,1),p.type==="unknown"&&n.atAnyCost&&(r(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),s.push(p)),p.type==="fixed"&&(p.unsafe?(r(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),s.push(p)):(r(()=>"We've found a fixed size image, checking if it matches the request",2),l(p,a))),p.type==="fixed-service")if(n.unsafeImageService){r(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2);let g=cf(p,n.width,n.height);l(g,a)}else{r(()=>"Checking for an image from the tile source 3",2);let g=cf(p,p.width,p.height);l(g,a)}if(p.type==="variable"&&p.maxWidth){let g=cf({id:p.id,type:"fixed-service",width:p.maxWidth,height:p.maxWidth,level:p.level,version:p.version},p.maxWidth);l(g,a)}}if(a&&!n.returnAllOptions){if(a.unsafe||n.allowUnsafe)continue;r(()=>`We found a match in choice list number ${u}, no searching any more`);break}}return n.atAnyCost&&o.length===0?(r(()=>a?`We found an image! ${a.id} of type ${a.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:a||s[0]||null,fallback:s.slice(1),log:t}):n.returnAllOptions?(r(()=>"Returning all options that we have found"),{best:(n.atAnyCost?a||o[0]||s[0]:a||o[0])||null,fallback:[...o,...s],log:t}):(r(()=>"Returning the best image that we found, and a fallback"),{best:a||o[0]||null,fallback:a?o:o.slice(1),log:t})}function IS(i){return(i["@context"]?Array.isArray(i["@context"])?i["@context"]:[i["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function Wk(i){return xc(i)?(i&&i.sizes?i.sizes:[]).map(e=>({id:yt(i),type:"fixed-service",height:e.height,width:e.width,level:lf(i),version:IS(i)?3:2})):[]}function jk(i){if(!Dk(i))return[];let e=[],t=Array.isArray(i.profile)?i.profile:[i.profile],n=t.length;for(let r=0;r<n;r++){let s=t[r];if(s&&typeof s!="string"&&(s.maxHeight||s.maxWidth))return[{id:yt(i),type:"variable",minWidth:0,minHeight:0,maxHeight:s.maxHeight||s.maxWidth,maxWidth:s.maxWidth||s.maxHeight,level:lf(i),version:i["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(i.tiles){let r=i.tiles.length;for(let s=0;s<r;s++){let o=i.tiles[s];o&&(o.height||o.width)&&e.push({id:yt(i),type:"variable",minHeight:0,minWidth:0,maxHeight:o.height||o.width,maxWidth:o.width,level:lf(i),version:IS(i)?3:2})}}return e}function PS(i){let e=[],t=i.length;for(let n=0;n<t;n++){let r=i[n];if(!r)continue;let s=Wk(r);s.length&&e.push(...s);let o=jk(r);o.length&&e.push(...o)}return e}function LS(i){let e=/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/,t=i.match(e);if(t&&t[4]&&t[5]){let n=t[1],r=parseInt(t[4],10),s=parseInt(t[5],10),o=t[7];if((n==="max"||n==="full")&&r&&s&&o)return{type:"fixed",id:i,height:s,width:r}}return{type:"unknown",id:i}}function uf(i){if(typeof i=="string")return LS(i);let e=Hk(i);if(e!=="Image"&&e!=="sc:Image")return null;let t=i,n=yt(t);return n?n&&t.width&&t.height?{id:n,type:"fixed",width:t.width,height:t.height,unsafe:!0}:LS(n):null}function Kk(i,e=!0,t){let n=[],r=uf(i);if(r===null)return n;let s=i;if(n.push(r),e&&s&&s.width&&s.height){let o=[],a=CS(s);for(let l of a){let c={id:yt(l),width:s.width,height:s.height};if(t.canLoadSync(c)){let u=t.loadServiceSync(c);u&&(u.height||(u.height=s.height),u.width||(u.width=s.width),o.push(...PS([u])))}}if(o.length)return n.push(...o),n}return s.service&&n.push(...PS(s.service)),n}function qk(i,e){if(i.length!==e.length)return!1;if(i.length===0&&e.length===0)return!0;let t=i.length,n=!0;for(let s=0;s<t;s++){let o=i[s],a=e[s];if(o.width!==a.width||o.height!==a.height){n=!1;break}}if(n)return!0;let r=0;for(let s=0;s<t;s++)for(let o=0;o<t;o++)if(i[s].width===e[o].width&&i[s].height===e[o].height){r++;break}return r===t}var kS=class{constructor(e={}){qi(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),qi(this,"fetchingCount",0),qi(this,"imageServices",{}),qi(this,"knownImageServers",{}),this.config=Object.assign(this.config,e)}setConfig(e){Object.assign(this.config,e)}sample(e,t,n=!0){let r=po(yt(e)),s=bs(yt(e)),o=this.knownImageServers[r];return this.imageServices[s]=Object.assign(e,{real:!0}),!o&&e.tiles&&!RS(e)?(this.knownImageServers[r]={verifications:0,malformed:!1,root:r,preLoaded:n,sampledId:yt(e),verified:!1,server:null,result:{context:e["@context"]||[],sampledProfile:e.profile,resourceServiceRatio:t&&e.height?t.height/e.height:1,sampledSizes:e.sizes||[],sizeRatios:Uk(e.width,e.height,e.sizes||[]),sampledTiles:e.tiles||[]}},!0):this.verify(e)}preLoad(e,t=!0){this.knownImageServers[e.root]=e,t&&(this.knownImageServers[e.root].malformed=!1,this.knownImageServers[e.root].verifications=this.config.verificationsRequired)}predict(e,t=!1,n=!1){let r=e==null?void 0:e.source,s=po(yt(e)),o=this.knownImageServers[s],a=bs(yt(e));return this.imageServices[a]?this.imageServices[a]||null:!this.config.approximateServices||!o||!o.result||!(r!=null&&r.height||e.height)||!(r!=null&&r.width||e.width)||!n&&(o.malformed||o.verifications<this.config.verificationsRequired)||e.source&&RS(e.source)?null:(this.imageServices[a]||(this.imageServices[a]={"@context":o.result.context,"@id":yt(e),id:yt(e),protocol:"http://iiif.io/api/image",tiles:(r==null?void 0:r.tiles)||zk(e.width,e.height,o.result.sampledTiles),sizes:(r==null?void 0:r.sizes)||$k(Math.round(e.width/o.result.resourceServiceRatio),Math.round(e.height/o.result.resourceServiceRatio),o.result.sizeRatios),profile:(r==null?void 0:r.profile)||o.result.sampledProfile,height:(r==null?void 0:r.height)||e.height,width:(r==null?void 0:r.width)||e.width,real:!1}),this.imageServices[a]||null)}async getThumbnailFromResource(e,t,n=!0,r=[]){let s=e?await this.getImageCandidates(e,n):[];return Gk(t,[()=>r,()=>s])}async getImageCandidates(e,t=!0){let n=e;if(t&&n&&n.height&&n.width){let r=CS(n);for(let s of r){let o={id:yt(s),width:s.width?s.width:n.width,height:s.height?s.height:n.height,source:s};await this.loadService(o)}}return Kk(e,t,this)}async verify(e){let t=this.predict(e,!1,!0),n=await this.fetchService(yt(e));if(!t)return!1;let r=t.height===n.height&&t.width===n.width&&t["@context"]===n["@context"]&&qk(t.sizes||[],n.sizes||[]);if(r){let s=po(yt(e)),o=this.knownImageServers[s];o&&(o.verifications+=1,o.verifications>=this.config.verificationsRequired&&(o.verified=!0))}return r}canLoadSync(e){let t=typeof e=="string"?e:yt(e),n=bs(t);if(this.imageServices[n])return!0;let r=this.knownImageServers[po(t)];return!!(r&&!r.malformed&&r.verifications>=this.config.verificationsRequired)}async markAsMalformed(e){return this.knownImageServers[po(yt(e))].malformed=!0,this.loadService(e,!0)}async fetchService(e,t=!1){let n=bs(e),r=this.imageServices[n];if(r&&(!t||r.real))return r;if(!this.config.enableFetching)throw Error("Fetching is not enabled");let s=await this.fetch(n).then(o=>o.json());return!s.id&&s["@id"]&&(s.id=s["@id"]),s.id!==e&&(s.id=e,s["@id"]&&(s["@id"]=e)),this.imageServices[n]=Object.assign(s,{real:!0}),this.imageServices[n]}async fetch(e,t){return fetch(e,t)}async loadService(e,t=!1){if(!this.config.disableThrottling){let s=!0;for(;s;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(o=>setTimeout(o,500));else{s=!1;break}}let n=this.knownImageServers[po(yt(e))];if(n&&!n.malformed&&!t){await n.result;let s=this.loadServiceSync(e);if(s)return s}this.fetchingCount++;let r=await this.fetchService(yt(e),t);return this.fetchingCount--,r.real&&this.sample(r,e),r}loadServiceSync(e){let t=bs(yt(e));return this.imageServices[t]?this.imageServices[t]:this.config.approximateServices?this.predict(e):null}};function Yk(i={}){let e=i.events||AS(),t=i.loader||new kS;return{store:_S((r,s)=>({loaded:{},loadServiceSync:(o,a,l)=>{let c=o.id||o["@id"],u=s().loaded[c];if(u&&u.status==="done")return u.service;if(u&&u.status==="loading")return null;if(u&&u.status==="error")throw Error("Failed to load image service");let d={id:yt(o),width:o.width||(a==null?void 0:a.width)||0,height:o.height||(a==null?void 0:a.height)||0,source:o},h=t.loadServiceSync(d);return h?(r(f=>({loaded:{...f.loaded,[c]:{status:"done",service:h,real:!0}}})),e.emit("image-service.loaded",{id:c,service:h})):l&&s().loadService(o,a).then(()=>{}),h},loadService:async(o,a)=>{let l=o.id||o["@id"],c=s().loaded[l];if(c&&c.status==="done")return c.service;if(c&&c.status==="loading")return new Promise((u,d)=>{let h=f=>{f.id===l&&(e.off("image-service.loaded",h),u(f.service||o))};e.on("image-service.loaded",h)});if(c&&c.status==="error"&&!(a!=null&&a.force))throw Error("Failed to load image service");e.emit("image-service.loading",{id:l});try{let u={id:yt(o),width:o.width||0,height:o.height||0,source:o},d=await t.loadService(u,a==null?void 0:a.force);return r(h=>({loaded:{...h.loaded,[l]:{status:"done",service:d,real:d.real}}})),e.emit("image-service.loaded",{id:l,service:d}),d}catch(u){throw e.emit("image-service.error",{id:l,error:u}),u}}})),events:e}}Yk();const Xk=new kS,DS=new Map;function Zk(i,{vault:e=La,dereference:t=!1,...n}={}){let r=DS.get(e);return r||(r=Qk(e),DS.set(e,r)),r.getBestThumbnailAtSize(i,n,t)}function Qk(i=La,e={}){let t=e.imageServiceLoader||Xk;async function n(r,s,o=!1,a=[],l){let c=()=>t.getThumbnailFromResource(void 0,s,o,a);if(!r)return await t.getThumbnailFromResource(void 0,s,o,a);if(typeof r=="string"){let h=uf(r);return h&&a.push(h),await t.getThumbnailFromResource(void 0,s,o,a)}let u=i.get(r,{skipSelfReturn:!1});if(typeof u=="string")return{best:uf(u),fallback:[],log:[]};if(!u)return await c();switch(await(async h=>{if(h&&h.thumbnail&&h.thumbnail.length){let f=i.get(h.thumbnail[0]),p=await t.getImageCandidates(f,o);p&&p.length&&a.push(...p)}})(u),u.type){case"Annotation":{let h=Array.isArray(u.body)?u.body:[u.body],f=i.get(h[0]);return l&&!f.width&&(f.width=l.width,f.height=l.height),await t.getThumbnailFromResource(f,s,o,a)}case"Canvas":{let h=u;return n(h.items[0],s,o,a,{width:h.width,height:h.height})}case"AnnotationPage":return n(u.items[0],s,o,a,l);case"Choice":{let h=u;return!h.items||h.items[0]?await c():n(h.items[0],s,o,a,l)}case"Collection":{let h=u,f=h.items[0];return f?n(f,s,o,a,l):await c()}case"Manifest":{let h=u,f=h.items[0];return f?n(f,s,o,a,l):await c()}case"SpecificResource":case"Image":case"Dataset":case"Sound":case"Text":case"TextualBody":case"Video":return l&&!u.width&&(u.width=l.width,u.height=l.height),t.getThumbnailFromResource(u,s,o,a)}return await c()}return{getBestThumbnailAtSize:n}}function sr(i){return typeof i=="string"?!1:i&&!i.type&&"source"in i?(i.type="SpecificResource",!0):!!i&&i.type==="SpecificResource"}function Tc(...i){return e=>i.reduce((t,n)=>n(t),e)}const OS=["Collection","Manifest","Canvas","AnnotationPage","AnnotationCollection","Annotation","ContentResource","Range","Service","Selector","Agent"];function Jk(i,e){if(i==null)throw Error("Null or undefined is not a valid entity.");if(Array.isArray(i))throw Error("Array is not a valid entity");if(typeof i!="object"){if(e)return e;throw Error(`${typeof i} is not a valid entity`)}if(typeof i.type=="string"){let t=OS.indexOf(i.type);if(t!==-1)return OS[t]}if(i.profile)return"Service";throw Error("Resource type is not known")}var eD=class dL{constructor(e,t={}){Lr(this,"traversals",void 0),Lr(this,"options",void 0),Lr(this,"_traverseManifest",Tc(this.traverseManifestItems.bind(this),this.traverseNavPlace.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this),this.traverseManifestStructures.bind(this),this.traverseInlineAnnotationPages.bind(this))),Lr(this,"_traverseCanvas",Tc(this.traverseCanvasItems.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this),this.traverseInlineAnnotationPages.bind(this))),Lr(this,"_traverseAnnotationPage",Tc(this.traverseAnnotationPageItems.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this))),Lr(this,"_traverseRange",Tc(this.traverseRangeRanges.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this))),this.traversals={collection:[],manifest:[],canvas:[],annotationCollection:[],annotationPage:[],annotation:[],contentResource:[],choice:[],range:[],service:[],agent:[],specificResource:[],geoJson:[],...e},this.options={allowUndefinedReturn:!1,...t}}static all(e){return new dL({collection:[e],manifest:[e],canvas:[e],annotationCollection:[e],annotationPage:[e],annotation:[e],contentResource:[e],choice:[e],range:[e],service:[e],geoJson:[e],specificResource:[e],agent:[e]})}traverseDescriptive(e){return e.thumbnail&&(e.thumbnail=ir(e.thumbnail).map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e.provider&&(e.provider=e.provider.map(t=>this.traverseAgent(t,e))),e}traverseLinking(e){return e.seeAlso&&(e.seeAlso=ir(e.seeAlso).map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e.service&&(e.service=ir(e.service).map(t=>this.traverseService(t))),e.services&&(e.services=ir(e.services).map(t=>this.traverseService(t,e))),e.logo&&(e.logo=ir(e.logo).map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e.homepage&&(e.homepage=ir(e.homepage).map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e.partOf&&(e.partOf=e.partOf.map(t=>typeof t=="string"||!t.type?this.traverseType(t,{parent:e},this.traversals.contentResource):t.type==="Canvas"?this.traverseType(t,{parent:e},this.traversals.canvas):t.type==="AnnotationCollection"?this.traverseType(t,{parent:e},this.traversals.annotationCollection):t.type==="Collection"?this.traverseType(t,{parent:e},this.traversals.collection):this.traverseType(t,{parent:e},this.traversals.contentResource))),e.start&&(sr(e.start)?e.start=this.traverseSpecificResource(e.start,"Canvas",e):e.start=this.traverseType(e.start,{parent:e},this.traversals.canvas)),e.rendering&&(e.rendering=e.rendering.map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e.supplementary&&(e.supplementary=e.supplementary.map(t=>this.traverseType(t,{parent:e},this.traversals.contentResource))),e}traverseCollectionItems(e){return e.items&&e.items.map(t=>t.type==="Collection"?this.traverseCollection(t):this.traverseManifest(t)),e}traverseCollection(e,t){return this.traverseType(this.traverseDescriptive(this.traverseNavPlace(this.traverseInlineAnnotationPages(this.traverseLinking(this.traverseLinkedCanvases(this.traverseCollectionItems(e)))))),{parent:t},this.traversals.collection)}traverseGeoJson(e,t){return this.traverseType(e,{parent:t},this.traversals.geoJson)}traverseNavPlace(e){return e.navPlace&&(e.navPlace=this.traverseGeoJson(e.navPlace,e)),e}traverseManifestItems(e){return e.items&&(e.items=e.items.map(t=>this.traverseCanvas(t))),e}traverseManifestStructures(e){return e.structures&&(e.structures=e.structures.map(t=>this.traverseRange(t))),e}traverseManifest(e,t){return this.traverseType(this._traverseManifest(e),{parent:t},this.traversals.manifest)}traverseCanvasItems(e){return e.items=(e.items||[]).map(t=>this.traverseAnnotationPage(t,e)),e}traverseInlineAnnotationPages(e){return typeof e=="string"||!e||e.annotations&&(e.annotations=e.annotations.map(t=>this.traverseAnnotationPage(t,e))),e}traverseCanvas(e,t){return this.traverseType(this._traverseCanvas(e),{parent:t},this.traversals.canvas)}traverseAnnotationPageItems(e){return e.items&&(e.items=e.items.map(t=>this.traverseAnnotation(t,e))),e}traverseAnnotationPage(e,t){return this.traverseType(this._traverseAnnotationPage(e),{parent:t},this.traversals.annotationPage)}traverseAnnotationBody(e){return Array.isArray(e.body)?e.body=e.body.map(t=>this.traverseContentResource(t,e)):e.body&&(e.body=this.traverseContentResource(e.body,e)),e}traverseLinkedCanvases(e){return e.placeholderCanvas&&(e.placeholderCanvas=this.traverseCanvas(e.placeholderCanvas)),e.accompanyingCanvas&&(e.accompanyingCanvas=this.traverseCanvas(e.accompanyingCanvas)),e}traverseAnnotation(e,t){return this.traverseType(this.traverseLinking(this.traverseAnnotationBody(this.traverseDescriptive(e))),{parent:t},this.traversals.annotation)}traverseContentResourceLinking(e){return typeof e=="string"||!e||e&&e.service&&(e.service=ir(e.service||[]).map(t=>this.traverseService(t,e))),e}traverseContentResource(e,t){return e.type==="Choice"&&(e.items=e.items.map(n=>this.traverseContentResource(n,e))),sr(e)?this.traverseSpecificResource(e,"ContentResource"):this.traverseType(this.traverseInlineAnnotationPages(this.traverseContentResourceLinking(e)),{parent:t},this.traversals.contentResource)}traverseSpecificResource(e,t,n){let r=e.source;return typeof e.source=="string"&&(r={id:e.source,type:t||"unknown"}),this.traverseType({...e,source:t==="Canvas"||r.type==="Canvas"?this.traverseType(r,{parent:n},this.traversals.canvas):t==="ContentResource"?this.traverseContentResource(r,{parent:n}):this.traverseUnknown(r,{parent:n,typeHint:t})},{parent:n},this.traversals.specificResource)}traverseRangeRanges(e){return e.items&&(e.items=e.items.map(t=>typeof t=="string"?this.traverseCanvas({id:t,type:"Canvas"},e):sr(t)?this.traverseSpecificResource(t,"Canvas",e):t.type==="Manifest"?this.traverseManifest(t,e):this.traverseRange(t,e))),e}traverseRange(e,t){return this.traverseType(this._traverseRange(e),{parent:t},this.traversals.range)}traverseAgent(e,t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(e)),{parent:t},this.traversals.agent)}traverseType(e,t,n){return n.reduce((r,s)=>{let o=s(r,t);return o===void 0&&!this.options.allowUndefinedReturn?r:o},e)}traverseService(e,t){let n=Object.assign({},e);return n&&n.service&&(n.service=ir(n.service).map(r=>this.traverseService(r))),this.traverseType(n,{parent:t},this.traversals.service)}traverseUnknown(e,{parent:t,typeHint:n}={}){let r=Jk(e,n);switch(r){case"Collection":return this.traverseCollection(e,t);case"Manifest":return this.traverseManifest(e,t);case"Canvas":return this.traverseCanvas(e,t);case"AnnotationPage":return this.traverseAnnotationPage(e,t);case"Annotation":return this.traverseAnnotation(e,t);case"ContentResource":return this.traverseContentResource(e,t);case"Range":return this.traverseRange(e,t);case"Service":return this.traverseService(e,t);case"Agent":return this.traverseAgent(e,t);default:throw Error(`Unknown or unsupported resource type of ${r}`)}}};function Ec(i,e){let t="unknown";if(!i)return;if(typeof i=="string")return{id:i,type:t};if(sr(i))return Ec(i.source);let n=i.type||i["@type"],r=i.id||i["@id"];if(n&&n.indexOf(":")!==-1&&(n=n.split(":").pop()),r&&n)return{id:r,type:n}}const Da={},Nt="iiif-parser:hasPart",or="iiif-parser:partOf",Oa="iiif-parser:isExternal",cn="__$UNSET$__",MS="__$UNWRAP$__",_e=[];Object.freeze(_e),Object.freeze(Da);function tD(i){if(i===Da||Object.keys(i).length===0)return!0;for(let e in i)return!1;return!0}function df(i,e){if(e&&e["@explicit"]){let t={},n=Object.keys(e);for(let r of n)r===or||r==="@explicit"||(tD(e[r])?t[r]=i[r]:t[r]=e[r]);return t}return i}function FS(i,e,t){let n=Ec(e);if(!n)return[void 0,void 0];let r=i.requests[n.id],s=n.type||i.mapping[n.id];if(!s||r&&r.resourceUri&&(!i.entities[s]||!i.entities[s][r.resourceUri]))return[void 0,void 0];let o=i.entities[s][r?r.resourceUri:n.id];if(n.type&&!o)return FS(i,{id:n.id},t);if(o&&o[Nt]){let a=o[Nt].find(c=>t?c[or]===t.id:c[or]===o.id);return[df(o,a),o]}return[o,o]}const iD={id:"https://iiif-parser/annotation-page",type:"AnnotationPage",behavior:_e,label:null,thumbnail:_e,summary:null,requiredStatement:null,metadata:_e,rights:null,provider:_e,items:_e,seeAlso:_e,homepage:_e,rendering:_e,service:_e},nD={id:"https://iiif-parser/empty-canvas",type:"Canvas",label:null,behavior:_e,thumbnail:_e,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:_e,rights:null,navDate:null,provider:_e,items:_e,annotations:_e,seeAlso:_e,homepage:_e,partOf:_e,rendering:_e,service:_e,duration:0,height:0,width:0},rD={id:"https://iiif-parser/empty-collection",type:"Collection",label:null,viewingDirection:"left-to-right",behavior:_e,thumbnail:_e,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:_e,rights:null,navDate:null,provider:_e,items:_e,annotations:_e,seeAlso:_e,homepage:_e,partOf:_e,rendering:_e,service:_e,services:_e},sD={id:"https://iiif-parser/empty-manifest",type:"Manifest",annotations:_e,behavior:_e,homepage:_e,items:_e,label:null,metadata:_e,navDate:null,provider:_e,partOf:_e,accompanyingCanvas:null,placeholderCanvas:null,rendering:_e,requiredStatement:null,rights:null,seeAlso:_e,service:_e,services:_e,start:null,structures:_e,summary:null,thumbnail:_e,viewingDirection:"left-to-right"},oD={id:"https://iiif-parser/empty-canvas",type:"Range",label:null,behavior:_e,thumbnail:_e,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:_e,rights:null,navDate:null,provider:_e,items:_e,annotations:_e,seeAlso:_e,homepage:_e,partOf:_e,rendering:_e,service:_e,start:null,supplementary:null,viewingDirection:"left-to-right"},aD={id:"https://iiif-parser/empty-agent",type:"Agent",label:{},logo:_e,seeAlso:_e,homepage:_e},lD={id:"https://iiif-parser/empty-service",type:"UnknownService"};function wc(i,e={}){if(Array.isArray(i))return wc(i[0]);if(typeof i=="string"){let[t,n]=i.split("#");return n?{type:"SpecificResource",source:{id:t,type:e.typeHint||"Unknown"},selector:{type:"FragmentSelector",value:n}}:{type:"SpecificResource",source:{id:t,type:e.typeMap&&e.typeMap[t]||e.typeHint||"Unknown"}}}if(i.type==="Choice"||i.type==="List"||i.type==="Composite"||i.type==="Independents")return wc(i.items[0]);if(!i.type&&"source"in i&&(i.type="SpecificResource"),i.type==="SpecificResource"){i.source.type==="Canvas"&&i.source.partOf&&typeof i.source.partOf=="string"&&(i.source.partOf=[{id:i.source.partOf,type:"Manifest"}]);let t=typeof i.source=="string"?i.source:i.source.id;if(t!=null&&t.includes("#")){let n=wc(t,e);n&&(i.selector=n.selector,i.source=n.source)}return i.selector?{...i,type:"SpecificResource",source:i.source,selector:i.selector}:{...i,type:"SpecificResource",source:i.source}}if(i.id){i.type==="Canvas"&&i.partOf&&typeof i.partOf=="string"&&(i.partOf=[{id:i.partOf,type:"Manifest"}]);let[t,n]=i.id.split("#");return n?{type:"SpecificResource",source:{...i,id:t},selector:{type:"FragmentSelector",value:n}}:{type:"SpecificResource",source:{...i,id:t}}}return{type:"SpecificResource",source:i}}function cD(){return{Collection:{},Manifest:{},Canvas:{},AnnotationPage:{},AnnotationCollection:{},Annotation:{},ContentResource:{},Range:{},Service:{},Selector:{},Agent:{}}}function NS(i,e){if(typeof i=="string")return{id:i,type:e};if(!i.id)throw Error(`Invalid resource does not have an ID (${JSON.stringify(i)}, ${e})`);return i}function uD(i,e){return(t,n)=>{let r=i[t]?i[t]:{};return(s,o)=>{let a=NS(s,n||t);return a&&a.id&&t?(r[a.id]=r[a.id]?ff(r[a.id],a,{parent:o.parent,isTopLevel:e.id===a.id}):ff({id:a.id,type:a.type},a,{parent:o.parent,isTopLevel:e.id===a.id}),{id:a.id,type:t==="ContentResource"?t:a.type}):a}}}function hf(i,e,t){if(!e)return i;if(Array.isArray(i)){if(!Array.isArray(e))throw Error("Cannot merge array with non-array");let n=[...i];for(let r of e)if(r["@id"]&&!r.id&&(r.id=r["@id"]),r["@type"]&&!r.type&&(r.type=r["@type"]),r!=null)if(Array.isArray(r))n.push(r);else if(typeof r=="object"&&r.id&&r.type){let s=n.findIndex(o=>o.id===r.id&&o.type===r.type);s>=0&&(n[s]=hf(n[s],r))}else i.indexOf(r)===-1&&n.push(r);return n}else if(typeof i=="object"){if(Array.isArray(e)||typeof e!="object")throw Error("Cannot merge object with non-object");let n={...i},r=[],s=[],o=Object.keys(i).filter(c=>c!==Nt&&c!=="id"&&c!=="type"),a={},l={};for(let[c,u]of Object.entries(e)){if(c===Nt||c==="id"||c==="type")continue;let d=n[c];d===u?s.push(c):d===_e||!d?(r.push(c),n[c]=u):(d&&u&&(a[c]=d,l[c]=u),n[c]=hf(d,u),n[c]===a[c]&&(s.push(c),delete a[c]))}if(t&&(t.parent&&t.parent.id||t.isTopLevel)){let c=[],u={};if(t.parent?u[or]=t.parent.id:t.isTopLevel&&(u[or]=i.id),n[Nt]&&n[Nt].length){let d=!(n[Nt]||[]).find(f=>f["@explicit"]),h=r.length>0||s.length!==o.length;if(d&&h)for(let f of n[Nt]){let p={...f},g=Object.keys(a);if(p){p["@explicit"]=!0;for(let m of o)m!==Nt&&(p[m]=Da);for(let m of g)p[m]=a[m]}c.push(p)}else c.push(...n[Nt]);if(h){let f=Object.keys(l);u["@explicit"]=!0;for(let p of r)u[p]=Da;for(let p of s)u[p]=Da;for(let p of f)u[p]=l[p]}}u.id=n.id,u.type=n.type,c.push(u),n[Nt]=c}return n}else if(i)return i;return e}function ff(i,e,t){if(typeof i=="string")return i;if(e.id!==i.id||e.type!==i.type){if(e.type==="ImageService3")return e;if(i.type==="ImageService3")return i;throw Error(`Can only merge entities with identical identifiers and type! ${e.type}(${e.id}) => ${i.type}(${i.id})`)}return hf({...i},e,t)}function dD(i){return(e,t)=>n=>{let{id:r,type:s}=NS(n,t||e);if(r===void 0)throw Error("Found invalid entity without an ID.");return e==="ContentResource"||e==="Service"?i[r]=e:i[r]=s,n}}function hD(i){let e=Object.assign({},i);if(e["@id"]&&(e.id=e["@id"]),e["@type"]&&(e.type=e["@type"]),e.service){let t=[];e.service=Array.isArray(e.service)?e.service:[e.service];for(let n of e.service)t.push({id:n["@id"]||n.id,type:n["@type"]||n.type});e.service=t}return Object.assign({},lD,e)}function fD(i){return e=>{i.Service=i.Service?i.Service:{};let t=e.id||e["@id"],n=hD(e);return n&&n.id&&(i.Service[n.id]?i.Service[t]=ff(i.Service[t],n):i.Service[t]=n),e}}function pD(i){let e=JSON.stringify(i),t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);let r=t>>>0,s=r.toString(16);return s.length%2?"0"+s:s}function pf(i){return e=>typeof e=="string"?{id:e,type:i}:e.id?e.type?e:{type:i,...e}:{id:`vault://${pD(e)}`,type:i,...e}}function go(i){return e=>({...i,...e})}function Ma(i){return Array.isArray(i)?i:[i]}function gD(i){return i.body&&(i.body=Ma(i.body)),i.seeAlso&&(i.seeAlso=Ma(i.seeAlso)),i.audience&&(i.audience=Ma(i.audience)),i.accessibility&&(i.accessibility=Ma(i.accessibility)),i.motivation&&(i.motivation=Ma(i.motivation)),i}function BS(i,{typeHint:e,partOfTypeHint:t}={}){if(typeof i=="string"&&(i={id:i,type:e||"unknown"}),sr(i))return typeof i.source=="string"&&(i.source={id:i.source,type:e||"unknown"}),i.source.type==="Canvas"&&i.source.partOf&&typeof i.source.partOf=="string"&&(i.source.partOf=[{id:i.source.partOf,type:t||"Manifest"}]),i;let n;if((i.id||"").indexOf("#")!==-1){let[r,s]=(i.id||"").split("#");i.id=r,s&&(n={type:"FragmentSelector",value:s})}return{type:"SpecificResource",source:i,selector:n}}function mD(i){let e=Object.assign({},i);return i&&i.items&&(e.items=i.items.map(t=>typeof t=="string"||t.type==="Canvas"?BS(t):t)),e}function vD(i){let e=Object.assign({},i);return e.start?(e.start=BS(e.start,{typeHint:"Canvas"}),e):i}function yD(i){let e=Object.assign({},i);return e.target?(e.target=wc(e.target,{typeHint:"Canvas"}),e):i}function SD(i){return i}function gf(i){return i.items===void 0&&(i[Oa]=!0),i}function xD(i){let e=wS(i),t=cD(),n={},r=uD(t,e),s=dD(n),o=new eD({collection:[gf,go(rD),s("Collection"),r("Collection")],manifest:[gf,go(sD),vD,s("Manifest"),r("Manifest")],canvas:[go(nD),s("Canvas"),r("Canvas")],annotationPage:[gf,pf("AnnotationPage"),go(iD),s("AnnotationPage"),r("AnnotationPage")],annotation:[pf("Annotation"),gD,yD,s("Annotation"),r("Annotation")],contentResource:[pf("ContentResource"),s("ContentResource"),r("ContentResource")],range:[go(oD),mD,s("Range","Canvas"),r("Range","Canvas")],agent:[go(aD),s("Agent"),r("Agent")],specificResource:[SD],service:[fD(t)]}),a=o.traverseUnknown(e);return{entities:t,resource:a,mapping:n}}function TD(i){let e={};for(let[t,n]of i){if(t===MS&&n!==cn)return n;n!==cn&&n!=null&&(e[t]=n)}return e}function ED(i,e,t){if(!e.type||!e.id)throw Error("Unknown entity");if(!t[e.type])throw Error(`Serializer not found for ${e.type}`);function n(r,s,o=0){let a=t[r.type];if(!a)return cn;if(o>20)throw Error("Circular reference: "+r.id+" "+r.type);let[l,c]=FS(i,r.type?r:r.id,s)||(r.id&&r.type?r:null);if(!l)return cn;let u=a(l,i,{parent:s,isTopLevel:e.id===r.id,fullResource:c}),d=u.next();for(;!d.done;){let h=d.value,f=cn;if(h)if(Array.isArray(h)){let p=[];for(let g of h)p.push(n(g,r,o+1));f=p}else f=n(h,r,o+1);d=u.next(f)}return d.value===cn?cn:TD(d.value)}return n(e)}function Fa(i,{allowSourceString:e=!0,allowString:t=!1,allowedStringType:n}={}){let r=s=>{if(e&&s&&s.source&&typeof s.source!="string"){let o=Object.keys(s.source);if(s.source.id&&s.source.type&&o.length===2)return{...s,source:s.source.id}}return s};if(i){if(i.source&&i.source.partOf)return r(i);let s=Object.keys(i);if(s.length===2&&i.type&&i.source||s.length===3&&i.type&&i.source&&s.indexOf("selector")!==-1&&!i.selector)return t&&(!n||n===i.source.type)?i.source.id:i.source.type==="ContentResource"?{type:"SpecificResource",source:i.source.id}:i.source;if(i.selector&&!Array.isArray(i.selector)&&typeof i.selector!="string"&&i.selector.type==="FragmentSelector"){let o=`${i.source.id}#${i.selector.value}`;return t?o:{id:o,type:i.source.type}}}return r(i)}function mo(i){if(!i)return;let e=Object.keys(i);if(e.length!==0){if(e.length===1){let t=e[0];if(!t)return"";let n=(i[t]||[]).join("");return t==="@none"||t==="none"||t==="en"?n:{"@language":t,"@value":n}}return e.map(t=>({"@language":t,"@value":(i[t]||[]).join("")}))}}function US(i){return Array.isArray(i)?i.map(e=>US(e)):typeof i=="string"?i:i.type&&i.type==="Canvas"?i.id:i}function Dr(i,e=!1){if(i)return i.length>1&&!e?i:i[0]||void 0}function wD(i){if(i){if(typeof i=="string")return{"@id":i};if("@id"in i){let e={...i};return delete e["@type"],e}return{"@context":"http://iiif.io/api/image/2/context.json","@id":i.id,profile:`http://iiif.io/api/image/2/profiles/${i.profile}.json`}}}function _s(i,e){return[["@id",i.id],["@type",e],["format",i.format],["height",i.height],["width",i.width],["viewingDirection",i.viewingDirection==="left-to-right"?void 0:i.viewingDirection],["license",i.license?i.license:void 0]]}function*As(i){let e=i.provider?yield i.provider[0]:void 0;return[["label",mo(i.label)],["metadata",i.metadata&&i.metadata.length?i.metadata.map(t=>({label:mo(t.label)||"",value:mo(t.value)||""})):void 0],["description",mo(i.summary)],["thumbnail",Dr(yield i.thumbnail)],["navDate",i.navDate],["logo",e?Dr(e.logo):void 0],["homepage",e?e.homepage:void 0],["attribution",i.requiredStatement?mo(i.requiredStatement.value):void 0]]}function*Na(i){let e=i.start&&i.start.type&&i.start.type==="SpecificResource"?Fa(i.start):i.start;return[["seeAlso",Dr(yield i.seeAlso)],["service",Dr((i.service||[]).map(wD))],["rendering",Dr(yield i.rendering)],["startCanvas",e?e.id:void 0]]}function bD(i){return i.type==="SpecificResource"}function _D(i){return i&&i.type==="FragmentSelector"}function AD(i){if(i&&bD(i)){let e=i.id,t=i.selector?Array.isArray(i.selector)?i.selector[0]:i.selector:void 0;return _D(t)&&(e+="#"+t.value),e}return i==null?void 0:i.id}const RD={Manifest:function*(i,e,{isTopLevel:t}){return[...t?[["@context","http://iiif.io/api/presentation/2/context.json"]]:[],..._s(i,"sc:Manifest"),...yield*As(i),...yield*Na(i),["sequences",[{"@id":`${i.id}/sequence0`,"@type":"sc:Sequence",canvases:yield i.items}]],["structures",yield i.structures]]},Canvas:function*(i){let e=yield i.items,t=e[0];return[..._s(i,"sc:Canvas"),...yield*As(i),...yield*Na(i),["images",t?[t.resources]:void 0],["annotations",i.annotations&&i.annotations.length?Dr(yield i.annotations):void 0]]},AnnotationPage:function*(i){return[..._s(i,"sc:AnnotationList"),...yield*As(i),["resources",i.items&&i.items.length?Dr(yield i.items):void 0]]},Annotation:function*(i){return[["@id",i.id],["@type","oa:Annotation"],["motivation","sc:painting"],["on",US(i.target)],["resource",Dr(yield i.body,!0)]]},ContentResource:function*(i){switch(i.type){case"Image":return[..._s(i,"dctypes:Image"),...yield*As(i),...yield*Na(i)];case"Text":case"Dataset":default:return[..._s(i,void 0),...yield*As(i)]}},AnnotationCollection:function*(i){return[["@id",i.id],["@type","sc:Layer"],["label",mo(i.label)]]},Collection:function*(i){return[..._s(i,"sc:Collection"),...yield*As(i),...yield*Na(i),["members",yield*i.items]]},Range:function*(i){let e=[],t=[];if(i.items)for(let n of i.items){let r=n.type==="SpecificResource"?n.source:n;if(r){let s=yield r;e.push({"@id":AD(n),"@type":r.type,label:s?s.label:void 0,within:i.id}),r.type==="Canvas"&&t.push(r.id)}}return[..._s(i,"sc:Range"),...yield*As(i),...yield*Na(i),["canvases",t.length===e.length?t:void 0],["members",t.length===e.length?void 0:e]]}};function Rs(i){var e;return[["id",(e=i.id)!=null&&e.startsWith("vault://")?void 0:i.id],["type",i.type],["format",i.format],["profile",i.profile],["height",i.height||void 0],["width",i.width||void 0],["duration",i.duration||void 0],["viewingDirection",i.viewingDirection==="left-to-right"?void 0:i.viewingDirection],["behavior",i.behavior&&i.behavior.length?i.behavior:void 0],["timeMode",i.timeMode],["motivation",Array.isArray(i.motivation)?i.motivation[0]:i.motivation],[Nt,cn]]}function Dt(i){if(i===cn||!i||i.length===0)return;let e=i.filter(t=>t!==cn);if(e.length!==0)return e}function $S(i){if(i&&i.type&&i.type==="ImageService2"){let{id:e,type:t,profile:n,...r}=i,s=typeof n=="string"?n:Array.isArray(n)?n.find(o=>typeof o=="string"):"";return{"@id":e,"@type":t,profile:s?s.startsWith("http")?s:`http://iiif.io/api/image/2/${s}.json`:"http://iiif.io/api/image/2/level0.json",...r}}return i}function HS(i){if(Array.isArray(i)||(i=i?[i]:[]),!(!i||i.length===0))return i.map($S)}function*Or(i){return[["label",i.label],["metadata",Dt(i.metadata)],["summary",i.summary],["requiredStatement",i.requiredStatement],["rights",Array.isArray(i.rights)?i.rights[0]||void 0:i.rights||void 0],["navDate",i.navDate],["language",i.language],["thumbnail",Dt(yield i.thumbnail)],["placeholderCanvas",yield i.placeholderCanvas],["accompanyingCanvas",yield i.accompanyingCanvas],["provider",Dt(yield i.provider)]]}function*Mr(i,e){let t=[];for(let n of i.partOf||[])n.type==="Manifest"&&e.type==="Manifest"||t.push(yield n);return[["seeAlso",Dt(yield i.seeAlso)],["service",Dt(HS(i.service))],["services",Dt(HS(i.services))],["rendering",Dt(yield i.rendering)],["supplementary",Dt(yield i.supplementary)],["homepage",Dt(yield i.homepage)],["logo",Dt(yield i.logo)],["partOf",Dt(t)],["start",i.start?Fa(i.start):i.start]]}const CD={Manifest:function*(i,e,{isTopLevel:t}){if(!t)return[...Rs(i),...yield*Or(i),["navPlace",i.navPlace]];let n="http://iiif.io/api/presentation/3/context.json";return(i.navPlace||zS(i))&&(n=["http://iiif.io/api/presentation/3/context.json","http://iiif.io/api/extension/navplace/context.json"]),[["@context",i["@context"]?i["@context"]:n],...Rs(i),...yield*Or(i),...yield*Mr(i),["items",yield i.items],["structures",Dt(yield i.structures)],["annotations",Dt(yield i.annotations)],["navPlace",i.navPlace]]},Canvas:function*(i,e,{parent:t}){return t&&t.type!=="Manifest"&&t.type!=="Canvas"?[["id",i.id]]:[...Rs(i),...yield*Or(i),...yield*Mr(i,t),["items",yield i.items],["annotations",Dt(yield i.annotations)],["navPlace",i.navPlace]]},Agent:function*(i){return[["id",i.id],["type","Agent"],["label",i.label],...yield*Mr(i)]},AnnotationPage:function*(i){var n;let e=Object.entries(i).map(([r,s])=>[r,Array.isArray(s)?Dt(s):s]).filter(([r,s])=>r!=="items"&&r!=="id"&&r!==Nt&&r!==or&&r!==Oa),t=yield i.items;return[["id",(n=i.id)!=null&&n.startsWith("vault://")?void 0:i.id],...e,...yield*Mr(i),["items",t.length||i[Oa]===!1?t:cn]]},Service:function*(i){return[[MS,$S(i)]]},Annotation:function*(i){let e=Object.entries(i).map(([n,r])=>n==="motivation"?[n,Array.isArray(r)?r[0]:r]:n==="target"?[n,Fa(r,{allowString:!0,allowSourceString:!0,allowedStringType:"Canvas"})]:[n,Array.isArray(r)?Dt(r):r]).filter(([n])=>n!=="body"&&n!==Nt&&n!==Oa),t;if(Array.isArray(i.body)){let n=[];for(let r of i.body)if(r&&sr(r)){let s={...r};r.source.type==="Canvas"?s.source=r.source:s.source=yield r.source,n.push(Fa(s,{allowSourceString:!0}))}else n.push(yield r);t=n}else i.body&&sr(i.body)?(t={...i.body},t.source=yield i.body.source):t=yield i.body;return[...e,...yield*Or(i),...yield*Mr(i),["body",t.length===1?t[0]:t]]},ContentResource:function*(i){return ID([...Rs(i),...yield*Or(i),...yield*Mr(i),["annotations",Dt(yield i.annotations)],["items",Dt(yield i.items)]],i)},AnnotationCollection:function*(i){return[["id",i.id],["type","AnnotationCollection"],["label",i.label]]},Collection:function*(i,e,{isTopLevel:t}){if(t){let n="http://iiif.io/api/presentation/3/context.json";return(i.navPlace||zS(i))&&(n=["http://iiif.io/api/extension/navplace/context.json","http://iiif.io/api/presentation/3/context.json"]),[["@context",n],...Rs(i),...yield*Or(i),...yield*Mr(i),["items",Dt(yield i.items)],["navPlace",i.navPlace]]}return[...Rs(i),...yield*Or(i),["navPlace",i.navPlace]]},Range:function*(i){let e=[];for(let t of i.items)t.type==="Range"?e.push(yield t):t&&t.type==="SpecificResource"?e.push(Fa(t)):e.push(t);return[...Rs(i),...yield*Or(i),...yield*Mr(i),["items",e],["annotations",Dt(yield i.annotations)],["navPlace",i.navPlace]]}};function ID(i,e){let t=Object.keys(e),n=i.map(([r])=>r);for(let r of t)r===Nt||r===Oa||n.indexOf(r)===-1&&e[r]!==void 0&&i.push([r,e[r]]);return i}function zS(i){if(!i.items||!Array.isArray(i.items))return!1;for(let e of i.items)if(e.navPlace)return!0;return!1}function PD(i){let e=encodeURIComponent(i);return(typeof btoa>"u"?Buffer.from(e,"utf-8").toString("base64"):btoa(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function LD(i){let e=kD(i),t=e.replace(/-/g,"+").replace(/_/g,"/"),n=typeof atob>"u"?Buffer.from(t,"base64").toString("utf-8"):atob(t);return decodeURIComponent(n).trim()}function kD(i){let e=i.length%4;if(e===1)throw Error("InvalidLengthError: Input base64url string is the wrong length to determine padding");return i+(e?"====".slice(0,4-e):"")}function DD(i,e){return sr(i)?typeof i.source=="string"?{...i,source:e}:{...i,source:{...i.source||{},id:e}}:{...i,id:e}}function VS(i,e){var n;let t=[];for(let r of e.items)if(r.type==="SpecificResource"&&((n=r.source)==null?void 0:n.type)==="Canvas"&&(r.source.id.indexOf("#")===-1?t.push(r.source):t.push({id:r.source.id.split("#")[0],type:"Canvas"})),r.type==="Range"&&t.push(...VS(i,i.get(r))),r.type==="SpecificResource"){let s=typeof r.source=="string"?r.source:r.source.id;t.push({id:s,type:"Canvas"})}return t}function OD(i=La,e,t,n=!1){let r=e.behavior||[],s=t?i.get(t):null;if(!s)return[];let o=s.behavior||[],a=n?!1:r.includes("paged"),l=a?!1:r.includes("continuous"),c=a||l?!1:r.includes("individuals"),u=o.includes("facing-pages"),d=o.includes("non-paged");if(u||d||c||n)return[{id:s.id,type:"Canvas"}];let[h,f]=GS(i,e);if(l)return h;let p=h.findIndex(g=>g.id===t);if(p===-1)return[];for(let g of f)if(g.includes(p))return g.map(m=>h[m]);return[{id:s.id,type:"Canvas"}]}function GS(i=La,e,{disablePaging:t,skipNonPaged:n}={}){let r=e.behavior||[],s=r.includes("paged"),o=s?!1:r.includes("continuous"),a=s||o?!1:r.includes("individuals"),l=e.type==="Manifest"?e.items:VS(i,e);if(o)return[l,[l.map((p,g)=>g)]];if(a||!s||t)return[l,l.map((p,g)=>[g])];let c=[],u=[],d=()=>{u.length&&(c.push([...u]),u=[])},h=0,f=!1;for(let p=0;p<l.length;p++){let g=i.get(l[p]),m=g.behavior||[];if(m.includes("non-paged")){p===h&&h++,n||(d(),c.push([p]),d());continue}if(p===h||m.includes("facing-pages")){u.length&&(f=!0),d(),c.push([p]),d();continue}if(u.push(p),f){d(),f=!1;continue}u.length>1&&d()}return u.length&&d(),[l,c]}const bt=function(i){return function(){let e={type:i,getType:()=>i,toString:()=>i};return(t,n)=>({...e,...t!==void 0&&{payload:t},...n!==void 0&&{meta:n}})}},WS="@iiif/IMPORT_ENTITIES",jS="@iiif/MODIFY_ENTITY_FIELD",KS="@iiif/REORDER_ENTITY_FIELD",qS="@iiif/MOVE_ENTITY",mf="@iiif/MOVE_ENTITIES",YS="@iiif/ADD_REFERENCE",vf="@iiif/UPDATE_REFERENCE",XS="@iiif/CHANGE_REFERENCE_IDENTIFIER",ZS="@iiif/REMOVE_REFERENCE",QS="@iiif/ADD_METADATA",JS="@iiif/REMOVE_METADATA",yf="@iiif/UPDATE_METADATA",ex="@iiif/REORDER_METADATA",tx=bt(WS)(),MD=bt(jS)(),FD=bt(KS)(),ND=bt(qS)(),BD=bt(mf)(),UD=bt(YS)(),$D=bt(ZS)(),HD=bt(vf)(),zD=bt(XS)(),VD=bt(QS)(),GD=bt(yf)(),WD=bt(JS)(),jD=bt(ex)(),KD={importEntities:tx,modifyEntityField:MD,reorderEntityField:FD,addReference:UD,removeReference:$D,updateReference:HD,changeReferenceIdentifier:zD,addMetadata:VD,removeMetadata:WD,updateMetadata:GD,reorderMetadata:jD,moveEntity:ND,moveEntities:BD},ix="@iiif/ADD_MAPPING",nx="@iiif/ADD_MAPPINGS",qD=bt(ix)(),YD=bt(nx)(),Sf="RESOURCE_ERROR",rx="RESOURCE_LOADING",xf="RESOURCE_READY",sx="@iiif/REQUEST_RESOURCE",ox="@iiif/REQUEST_ERROR",ax="@iiif/REQUEST_MISMATCH",lx="@iiif/REQUEST_COMPLETE",XD="@iiif/REQUEST_OFFLINE_RESOURCE",ZD=bt(sx)(),Tf=bt(ox)(),QD=bt(ax)(),JD=bt(lx)(),Ef="@iiif/BATCH",eO="@iiif/BATCH_IMPORT",wf=bt(Ef)(),cx="@iiif/SET_META_VALUE",ux="@iiif/SET_META_VALUE_DYNAMIC",dx="@iiif/UNSET_META_VALUE",tO=bt(cx)(),iO=bt(ux)(),nO=bt(dx)(),hx={setMetaValue:tO,setMetaValueDynamic:iO,unsetMetaValue:nO},rO=(i,e)=>{let{entities:t,resource:n,mapping:r}=xD(e);if(n.id===void 0)return[Tf({id:i,message:"ID is not defined in resource."})];let s=[tx({entities:t}),YD({mapping:r})];return n.id!==i&&(s.push(qD({id:i,type:n.type})),s.push(QD({requestId:i,actualId:n.id}))),s.push(JD({id:i})),s},fx=Number.isNaN||function(i){return typeof i=="number"&&i!==i};function sO(i,e){return!!(i===e||fx(i)&&fx(e))}function px(i,e){if(!Array.isArray(i)||!Array.isArray(e))return i===e;if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!sO(i[t],e[t]))return!1;return!0}function bf(i,e,t){let n=i.iiif.requests[e],r=i.iiif.mapping[e];if(!r||!i.iiif.entities[r][n.resourceUri])return;let s=i.iiif.entities[r][n.resourceUri];if(s&&s[Nt]){let o=s[Nt].find(a=>a[or]===s.id);return df(s,o)}return s}function oO(i){return i&&typeof i.then=="function"}function gx(i,e,{waitTimeout:t=30}={}){return(n,r,s)=>{let o=i.getStore(),a=o.getState(),l=a.iiif.requests[n];if(l){if(l.loadingState===xf){let u=bf(a,n);if(u)return u}switch(l.loadingState){case Sf:break;case rx:return(async()=>{let u,d=!1;try{let h=await Promise.race([new Promise((f,p)=>{d||(u=o.subscribe(()=>{let g=o.getState();if(g.iiif.requests[n].loadingState===Sf){p();return}if(g.iiif.requests[n].loadingState===xf){let m=bf(g,n);m?f(m):p()}}))}),new Promise((f,p)=>setTimeout(()=>{d=!0,p()},t*60*1e3))]);if(u&&u(),h)return h}catch{u&&u()}})()}}i.dispatch(ZD({id:n}));let c=u=>{if(!u)return;!u.id&&!u["@id"]&&(u["@type"]&&(u["@id"]=n),u.id=n);let d=rO(n,u);return i.dispatch(wf({actions:d})),bf(o.getState(),n)};try{let u=e(n,r);return oO(u)?(async()=>{try{let d=await u;return s&&(d=s(d)),c(d)}catch(d){throw i.dispatch(Tf({id:n,message:d.toString()})),d}})():c(s?s(u):u)}catch(u){throw i.dispatch(Tf({id:n,message:u.toString()})),u}}}function mx(){return{Collection:{},Manifest:{},Canvas:{},AnnotationPage:{},AnnotationCollection:{},Annotation:{},ContentResource:{},Range:{},Service:{},Selector:{},Agent:{}}}const _f={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},aO=(i,e)=>(t,n,r)=>(r.dispatch=s=>(t(o=>i(o,s),!1,s),s),r.dispatchFromDevtools=!0,{dispatch:(...s)=>r.dispatch(...s),...e}),lO=aO,Af=new Map,bc=i=>{let e=Af.get(i);return e?Object.fromEntries(Object.entries(e.stores).map(([t,n])=>[t,n.getState()])):{}},cO=(i,e,t)=>{if(i===void 0)return{type:"untracked",connection:e.connect(t)};let n=Af.get(t.name);if(n)return{type:"tracked",store:i,...n};let r={connection:e.connect(t),stores:{}};return Af.set(t.name,r),{type:"tracked",store:i,...r}},uO=(i,e={})=>(t,n,r)=>{let{enabled:s,anonymousActionType:o,store:a,...l}=e,c;try{c=(s??(_f?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!c)return(_f?"production":void 0)!=="production"&&s&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),i(t,n,r);let{connection:u,...d}=cO(a,c,l),h=!0;r.setState=(g,m,v)=>{let y=t(g,m);if(!h)return y;let S=v===void 0?{type:o||"anonymous"}:typeof v=="string"?{type:v}:v;return a===void 0?(u==null||u.send(S,n()),y):(u==null||u.send({...S,type:`${a}/${S.type}`},{...bc(l.name),[a]:r.getState()}),y)};let f=(...g)=>{let m=h;h=!1,t(...g),h=m},p=i(r.setState,n,r);if(d.type==="untracked"?u==null||u.init(p):(d.stores[d.store]=r,u==null||u.init(Object.fromEntries(Object.entries(d.stores).map(([g,m])=>[g,g===d.store?p:m.getState()])))),r.dispatchFromDevtools&&typeof r.dispatch=="function"){let g=!1,m=r.dispatch;r.dispatch=(...v)=>{(_f?"production":void 0)!=="production"&&v[0].type==="__setState"&&!g&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),g=!0),m(...v)}}return u.subscribe(g=>{var m;switch(g.type){case"ACTION":if(typeof g.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Rf(g.payload,v=>{if(v.type==="__setState"){if(a===void 0){f(v.state);return}Object.keys(v.state).length!==1&&console.error(`
|
|
18
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
19
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
20
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
21
|
+
`);let y=v.state[a];if(y==null)return;JSON.stringify(r.getState())!==JSON.stringify(y)&&f(y);return}r.dispatchFromDevtools&&typeof r.dispatch=="function"&&r.dispatch(v)});case"DISPATCH":switch(g.payload.type){case"RESET":return f(p),a===void 0?u==null?void 0:u.init(r.getState()):u==null?void 0:u.init(bc(l.name));case"COMMIT":if(a===void 0){u==null||u.init(r.getState());return}return u==null?void 0:u.init(bc(l.name));case"ROLLBACK":return Rf(g.state,v=>{if(a===void 0){f(v),u==null||u.init(r.getState());return}f(v[a]),u==null||u.init(bc(l.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Rf(g.state,v=>{if(a===void 0){f(v);return}JSON.stringify(r.getState())!==JSON.stringify(v[a])&&f(v[a])});case"IMPORT_STATE":{let{nextLiftedState:v}=g.payload,y=(m=v.computedStates.slice(-1)[0])==null?void 0:m.state;if(!y)return;f(a===void 0?y:y[a]),u==null||u.send(null,v);return}case"PAUSE_RECORDING":return h=!h}return}}),p},dO=uO,Rf=(i,e)=>{let t;try{t=JSON.parse(i)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}t!==void 0&&e(t)},hO=i=>(e,t,n)=>{let r=n.subscribe;return n.subscribe=(o,a,l)=>{let c=o;if(a){let u=(l==null?void 0:l.equalityFn)||Object.is,d=o(n.getState());c=h=>{let f=o(h);if(!u(d,f)){let p=d;a(d=f,p)}},l!=null&&l.fireImmediately&&a(d,d)}return r(c)},i(e,t,n)},fO=hO,pO=(i={},e)=>{switch(e.type){case ix:return{...i,[e.payload.id]:e.payload.type};case nx:return{...i,...e.payload.mapping};default:return i}};function Ba(i,e,t,n){return!(!i[t]||!i[t][e]||!i[t][e][n]||!Array.isArray(i[t][e][n]))}function gO(i,e){let t={},n=[];for(let[r,s]of Object.entries(i||{})){n.push(r);let o=(e||{})[r];if(!o||o.length===0){t[r]=s;continue}t[r]=o}for(let[r,s]of Object.entries(e||{}))n.indexOf(r)===-1&&(t[r]=s);return t}function Ae(i){return i.payload||{}}function mO(i,e,t){if(!i[e]||!Array.isArray(i[e]))return null;let n=t.index===void 0?i[e].findIndex(r=>{var s;return r?((s=Ec(r))==null?void 0:s.id)===t.id:!1}):t.index;return n===-1?null:{entity:i[e][n],index:n}}function vx(i,e){var t;if(!(!(e!=null&&e.id)||!(e!=null&&e.type)))return(t=i[e.type])==null?void 0:t[e.id]}function _c(i,e){return i===void 0?e:i}const yx=(i=mx(),e)=>{var n,r;let t=(s,o)=>({...i,[Ae(e).type]:{...i[Ae(e).type],[Ae(e).id]:{...s,...o}}});switch(e.type){case jS:{if(!i[Ae(e).type]||!i[Ae(e).type][Ae(e).id])return i;let s=i[Ae(e).type][Ae(e).id];return typeof s=="string"?i:t(s,{[Ae(e).key]:Ae(e).value})}case KS:{if(!Ba(i,Ae(e).id,Ae(e).type,Ae(e).key))return i;let s=i[Ae(e).type][Ae(e).id];if(typeof s=="string")return i;let o=Array.from(s[Ae(e).key]),[a]=o.splice(Ae(e).startIndex,1);return o.splice(Ae(e).endIndex,0,a),t(s,{[Ae(e).key]:o})}case mf:{let s=Ae(e).subjects,o=Ae(e).from,a=Ae(e).to||o,l=vx(i,o),c=(a==null?void 0:a.key)||o.key;if(!Ba(i,o.id,o.type,o.key)||!Ba(i,a.id,a.type,a.key))return i;let u=[],d=[];if(s.type==="slice"){let S=s.startIndex,x=s.length;u=Array.from(l[o.key]),d=u.splice(S,x)}else{let S=Array.from(l[o.key]);for(let x of s.items){let E=mO(l,o.key,x);E&&(d.push(E.entity),S[E.index]=null),u=S.filter(C=>C!==null)}}let h={...l,[o.key]:u},f={...i,[o.type]:{...i[o.type],[o.id]:h}},p=vx(f,a);if(!p)return i;let g=(a==null?void 0:a.index)===void 0?p[c].length:a.index,m=Array.from(p[a.key]);m.splice(g,0,...d);let v={...p,[c]:m};return{...f,[a.type]:{...f[a.type],[a.id]:v}}}case qS:return yx(i,{type:mf,payload:{subjects:{type:"list",items:[Ae(e).subject]},from:Ae(e).from,to:Ae(e).to}});case XS:{let{id:s,index:o,key:a,newIdentifier:l,reference:c,type:u}=Ae(e),d=i[u][s],h=Ec(c);if(!d||!d[a]||!h||o<0)return i;let f=d[a],p=f[o],g=(n=i[h.type])==null?void 0:n[h.id];if(!g||!p)return i;let m=DD(p,l),v=Array.from(f);v.splice(_c(o,v.length+1),1,m);let y=t(d,{[a]:v}),S={...g,id:l};S["iiif-parser:hasPart"]&&(S["iiif-parser:hasPart"]=S["iiif-parser:hasPart"].filter(E=>E["iiif-parser:partOf"]===s).map(E=>({...E,id:l})));let x={...y[h.type],[l]:S};return y[h.type]=x,y}case WS:{let s=Object.keys(Ae(e).entities),o={...i};for(let a of s){let l=Ae(e).entities[a],c={...i[a]||{}},u=!1,d=Object.keys(l||{})||[];if(l&&d){for(let h of d)u=!0,c[h]=i[a][h]?gO(i[a][h],l[h]):l[h];u&&(o[a]=c)}}return o}case YS:{if(!Ba(i,Ae(e).id,Ae(e).type,Ae(e).key))return i;let s=i[Ae(e).type][Ae(e).id],o=Array.from(s[Ae(e).key]);return o.splice(_c(Ae(e).index,o.length+1),0,Ae(e).reference),t(s,{[Ae(e).key]:o})}case vf:case ZS:{if(!Ba(i,Ae(e).id,Ae(e).type,Ae(e).key))return i;let s=i[Ae(e).type][Ae(e).id],o=Array.from(s[Ae(e).key]),a=_c(Ae(e).index,o.findIndex(l=>l&&l.id===Ae(e).reference.id));return a===-1||((r=o[a])==null?void 0:r.id)!==Ae(e).reference.id?i:(e.type===vf?o.splice(a,1,Ae(e).reference):o.splice(a,1),t(s,{[Ae(e).key]:o}))}case QS:{let s=i[Ae(e).type][Ae(e).id];if(!s)return i;let o=Array.from(s.metadata||[]),a=Ae(e);return o.splice(_c(e.payload.beforeIndex,o.length+1),0,{label:a.label,value:a.label}),t(s,{metadata:o})}case ex:{let s=i[Ae(e).type][Ae(e).id];if(typeof s=="string"||!s)return i;let o=Array.from(s.metadata||[]),[a]=o.splice(Ae(e).startIndex,1);return o.splice(Ae(e).endIndex,0,a),t(s,{metadata:o})}case yf:case JS:{let s=i[Ae(e).type][Ae(e).id],o=Array.from(s.metadata||[]),a=Ae(e).atIndex;return a===void 0||a===-1||!o[a]?i:(e.type===yf?o.splice(a,1,{label:Ae(e).label,value:Ae(e).value}):o.splice(a,1),t(s,{metadata:o}))}default:return i}},vO=(i={},e)=>{switch(e.type){case sx:case XD:return{...i,[e.payload.id]:{requestUri:e.payload.id,loadingState:rx,uriMismatch:!1,resourceUri:e.payload.id}};case ax:return{...i,[e.payload.requestId]:{...i[e.payload.requestId]||{},uriMismatch:!0,resourceUri:e.payload.actualId},[e.payload.actualId]:{requestUri:e.payload.requestId,loadingState:i[e.payload.requestId].loadingState,uriMismatch:!0,resourceUri:e.payload.actualId}};case ox:return{...i,[e.payload.id]:{...i[e.payload.id]||{},loadingState:Sf,error:e.payload.message}};case lx:return{...i,[e.payload.id]:{...i[e.payload.id]||{},loadingState:xf,error:void 0}}}return i},yO=(i={},e)=>{let{id:t,updateValue:n,value:r,meta:s,key:o}=e&&e.payload||{};switch(e.type){case cx:return{...i,[t]:{...i[t]||{},[s]:{...i[t]&&i[t][s]||{},[o]:r}}};case ux:return{...i,[t]:{...i[t]||{},[s]:{...i[t]&&i[t][s]||{},[o]:i[t]&&i[t][s]?n(i[t][s][o]):n(void 0)}}};case dx:return i[t]&&i[t][s]&&i[t][s][o]?{...i,[t]:{...i[t]||{},[s]:{...i[t]&&i[t][s]||{},[o]:void 0}}}:i;default:return i}};function Sx(i={}){let e=Object.keys(i);return function(t={},n){let r=!1,s={};for(let o=0;o<e.length;o++){let a=e[o];s[a]=i[a](t[a],n),r||(r=s[a]!==t[a])}return r?s:t}}function SO(i){return(e,t)=>t&&t.type===Ef?t.payload.actions.reduce(i,e):t&&t.type===eO?{...e,iiif:{...e.iiif,...t.payload.state}}:i(e,t)}const xO=Sx({mapping:pO,entities:yx,requests:vO,meta:yO});function TO(){return{iiif:{entities:mx(),meta:{},mapping:{},requests:{}}}}function EO(i={}){let{enableDevtools:e=!1,iiifStoreName:t="iiif",defaultState:n=TO(),customReducers:r={}}=i,s=SO(Sx({[t]:xO,...r})),o=!!(typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__);return _S(fO((o?dO:(l,c)=>l)(lO(s,n),{enabled:e})))}function ai(i,e,t,n=!0){e[vo]=e[vo]||[],e[vo].push(i);let r=new Map;Object.defineProperty(e,i,{enumerable:n,get(){if(e[Cs][i]===void 0)return;let s=e[Cs][i];if(!s)return s;let o=t.get(e[Cs][i],{parent:this.id?{id:this.id,type:this.type}:void 0});return r.has(o)||(r.clear(),r.set(o,Ps(o,t))),r.get(o)},set(s){e[Cs][i]!==s&&(this[Is]?t.modifyEntityField({id:this.id,type:this.type},i,Tx(s)):this[Cs][i]=s)}})}const Cs=Symbol.for("_refs_"),Is=Symbol.for("_reactive_"),vo=Symbol.for("_defined_"),xx=Symbol.for("_parent_");function wO(i,e=!1,t){let n={id:"",type:"unknown",[vo]:[],[Cs]:{},[xx]:null,[Is]:null,is(r){return typeof r=="string"?this.id===r:r.id?r.id===this.id:!1},reactive(){if(!this[Is])return this[Is]=this.subscribe(()=>this.refresh(),!0),()=>{this.unreactive()}},refresh(){if(this.id){let r=this.unwrap();for(let s of Object.keys(r||{}))this[vo].includes(s)?this[Cs][s]=r[s]:this[s]=r[s]}},unreactive(){this[Is]&&(this[Is](),this[Is]=null)},unwrap(){if(!this.id)throw Error("Invalid object");let r=this[xx];return i.get(this.id,{parent:r?{id:r,type:"unknown"}:void 0})},toPresentation3(){return i.toPresentation3(this.unwrap())},toPresentation2(){return i.toPresentation2(this.unwrap())},valueOf(){return this.unwrap()},toJSON(){let r=this;return{...r,items:r.items,annotations:r.annotations,structures:r.structures,seeAlso:r.seeAlso,service:r.service,services:r.services,rendering:r.rendering,partOf:r.partOf,start:r.start,supplementary:r.supplementary,homepage:r.homepage,thumbnail:r.thumbnail,placeholderCanvas:r.placeholderCanvas,accompanyingCanvas:r.accompanyingCanvas,provider:r.provider}},subscribe(r,s=!0){return i.subscribe(()=>this.id?i.get(this.id):null,r,s)}};return ai("items",n,i),ai("annotations",n,i),ai("structures",n,i),ai("seeAlso",n,i),ai("rendering",n,i),ai("partOf",n,i),ai("start",n,i,!1),ai("supplementary",n,i),ai("homepage",n,i),ai("thumbnail",n,i),ai("placeholderCanvas",n,i,!1),ai("accompanyingCanvas",n,i,!1),ai("provider",n,i),ai("body",n,i),ai("logo",n,i),n}function bO(i){return!!i[vo]}function Tx(i){return Array.isArray(i)?i.map(e=>Tx(e)):!i||!i.type?i:{id:i.id,type:i.type}}function Ps(i,e,t=!1,n){if(Array.isArray(i))return i.map(a=>Ps(a,e,t));if(!i||!i.type||!i.id)return i;let r=wO(e,t),s=Object.create(r),o=Object.assign(s,i);return t&&o.reactive(),o}function Ex(i){switch(i){case"Image":case"Video":case"Sound":case"Dataset":case"Text":case"Composite":case"List":case"Independents":case"Audience":return"ContentResource";case"ImageService1":case"ImageService2":case"ImageService3":return"Service"}return i}var wx=class{constructor(e,t){qi(this,"options",void 0),qi(this,"store",void 0),qi(this,"emitter",void 0),qi(this,"isBatching",!1),qi(this,"batchQueue",[]),qi(this,"remoteFetcher",void 0),qi(this,"staticFetcher",void 0),qi(this,"defaultFetcher",n=>fetch(n).then(r=>{if(r.status===200)return r.json();{let s=Error(`${r.status} ${r.statusText}`);throw s.name="HTTPError",s}})),this.options=Object.assign({reducers:{},customFetcher:this.defaultFetcher,enableDevtools:!0},e||{}),this.store=t||EO({customReducers:this.options.reducers,defaultState:this.options.defaultState,enableDevtools:this.options.enableDevtools}),this.emitter=AS(),this.remoteFetcher=gx(this,this.options.customFetcher),this.staticFetcher=gx(this,(n,r)=>r)}batch(e){this.isBatching=!0;try{e(this),this.isBatching=!1,this.dispatch(wf({actions:this.batchQueue}))}catch(t){throw this.batchQueue=[],this.isBatching=!1,t}this.batchQueue=[]}async asyncBatch(e){this.isBatching=!0;try{await e(this),this.isBatching=!1,this.dispatch(wf({actions:this.batchQueue}))}catch(t){throw this.batchQueue=[],this.isBatching=!1,t}this.batchQueue=[]}modifyEntityField(e,t,n){this.dispatch(KD.modifyEntityField({id:e.id,type:e.type,key:t,value:n}))}dispatch(e){if(this.isBatching)this.batchQueue.push(e);else{if(e.type===Ef){for(let r of e.payload.actions)this.emitter.emit(r.type,{action:r,state:this.store.getState()});this.store.dispatch(e);let n=this.getState();for(let r of e.payload.actions)this.emitter.emit(`after:${r.type}`,{action:r,state:n});return}this.emitter.emit(e.type,{action:e,state:this.store.getState()}),this.store.dispatch(e);let t=this.store.getState();this.emitter.emit(`after:${e.type}`,{action:e,state:t});return}}on(e,t){return this.emitter.on(e,t),()=>{this.emitter.off(e,t)}}serialize(e,t){return ED(this.getState().iiif,e,t)}toPresentation2(e){return this.serialize(e,RD)}toPresentation3(e){return this.serialize(e,CD)}hydrate(e,t,n={}){return this.get(e,t,{...n,skipSelfReturn:!1})}get(e,t,n={}){typeof t!="string"&&(n=t||{},t=void 0);let{skipSelfReturn:r=!0}=n||{},s=n.parent?typeof n.parent=="string"?n.parent:n.parent.id:void 0;if(Array.isArray(e))return e.map(d=>this.get(d,n));let o=this.getState();if(sr(e)&&!n.preserveSpecificResources&&(e=e.source),typeof e=="string"){let d=Ex(t||o.iiif.mapping[e]);if(!d)return r?null:{id:e,type:"unknown"};e={id:e,type:d}}if(e&&e.partOf&&!s&&!n.skipPartOfCheck){let d=Array.isArray(e.partOf)?e.partOf[0]:e.partOf;d&&(typeof d=="string"&&(s=d),typeof d.id=="string"&&(s=d.id))}let a=Ex(t||(e==null?void 0:e.type)),l=e==null?void 0:e.id,c=o.iiif.entities[a];if(!c){let d=o.iiif.requests[l];return d&&d.resourceUri!==l?this.get(d.resourceUri,n):r?null:e}let u=c[e.id];if(u&&u[Nt]){let d=u[Nt].find(h=>s?h[or]===s:h[or]===u.id);return df(u,d)}return c[e.id]||(r?null:e)}select(e){return e(this.getState())}getStore(){return this.store}getState(){return this.store.getState()}deep(e,t){if(e===void 0)return this.get(t,{skipSelfReturn:!1});if(typeof e=="function")try{let r=e(this.get(t,{skipSelfReturn:!1})),s=o=>this.deep(o,r);return s.size=Array.isArray(r)?r.length:1,s}catch{let r=s=>this.deep(s,void 0);return r.size=0,r}let n=r=>this.deep(r,e);return n.size=Array.isArray(e)?e.length:1,n}loadManifest(e,t,n){let r=typeof e=="string"?e:e.id;return this.load(r,t,n)}loadCollection(e,t,n){let r=typeof e=="string"?e:e.id;return this.load(r,t,n)}load(e,t,n){let r=typeof e=="string"?e:e.id;return t?Promise.resolve(this.staticFetcher(r,t,n)):Promise.resolve(this.remoteFetcher(r,{},n))}loadSync(e,t,n){let r=typeof e=="string"?e:e.id;return this.staticFetcher(r,t,n)}loadManifestSync(e,t,n){let r=typeof e=="string"?e:e.id;return this.loadSync(r,t,n)}loadCollectionSync(e,t,n){let r=typeof e=="string"?e:e.id;return this.loadSync(r,t,n)}areInputsEqual(e,t){return px(e,t)}subscribe(e,t,n){return n===void 0&&(t===void 0||t===!1||t===!0)&&(n=t,t=e,e=r=>r),this.store.subscribe(e,r=>t(r,this),{equalityFn:px,fireImmediately:!n})}async ensureLoaded(e){let t=typeof e=="string"?e:e.id;this.requestStatus(t)||await this.load(t)}requestStatus(e){return this.select(t=>t.iiif.requests[e])}getPaginationState(e){let t=typeof e=="string"?e:e.id;if(!t)return null;let n=this.getResourceMeta(t,"@vault/pagination");if(n!=null&&n.state)return n.state;let r=this.get(e);if(r.first){let s={currentPage:null,currentPageIndex:null,isFetching:!1,isFullyLoaded:!1,next:r.first,page:1,pages:[],previous:null,totalItems:r.total,currentLength:0};return this.setMetaValue([t,"@vault/pagination","state"],s),s}return null}async loadNextPage(e,t){var f;let n=typeof e=="string"?e:e.id;if(!n)return[null,null];let r=this.getPaginationState(e);if(!r||r.isFullyLoaded||!r.next)return[null,null];if(r.isFetching)return[r,null];let s=typeof r.next=="string"?r.next:r.next.id,o=r.currentPage,a={...r,isFetching:!0};this.setMetaValue([n,"@vault/pagination","state"],a);let l;try{l=await this.loadCollection(s,t,p=>{let{id:g,"@id":m,...v}=p||{};return m?{"@id":s,...v}:{id:s,...v}})}catch(p){let g={...r,isFetching:!1,error:p};return this.setMetaValue([n,"@vault/pagination","state"],g),[g,null]}if(!l){let p={...r,isFetching:!1,error:Error("Collection not found")};return this.setMetaValue([n,"@vault/pagination","state"],p),[p,null]}let c=this.get(n),u=[...c.items||[],...l.items||[]].map(p=>({id:p.id,type:p.type}));this.modifyEntityField({id:n,type:"Collection"},"items",u);let d=this.getPaginationState(e);if(!d)throw Error("Pagination state not found");let h={...d,isFetching:!1,error:null,currentPage:l.id,next:((f=l.next)==null?void 0:f.id)||null,currentPageIndex:d.pages.length,currentLength:u.length,pages:[...d.pages,{id:l.id,type:"Collection",startIndex:c.items.length,pageLength:l.items.length,order:typeof d.currentPageIndex=="number"?d.currentPageIndex+1:0}],isFullyLoaded:!l.next,previous:o,page:d.pages.length+1};return this.setMetaValue([n,"@vault/pagination","state"],h),[h,l]}getResourceMeta(e,t){let n=this.getState().iiif.meta[e];if(n)return t?n[t]:n}getObject(e,t,n={}){let{reactive:r,...s}=n;return Ps(this.get(e,t,s),this,r)}async loadObject(e,t){return Ps(await this.load(e,t),this)}async loadManifestObject(e,t){return Ps(await this.loadManifest(e,t),this)}async loadCollectionObject(e,t){return Ps(await this.loadCollection(e,t),this)}wrapObject(e){return Ps(this.get(e,{skipSelfReturn:!1}),this)}isWrapped(e){return bO(e)}setMetaValue([e,t,n],r){this.dispatch(typeof r=="function"?hx.setMetaValueDynamic({id:e,meta:t,key:n,updateValue:r}):hx.setMetaValue({id:e,meta:t,key:n,value:r}))}};const _O=i=>(Array.isArray(i["@context"])?i["@context"]:[i["@context"]]).map(t=>t==null?void 0:t.replace("http://","https://")),AO=i=>fetch(`${i.replace(/\/$/,"")}/info.json`).then(e=>e.json()).then(e=>e).catch(e=>{console.error(`The IIIF tilesource ${i.replace(/\/$/,"")}/info.json failed to load: ${e}`)}),RO=i=>{let e,t;if(Array.isArray(i)&&(e=i[0],e)){let n;"@id"in e?n=e["@id"]:n=e.id,t=n}return t},bx=i=>{var n,r,s,o,a,l,c,u,d,h,f,p,g,m,v;let e,t={};switch(i==null?void 0:i.type){case"SpecificResource":e=(s=(r=(n=i==null?void 0:i.target)==null?void 0:n.partOf)==null?void 0:r[0])==null?void 0:s.id,t={manifest:e,canvas:(o=i==null?void 0:i.target)==null?void 0:o.id},i!=null&&i.selector&&(t.selector=i.selector);break;case"Range":case"Annotation":const y=((a=i==null?void 0:i.target)==null?void 0:a.source)||(i==null?void 0:i.target),S=(l=i==null?void 0:i.target)==null?void 0:l.selector;t={manifest:(u=(c=y==null?void 0:y.partOf)==null?void 0:c[0])==null?void 0:u.id,canvas:y==null?void 0:y.id},(((d=i==null?void 0:i.target)==null?void 0:d.type)==="SpecificResource"||(h=i==null?void 0:i.target)!=null&&h.selector)&&(t.selector=S);break;case"Canvas":if(e=(p=(f=i==null?void 0:i.partOf)==null?void 0:f[0])==null?void 0:p.id,t={manifest:e,canvas:i==null?void 0:i.id},(g=i==null?void 0:i.id)!=null&&g.includes("#xywh=")){const[x,E]=i.id.split("#xywh=");t.canvas=x,t.selector={type:"FragmentSelector",value:`xywh=${E}`}}break;case"Manifest":e=i==null?void 0:i.id,t={collection:(v=(m=i==null?void 0:i.partOf)==null?void 0:m[0])==null?void 0:v.id,manifest:i==null?void 0:i.id};break;case"Collection":e=i==null?void 0:i.id,t={collection:e};break}return{resourceId:e,active:t}},CO=i=>{const e=["https://iiif.io/api/presentation/2/context.json","https://iiif.io/api/presentation/3/context.json"],t=new TypeError(`The IIIF content may not be a valid IIIF resource: ${e.join(", ")}`);i["@context"]||console.warn(t);const n=_O(i);try{if(n.includes(e[0])){const r=wS(i);if(!r||!r.id||!r.type)throw t;return r}else{if(n.includes(e[1]))return i;throw t}}catch(r){console.warn(r)}},IO=i=>{if(typeof i=="string"&&DO(i))return{resourceId:i};if(typeof i=="object"){const e=CO(i);return{resourceId:e==null?void 0:e.id,resourceObject:e}}else{const e=JSON.parse(LD(i)),{active:t}=bx(e);return{active:t,resourceId:e==null?void 0:e.resourceId,resourceObject:e}}},PO=i=>{const{resourceId:e,resourceObject:t}=IO(i);return t||e},LO=i=>i.items.map(t=>t.id)[0],kO=i=>{const e=i.items.filter(t=>t.type==="Manifest").map(t=>t.id);return e.length==0?null:e[0]},DO=i=>{try{new URL(i)}catch{return!1}return!0};var Yi=(i=>(i.TiledImage="tiledImage",i.SimpleImage="simpleImage",i))(Yi||{});const OO=i=>{const e=Array.isArray(i==null?void 0:i.service)&&(i==null?void 0:i.service.length)>0,t=e?RO(i==null?void 0:i.service):i==null?void 0:i.id,n=e?Yi.TiledImage:Yi.SimpleImage;return{uri:t,imageType:n}},MO=(i,e)=>{const t=e?Yi.TiledImage:Yi.SimpleImage;return{uri:i,imageType:t}},FO=ln(null),Cf={didCatch:!1,error:null};class If extends ji{constructor(e){super(e),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=Cf}static getDerivedStateFromError(e){return{didCatch:!0,error:e}}resetErrorBoundary(){const{error:e}=this.state;if(e!==null){for(var t,n,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];(t=(n=this.props).onReset)===null||t===void 0||t.call(n,{args:s,reason:"imperative-api"}),this.setState(Cf)}}componentDidCatch(e,t){var n,r;(n=(r=this.props).onError)===null||n===void 0||n.call(r,e,t)}componentDidUpdate(e,t){const{didCatch:n}=this.state,{resetKeys:r}=this.props;if(n&&t.error!==null&&NO(e.resetKeys,r)){var s,o;(s=(o=this.props).onReset)===null||s===void 0||s.call(o,{next:r,prev:e.resetKeys,reason:"keys"}),this.setState(Cf)}}render(){const{children:e,fallbackRender:t,FallbackComponent:n,fallback:r}=this.props,{didCatch:s,error:o}=this.state;let a=e;if(s){const l={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof t=="function")a=t(l);else if(n)a=Ve(n,l);else if(r!==void 0)a=r;else throw o}return Ve(FO.Provider,{value:{didCatch:s,error:o,resetErrorBoundary:this.resetErrorBoundary}},a)}}function NO(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return i.length!==e.length||i.some((t,n)=>!Object.is(t,e[n]))}var ot="colors",li="sizes",Te="space",BO={gap:Te,gridGap:Te,columnGap:Te,gridColumnGap:Te,rowGap:Te,gridRowGap:Te,inset:Te,insetBlock:Te,insetBlockEnd:Te,insetBlockStart:Te,insetInline:Te,insetInlineEnd:Te,insetInlineStart:Te,margin:Te,marginTop:Te,marginRight:Te,marginBottom:Te,marginLeft:Te,marginBlock:Te,marginBlockEnd:Te,marginBlockStart:Te,marginInline:Te,marginInlineEnd:Te,marginInlineStart:Te,padding:Te,paddingTop:Te,paddingRight:Te,paddingBottom:Te,paddingLeft:Te,paddingBlock:Te,paddingBlockEnd:Te,paddingBlockStart:Te,paddingInline:Te,paddingInlineEnd:Te,paddingInlineStart:Te,top:Te,right:Te,bottom:Te,left:Te,scrollMargin:Te,scrollMarginTop:Te,scrollMarginRight:Te,scrollMarginBottom:Te,scrollMarginLeft:Te,scrollMarginX:Te,scrollMarginY:Te,scrollMarginBlock:Te,scrollMarginBlockEnd:Te,scrollMarginBlockStart:Te,scrollMarginInline:Te,scrollMarginInlineEnd:Te,scrollMarginInlineStart:Te,scrollPadding:Te,scrollPaddingTop:Te,scrollPaddingRight:Te,scrollPaddingBottom:Te,scrollPaddingLeft:Te,scrollPaddingX:Te,scrollPaddingY:Te,scrollPaddingBlock:Te,scrollPaddingBlockEnd:Te,scrollPaddingBlockStart:Te,scrollPaddingInline:Te,scrollPaddingInlineEnd:Te,scrollPaddingInlineStart:Te,fontSize:"fontSizes",background:ot,backgroundColor:ot,backgroundImage:ot,borderImage:ot,border:ot,borderBlock:ot,borderBlockEnd:ot,borderBlockStart:ot,borderBottom:ot,borderBottomColor:ot,borderColor:ot,borderInline:ot,borderInlineEnd:ot,borderInlineStart:ot,borderLeft:ot,borderLeftColor:ot,borderRight:ot,borderRightColor:ot,borderTop:ot,borderTopColor:ot,caretColor:ot,color:ot,columnRuleColor:ot,fill:ot,outline:ot,outlineColor:ot,stroke:ot,textDecorationColor:ot,fontFamily:"fonts",fontWeight:"fontWeights",lineHeight:"lineHeights",letterSpacing:"letterSpacings",blockSize:li,minBlockSize:li,maxBlockSize:li,inlineSize:li,minInlineSize:li,maxInlineSize:li,width:li,minWidth:li,maxWidth:li,height:li,minHeight:li,maxHeight:li,flexBasis:li,gridTemplateColumns:li,gridTemplateRows:li,borderWidth:"borderWidths",borderTopWidth:"borderWidths",borderRightWidth:"borderWidths",borderBottomWidth:"borderWidths",borderLeftWidth:"borderWidths",borderStyle:"borderStyles",borderTopStyle:"borderStyles",borderRightStyle:"borderStyles",borderBottomStyle:"borderStyles",borderLeftStyle:"borderStyles",borderRadius:"radii",borderTopLeftRadius:"radii",borderTopRightRadius:"radii",borderBottomRightRadius:"radii",borderBottomLeftRadius:"radii",boxShadow:"shadows",textShadow:"shadows",transition:"transitions",zIndex:"zIndices"},UO=(i,e)=>typeof e=="function"?{"()":Function.prototype.toString.call(e)}:e,yo=()=>{const i=Object.create(null);return(e,t,...n)=>{const r=(s=>JSON.stringify(s,UO))(e);return r in i?i[r]:i[r]=t(e,...n)}},Ls=Symbol.for("sxs.internal"),Pf=(i,e)=>Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)),_x=i=>{for(const e in i)return!0;return!1},{hasOwnProperty:$O}=Object.prototype,Lf=i=>i.includes("-")?i:i.replace(/[A-Z]/g,e=>"-"+e.toLowerCase()),HO=/\s+(?![^()]*\))/,So=i=>e=>i(...typeof e=="string"?String(e).split(HO):[e]),Ax={appearance:i=>({WebkitAppearance:i,appearance:i}),backfaceVisibility:i=>({WebkitBackfaceVisibility:i,backfaceVisibility:i}),backdropFilter:i=>({WebkitBackdropFilter:i,backdropFilter:i}),backgroundClip:i=>({WebkitBackgroundClip:i,backgroundClip:i}),boxDecorationBreak:i=>({WebkitBoxDecorationBreak:i,boxDecorationBreak:i}),clipPath:i=>({WebkitClipPath:i,clipPath:i}),content:i=>({content:i.includes('"')||i.includes("'")||/^([A-Za-z]+\([^]*|[^]*-quote|inherit|initial|none|normal|revert|unset)$/.test(i)?i:`"${i}"`}),hyphens:i=>({WebkitHyphens:i,hyphens:i}),maskImage:i=>({WebkitMaskImage:i,maskImage:i}),maskSize:i=>({WebkitMaskSize:i,maskSize:i}),tabSize:i=>({MozTabSize:i,tabSize:i}),textSizeAdjust:i=>({WebkitTextSizeAdjust:i,textSizeAdjust:i}),userSelect:i=>({WebkitUserSelect:i,userSelect:i}),marginBlock:So((i,e)=>({marginBlockStart:i,marginBlockEnd:e||i})),marginInline:So((i,e)=>({marginInlineStart:i,marginInlineEnd:e||i})),maxSize:So((i,e)=>({maxBlockSize:i,maxInlineSize:e||i})),minSize:So((i,e)=>({minBlockSize:i,minInlineSize:e||i})),paddingBlock:So((i,e)=>({paddingBlockStart:i,paddingBlockEnd:e||i})),paddingInline:So((i,e)=>({paddingInlineStart:i,paddingInlineEnd:e||i}))},kf=/([\d.]+)([^]*)/,zO=(i,e)=>i.length?i.reduce((t,n)=>(t.push(...e.map(r=>r.includes("&")?r.replace(/&/g,/[ +>|~]/.test(n)&&/&.*&/.test(r)?`:is(${n})`:n):n+" "+r)),t),[]):e,VO=(i,e)=>i in GO&&typeof e=="string"?e.replace(/^((?:[^]*[^\w-])?)(fit-content|stretch)((?:[^\w-][^]*)?)$/,(t,n,r,s)=>n+(r==="stretch"?`-moz-available${s};${Lf(i)}:${n}-webkit-fill-available`:`-moz-fit-content${s};${Lf(i)}:${n}fit-content`)+s):String(e),GO={blockSize:1,height:1,inlineSize:1,maxBlockSize:1,maxHeight:1,maxInlineSize:1,maxWidth:1,minBlockSize:1,minHeight:1,minInlineSize:1,minWidth:1,width:1},ar=i=>i?i+"-":"",Rx=(i,e,t)=>i.replace(/([+-])?((?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?)?(\$|--)([$\w-]+)/g,(n,r,s,o,a)=>o=="$"==!!s?n:(r||o=="--"?"calc(":"")+"var(--"+(o==="$"?ar(e)+(a.includes("$")?"":ar(t))+a.replace(/\$/g,"-"):a)+")"+(r||o=="--"?"*"+(r||"")+(s||"1")+")":"")),WO=/\s*,\s*(?![^()]*\))/,jO=Object.prototype.toString,xo=(i,e,t,n,r)=>{let s,o,a;const l=(c,u,d)=>{let h,f;const p=g=>{for(h in g){const y=h.charCodeAt(0)===64,S=y&&Array.isArray(g[h])?g[h]:[g[h]];for(f of S){const x=/[A-Z]/.test(v=h)?v:v.replace(/-[^]/g,C=>C[1].toUpperCase()),E=typeof f=="object"&&f&&f.toString===jO&&(!n.utils[x]||!u.length);if(x in n.utils&&!E){const C=n.utils[x];if(C!==o){o=C,p(C(f)),o=null;continue}}else if(x in Ax){const C=Ax[x];if(C!==a){a=C,p(C(f)),a=null;continue}}if(y&&(m=h.slice(1)in n.media?"@media "+n.media[h.slice(1)]:h,h=m.replace(/\(\s*([\w-]+)\s*(=|<|<=|>|>=)\s*([\w-]+)\s*(?:(<|<=|>|>=)\s*([\w-]+)\s*)?\)/g,(C,b,I,D,P,k)=>{const N=kf.test(b),B=.0625*(N?-1:1),[K,q]=N?[D,b]:[b,D];return"("+(I[0]==="="?"":I[0]===">"===N?"max-":"min-")+K+":"+(I[0]!=="="&&I.length===1?q.replace(kf,(H,X,F)=>Number(X)+B*(I===">"?1:-1)+F):q)+(P?") and ("+(P[0]===">"?"min-":"max-")+K+":"+(P.length===1?k.replace(kf,(H,X,F)=>Number(X)+B*(P===">"?-1:1)+F):k):"")+")"})),E){const C=y?d.concat(h):[...d],b=y?[...u]:zO(u,h.split(WO));s!==void 0&&r(Cx(...s)),s=void 0,l(f,b,C)}else s===void 0&&(s=[[],u,d]),h=y||h.charCodeAt(0)!==36?h:`--${ar(n.prefix)}${h.slice(1).replace(/\$/g,"-")}`,f=E?f:typeof f=="number"?f&&x in KO?String(f)+"px":String(f):Rx(VO(x,f??""),n.prefix,n.themeMap[x]),s[0].push(`${y?`${h} `:`${Lf(h)}:`}${f}`)}}var m,v};p(c),s!==void 0&&r(Cx(...s)),s=void 0};l(i,e,t)},Cx=(i,e,t)=>`${t.map(n=>`${n}{`).join("")}${e.length?`${e.join(",")}{`:""}${i.join(";")}${e.length?"}":""}${Array(t.length?t.length+1:0).join("}")}`,KO={animationDelay:1,animationDuration:1,backgroundSize:1,blockSize:1,border:1,borderBlock:1,borderBlockEnd:1,borderBlockEndWidth:1,borderBlockStart:1,borderBlockStartWidth:1,borderBlockWidth:1,borderBottom:1,borderBottomLeftRadius:1,borderBottomRightRadius:1,borderBottomWidth:1,borderEndEndRadius:1,borderEndStartRadius:1,borderInlineEnd:1,borderInlineEndWidth:1,borderInlineStart:1,borderInlineStartWidth:1,borderInlineWidth:1,borderLeft:1,borderLeftWidth:1,borderRadius:1,borderRight:1,borderRightWidth:1,borderSpacing:1,borderStartEndRadius:1,borderStartStartRadius:1,borderTop:1,borderTopLeftRadius:1,borderTopRightRadius:1,borderTopWidth:1,borderWidth:1,bottom:1,columnGap:1,columnRule:1,columnRuleWidth:1,columnWidth:1,containIntrinsicSize:1,flexBasis:1,fontSize:1,gap:1,gridAutoColumns:1,gridAutoRows:1,gridTemplateColumns:1,gridTemplateRows:1,height:1,inlineSize:1,inset:1,insetBlock:1,insetBlockEnd:1,insetBlockStart:1,insetInline:1,insetInlineEnd:1,insetInlineStart:1,left:1,letterSpacing:1,margin:1,marginBlock:1,marginBlockEnd:1,marginBlockStart:1,marginBottom:1,marginInline:1,marginInlineEnd:1,marginInlineStart:1,marginLeft:1,marginRight:1,marginTop:1,maxBlockSize:1,maxHeight:1,maxInlineSize:1,maxWidth:1,minBlockSize:1,minHeight:1,minInlineSize:1,minWidth:1,offsetDistance:1,offsetRotate:1,outline:1,outlineOffset:1,outlineWidth:1,overflowClipMargin:1,padding:1,paddingBlock:1,paddingBlockEnd:1,paddingBlockStart:1,paddingBottom:1,paddingInline:1,paddingInlineEnd:1,paddingInlineStart:1,paddingLeft:1,paddingRight:1,paddingTop:1,perspective:1,right:1,rowGap:1,scrollMargin:1,scrollMarginBlock:1,scrollMarginBlockEnd:1,scrollMarginBlockStart:1,scrollMarginBottom:1,scrollMarginInline:1,scrollMarginInlineEnd:1,scrollMarginInlineStart:1,scrollMarginLeft:1,scrollMarginRight:1,scrollMarginTop:1,scrollPadding:1,scrollPaddingBlock:1,scrollPaddingBlockEnd:1,scrollPaddingBlockStart:1,scrollPaddingBottom:1,scrollPaddingInline:1,scrollPaddingInlineEnd:1,scrollPaddingInlineStart:1,scrollPaddingLeft:1,scrollPaddingRight:1,scrollPaddingTop:1,shapeMargin:1,textDecoration:1,textDecorationThickness:1,textIndent:1,textUnderlineOffset:1,top:1,transitionDelay:1,transitionDuration:1,verticalAlign:1,width:1,wordSpacing:1},Ix=i=>String.fromCharCode(i+(i>25?39:97)),ks=i=>(e=>{let t,n="";for(t=Math.abs(e);t>52;t=t/52|0)n=Ix(t%52)+n;return Ix(t%52)+n})(((e,t)=>{let n=t.length;for(;n;)e=33*e^t.charCodeAt(--n);return e})(5381,JSON.stringify(i))>>>0),Ua=["themed","global","styled","onevar","resonevar","allvar","inline"],qO=i=>{if(i.href&&!i.href.startsWith(location.origin))return!1;try{return!!i.cssRules}catch{return!1}},YO=i=>{let e;const t=()=>{const{cssRules:r}=e.sheet;return[].map.call(r,(s,o)=>{const{cssText:a}=s;let l="";if(a.startsWith("--sxs"))return"";if(r[o-1]&&(l=r[o-1].cssText).startsWith("--sxs")){if(!s.cssRules.length)return"";for(const c in e.rules)if(e.rules[c].group===s)return`--sxs{--sxs:${[...e.rules[c].cache].join(" ")}}${a}`;return s.cssRules.length?`${l}${a}`:""}return a}).join("")},n=()=>{if(e){const{rules:a,sheet:l}=e;if(!l.deleteRule){for(;Object(Object(l.cssRules)[0]).type===3;)l.cssRules.splice(0,1);l.cssRules=[]}for(const c in a)delete a[c]}const r=Object(i).styleSheets||[];for(const a of r)if(qO(a)){for(let l=0,c=a.cssRules;c[l];++l){const u=Object(c[l]);if(u.type!==1)continue;const d=Object(c[l+1]);if(d.type!==4)continue;++l;const{cssText:h}=u;if(!h.startsWith("--sxs"))continue;const f=h.slice(14,-3).trim().split(/\s+/),p=Ua[f[0]];p&&(e||(e={sheet:a,reset:n,rules:{},toString:t}),e.rules[p]={group:d,index:l,cache:new Set(f)})}if(e)break}if(!e){const a=(l,c)=>({type:c,cssRules:[],insertRule(u,d){this.cssRules.splice(d,0,a(u,{import:3,undefined:1}[(u.toLowerCase().match(/^@([a-z]+)/)||[])[1]]||4))},get cssText(){return l==="@media{}"?`@media{${[].map.call(this.cssRules,u=>u.cssText).join("")}}`:l}});e={sheet:i?(i.head||i).appendChild(document.createElement("style")).sheet:a("","text/css"),rules:{},reset:n,toString:t}}const{sheet:s,rules:o}=e;for(let a=Ua.length-1;a>=0;--a){const l=Ua[a];if(!o[l]){const c=Ua[a+1],u=o[c]?o[c].index:s.cssRules.length;s.insertRule("@media{}",u),s.insertRule(`--sxs{--sxs:${a}}`,u),o[l]={group:s.cssRules[u+1],index:u,cache:new Set([a])}}XO(o[l])}};return n(),e},XO=i=>{const e=i.group;let t=e.cssRules.length;i.apply=n=>{try{e.insertRule(n,t),++t}catch{}}},$a=Symbol(),ZO=yo(),Px=(i,e)=>ZO(i,()=>(...t)=>{let n={type:null,composers:new Set};for(const r of t)if(r!=null)if(r[Ls]){n.type==null&&(n.type=r[Ls].type);for(const s of r[Ls].composers)n.composers.add(s)}else r.constructor!==Object||r.$$typeof?n.type==null&&(n.type=r):n.composers.add(QO(r,i));return n.type==null&&(n.type="span"),n.composers.size||n.composers.add(["PJLV",{},[],[],{},[]]),JO(i,n,e)}),QO=({variants:i,compoundVariants:e,defaultVariants:t,...n},r)=>{const s=`${ar(r.prefix)}c-${ks(n)}`,o=[],a=[],l=Object.create(null),c=[];for(const h in t)l[h]=String(t[h]);if(typeof i=="object"&&i)for(const h in i){u=l,d=h,$O.call(u,d)||(l[h]="undefined");const f=i[h];for(const p in f){const g={[h]:String(p)};String(p)==="undefined"&&c.push(h);const m=f[p],v=[g,m,!_x(m)];o.push(v)}}var u,d;if(typeof e=="object"&&e)for(const h of e){let{css:f,...p}=h;f=typeof f=="object"&&f||{};for(const m in p)p[m]=String(p[m]);const g=[p,f,!_x(f)];a.push(g)}return[s,n,o,a,l,c]},JO=(i,e,t)=>{const[n,r,s,o]=eM(e.composers),a=typeof e.type=="function"||e.type.$$typeof?(d=>{function h(){for(let f=0;f<h[$a].length;f++){const[p,g]=h[$a][f];d.rules[p].apply(g)}return h[$a]=[],null}return h[$a]=[],h.rules={},Ua.forEach(f=>h.rules[f]={apply:p=>h[$a].push([f,p])}),h})(t):null,l=(a||t).rules,c=`.${n}${r.length>1?`:where(.${r.slice(1).join(".")})`:""}`,u=d=>{d=typeof d=="object"&&d||tM;const{css:h,...f}=d,p={};for(const v in s)if(delete f[v],v in d){let y=d[v];typeof y=="object"&&y?p[v]={"@initial":s[v],...y}:(y=String(y),p[v]=y!=="undefined"||o.has(v)?y:s[v])}else p[v]=s[v];const g=new Set([...r]);for(const[v,y,S,x]of e.composers){t.rules.styled.cache.has(v)||(t.rules.styled.cache.add(v),xo(y,[`.${v}`],[],i,b=>{l.styled.apply(b)}));const E=Lx(S,p,i.media),C=Lx(x,p,i.media,!0);for(const b of E)if(b!==void 0)for(const[I,D,P]of b){const k=`${v}-${ks(D)}-${I}`;g.add(k);const N=(P?t.rules.resonevar:t.rules.onevar).cache,B=P?l.resonevar:l.onevar;N.has(k)||(N.add(k),xo(D,[`.${k}`],[],i,K=>{B.apply(K)}))}for(const b of C)if(b!==void 0)for(const[I,D]of b){const P=`${v}-${ks(D)}-${I}`;g.add(P),t.rules.allvar.cache.has(P)||(t.rules.allvar.cache.add(P),xo(D,[`.${P}`],[],i,k=>{l.allvar.apply(k)}))}}if(typeof h=="object"&&h){const v=`${n}-i${ks(h)}-css`;g.add(v),t.rules.inline.cache.has(v)||(t.rules.inline.cache.add(v),xo(h,[`.${v}`],[],i,y=>{l.inline.apply(y)}))}for(const v of String(d.className||"").trim().split(/\s+/))v&&g.add(v);const m=f.className=[...g].join(" ");return{type:e.type,className:m,selector:c,props:f,toString:()=>m,deferredInjector:a}};return Pf(u,{className:n,selector:c,[Ls]:e,toString:()=>(t.rules.styled.cache.has(n)||u(),n)})},eM=i=>{let e="";const t=[],n={},r=[];for(const[s,,,,o,a]of i){e===""&&(e=s),t.push(s),r.push(...a);for(const l in o){const c=o[l];(n[l]===void 0||c!=="undefined"||a.includes(c))&&(n[l]=c)}}return[e,t,n,new Set(r)]},Lx=(i,e,t,n)=>{const r=[];e:for(let[s,o,a]of i){if(a)continue;let l,c=0,u=!1;for(l in s){const d=s[l];let h=e[l];if(h!==d){if(typeof h!="object"||!h)continue e;{let f,p,g=0;for(const m in h){if(d===String(h[m])){if(m!=="@initial"){const v=m.slice(1);(p=p||[]).push(v in t?t[v]:m.replace(/^@media ?/,"")),u=!0}c+=g,f=!0}++g}if(p&&p.length&&(o={["@media "+p.join(", ")]:o}),!f)continue e}}}(r[c]=r[c]||[]).push([n?"cv":`${l}-${s[l]}`,o,u])}return r},tM={},iM=yo(),nM=(i,e)=>iM(i,()=>(...t)=>{const n=()=>{for(let r of t){r=typeof r=="object"&&r||{};let s=ks(r);if(!e.rules.global.cache.has(s)){if(e.rules.global.cache.add(s),"@import"in r){let o=[].indexOf.call(e.sheet.cssRules,e.rules.themed.group)-1;for(let a of[].concat(r["@import"]))a=a.includes('"')||a.includes("'")?a:`"${a}"`,e.sheet.insertRule(`@import ${a};`,o++);delete r["@import"]}xo(r,[],[],i,o=>{e.rules.global.apply(o)})}}return""};return Pf(n,{toString:n})}),rM=yo(),sM=(i,e)=>rM(i,()=>t=>{const n=`${ar(i.prefix)}k-${ks(t)}`,r=()=>{if(!e.rules.global.cache.has(n)){e.rules.global.cache.add(n);const s=[];xo(t,[],[],i,a=>s.push(a));const o=`@keyframes ${n}{${s.join("")}}`;e.rules.global.apply(o)}return n};return Pf(r,{get name(){return r()},toString:r})}),oM=class{constructor(e,t,n,r){this.token=e==null?"":String(e),this.value=t==null?"":String(t),this.scale=n==null?"":String(n),this.prefix=r==null?"":String(r)}get computedValue(){return"var("+this.variable+")"}get variable(){return"--"+ar(this.prefix)+ar(this.scale)+this.token}toString(){return this.computedValue}},aM=yo(),lM=(i,e)=>aM(i,()=>(t,n)=>{n=typeof t=="object"&&t||Object(n);const r=`.${t=(t=typeof t=="string"?t:"")||`${ar(i.prefix)}t-${ks(n)}`}`,s={},o=[];for(const l in n){s[l]={};for(const c in n[l]){const u=`--${ar(i.prefix)}${l}-${c}`,d=Rx(String(n[l][c]),i.prefix,l);s[l][c]=new oM(c,d,l,i.prefix),o.push(`${u}:${d}`)}}const a=()=>{if(o.length&&!e.rules.themed.cache.has(t)){e.rules.themed.cache.add(t);const l=`${n===i.theme?":root,":""}.${t}{${o.join(";")}}`;e.rules.themed.apply(l)}return t};return{...s,get className(){return a()},selector:r,toString:a}}),cM=yo(),kx,uM=yo(),Dx=i=>{const e=(t=>{let n=!1;const r=cM(t,s=>{n=!0;const o="prefix"in(s=typeof s=="object"&&s||{})?String(s.prefix):"",a=typeof s.media=="object"&&s.media||{},l=typeof s.root=="object"?s.root||null:globalThis.document||null,c=typeof s.theme=="object"&&s.theme||{},u={prefix:o,media:a,theme:c,themeMap:typeof s.themeMap=="object"&&s.themeMap||{...BO},utils:typeof s.utils=="object"&&s.utils||{}},d=YO(l),h={css:Px(u,d),globalCss:nM(u,d),keyframes:sM(u,d),createTheme:lM(u,d),reset(){d.reset(),h.theme.toString()},theme:{},sheet:d,config:u,prefix:o,getCssText:d.toString,toString:d.toString};return String(h.theme=h.createTheme(c)),h});return n||r.reset(),r})(i);return e.styled=(({config:t,sheet:n})=>uM(t,()=>{const r=Px(t,n);return(...s)=>{const o=r(...s),a=o[Ls].type,l=et.forwardRef((c,u)=>{const d=c&&c.as||a,{props:h,deferredInjector:f}=o(c);return delete h.as,h.ref=u,f?et.createElement(et.Fragment,null,et.createElement(d,h),et.createElement(f,null)):et.createElement(d,h)});return l.className=o.className,l.displayName=`Styled.${a.displayName||a.name||a}`,l.selector=o.selector,l.toString=()=>o.selector,l[Ls]=o[Ls],l}}))(e),e},dM=()=>kx||(kx=Dx()),hM=(...i)=>dM().createTheme(...i);const Df=209,fM={colors:{primary:"#1a1d1e",primaryMuted:"#26292b",primaryAlt:"#151718",accent:`hsl(${Df} 100% 38.2%)`,accentMuted:`hsl(${Df} 80% 61.8%)`,accentAlt:`hsl(${Df} 80% 30%)`,secondary:"#FFFFFF",secondaryMuted:"#e6e8eb",secondaryAlt:"#c1c8cd"},fontSizes:{1:"12px",2:"13px",3:"15px",4:"17px",5:"19px",6:"21px",7:"27px",8:"35px",9:"59px"},lineHeights:{1:"12px",2:"13px",3:"15px",4:"17px",5:"19px",6:"21px",7:"27px",8:"35px",9:"59px"},sizes:{1:"5px",2:"10px",3:"15px",4:"20px",5:"25px",6:"35px",7:"45px",8:"65px",9:"80px"},space:{1:"5px",2:"10px",3:"15px",4:"20px",5:"25px",6:"35px",7:"45px",8:"65px",9:"80px"},radii:{1:"4px",2:"6px",3:"8px",4:"12px",round:"50%",pill:"9999px"},transitions:{all:"all 200ms cubic-bezier(0.16, 1, 0.3, 1)"},zIndices:{1:"100",2:"200",3:"300",4:"400",max:"999"}},Ox={xxs:"(max-width: 349px)",xs:"(max-width: 575px)",sm:"(max-width: 767px)",md:"(max-width: 991px)",lg:"(max-width: 90rem)",xl:"(min-width: calc(90rem + 1px))"},{styled:oe,css:y9,keyframes:Mx,createTheme:S9}=Dx({theme:fM,media:Ox}),pM=oe("div",{display:"flex",flexDirection:"column",alignItems:"center"}),gM=oe("p",{fontWeight:"bold",fontSize:"x-large"}),mM=oe("span",{fontSize:"medium"}),Of=({error:i})=>{const{message:e}=i;return T(pM,{role:"alert",children:[T(gM,{"data-testid":"headline",children:"Something went wrong"}),e&&T(mM,{children:[`Error message: ${e}`," "]})]})},Mf=oe("div",{position:"absolute !important",zIndex:"1",top:"1rem",left:"1rem",width:"161.8px",height:"100px",backgroundColor:"#000D",boxShadow:"5px 5px 5px #0002",borderRadius:"3px",".displayregion":{border:" 3px solid $accent !important",boxShadow:"0 0 3px #0006"},"@sm":{width:"123px",height:"76px"},"@xs":{width:"100px",height:"61.8px"}}),vM=oe("div",{position:"relative",width:"100%",height:"100%",zIndex:"0",".clover-iiif-image-openseadragon-annotation":{position:"relative",backgroundColor:"transparent",border:"2px solid #0003",boxSizing:"content-box",borderRadius:"3px",boxShadow:"0 0 38vw 38vw transparent",transition:"box-shadow 100ms ease-in-out",zIndex:"0",label:{opacity:0,position:"absolute",lineHeight:"1.47rem",pointerEvents:"none",textAlign:"center",minWidth:"300px",maxWidth:"20vw",padding:"0.5rem",borderRadius:"3px",top:"calc(100% + 0.5rem)",left:"50%",transform:"translate(-50%, 0)",backgroundColor:"$primary",color:"$secondary",transition:"opacity 100ms ease-in-out"},"&[data-active=true]":{border:"2px solid $accent !important",boxShadow:"0 0 38vw 38vw #0003",zIndex:"99999999",label:{opacity:1}}}}),yM=oe("div",{width:"100%",height:"100%",maxHeight:"100vh",background:"transparent",backgroundSize:"contain",color:"white",position:"relative",zIndex:"0",overflow:"hidden",variants:{hasNavigator:{true:{[`${Mf}`]:{display:"block"}},false:{[`${Mf}`]:{display:"none"}}}}}),SM=i=>{const e=i.toString().split(":"),t=Math.ceil(parseInt(e[0])),n=Math.ceil(parseInt(e[1])),r=xM(Math.ceil(parseInt(e[2])),2);let o=`${t!==0&&n<10?(n+"").padStart(2,"0"):n}:${r}`;return t!==0&&(o=`${t}:${o}`),o},Fx=i=>{const e=new Date(i*1e3).toISOString().substr(11,8);return SM(e)},Nx=(i,e)=>{if(typeof i!="object"||i===null)return e;for(const t in e)typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?(i[t]||(i[t]={}),i[t]=Nx(i[t],e[t])):i[t]=e[t];return i},Bx=i=>i.split("").reduce(function(e,t){return e=(e<<5)-e+t.charCodeAt(0),e&e},0),Ux=(i,e)=>Object.hasOwn(i,e)?i[e].toString():void 0,xM=(i,e)=>String(i).padStart(e,"0");let Ac;const TM=new Uint8Array(16);function EM(){if(!Ac&&(Ac=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ac))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ac(TM)}const qt=[];for(let i=0;i<256;++i)qt.push((i+256).toString(16).slice(1));function wM(i,e=0){return qt[i[e+0]]+qt[i[e+1]]+qt[i[e+2]]+qt[i[e+3]]+"-"+qt[i[e+4]]+qt[i[e+5]]+"-"+qt[i[e+6]]+qt[i[e+7]]+"-"+qt[i[e+8]]+qt[i[e+9]]+"-"+qt[i[e+10]]+qt[i[e+11]]+qt[i[e+12]]+qt[i[e+13]]+qt[i[e+14]]+qt[i[e+15]]}const $x={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function To(i,e,t){if($x.randomUUID&&!i)return $x.randomUUID();i=i||{};const n=i.random||(i.rng||EM)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,wM(n)}const Hx={behavior:"smooth",block:"center"},un={annotationOverlays:{backgroundColor:"#6666ff",borderColor:"#000099",borderType:"solid",borderWidth:"1px",opacity:"0.5",renderOverlays:!0,zoomLevel:2},annotations:{motivations:void 0},background:"transparent",canvasBackgroundColor:"#6662",canvasHeight:"500px",contentSearch:{searchResultsLimit:20,overlays:{backgroundColor:"#ff6666",borderColor:"#990000",borderType:"solid",borderWidth:"1px",opacity:"0.5",renderOverlays:!0,zoomLevel:4}},crossOrigin:"anonymous",ignoreCaptionLabels:[],informationPanel:{vtt:{autoScroll:{enabled:!0,settings:Hx}},open:!0,renderAbout:!0,renderSupplementing:!0,renderToggle:!0,renderAnnotation:!0,renderContentSearch:!0},openSeadragon:{},requestHeaders:{"Content-Type":"application/json"},showDownload:!0,showIIIFBadge:!0,showTitle:!0,withCredentials:!1},Ff=(i=un)=>Nf(i);function Nf(i){return Array.isArray(i)?i.map(e=>Nf(e)):i&&typeof i=="object"?Object.entries(i).reduce((e,[t,n])=>(e[t]=Nf(n),e),{}):i}function zx(i){const t=(()=>{var o,a;return((a=(o=un==null?void 0:un.informationPanel)==null?void 0:o.vtt)==null?void 0:a.autoScroll)||{enabled:!0,settings:Hx}})();if(i==null)return{enabled:t.enabled,settings:{...t.settings}};if(typeof i=="boolean")return{enabled:i,settings:{...t.settings}};if("enabled"in i){const s=i;return{enabled:s.enabled,settings:{...s.settings}}}const r={enabled:!0,settings:{...i}};return bM(r.settings),r}function bM({behavior:i,block:e}){const t=["auto","instant","smooth"],n=["center","end","nearest","start"];if(!t.includes(i))throw TypeError(`'${i}' not in ${t.join(" | ")}`);if(!n.includes(e))throw TypeError(`'${e}' not in ${n.join(" | ")}`)}const _M=zx((qP=(KP=un==null?void 0:un.informationPanel)==null?void 0:KP.vtt)==null?void 0:qP.autoScroll),Vx=()=>{var i;return{activeCanvas:"",activeManifest:"",activePlayer:null,activeSelector:void 0,OSDImageLoaded:!1,collection:{},configOptions:Ff(),customDisplays:[],plugins:[],isAutoScrollEnabled:_M.enabled,isAutoScrolling:!1,isInformationOpen:((i=un==null?void 0:un.informationPanel)==null?void 0:i.open)??!0,isLoaded:!1,isMediaPlaying:!1,isPaged:!1,isUserScrolling:void 0,sequence:[[],[]],vault:new wx,viewingDirection:"left-to-right",openSeadragonViewer:null,viewerId:To(),visibleCanvases:[],visibleAnnotations:[]}},Bf=Vx(),Gx=et.createContext(Bf),Wx=et.createContext(Bf);function AM(i,e){switch(e.type){case"updateActiveCanvas":return e.canvasId||(e.canvasId=""),{...i,activeCanvas:e.canvasId};case"updateActiveManifest":return{...i,activeManifest:e.manifestId};case"updateActivePlayer":return{...i,activePlayer:e.player};case"updateOSDImageLoaded":return{...i,OSDImageLoaded:e.OSDImageLoaded};case"updateAutoScrollAnnotationEnabled":return{...i,isAutoScrollEnabled:e.isAutoScrollEnabled};case"updateAutoScrolling":return{...i,isAutoScrolling:e.isAutoScrolling};case"updateCollection":return{...i,collection:e.collection};case"updateConfigOptions":{const t=Nx(Ff(i.configOptions),e.configOptions);return{...i,configOptions:t}}case"updateContentStateAnnotation":return{...i,contentStateAnnotation:e.contentStateAnnotation};case"updateInformationOpen":return{...i,isInformationOpen:e.isInformationOpen};case"updateInformationPanelResource":return{...i,informationPanelResource:e.informationPanelResource};case"updateIsLoaded":return{...i,isLoaded:e.isLoaded};case"updateIsMediaPlaying":return{...i,isMediaPlaying:e.isMediaPlaying??!1};case"updateManifestSequence":return{...i,sequence:e.sequence};case"updateUserScrolling":return{...i,isUserScrolling:e.isUserScrolling};case"updateOpenSeadragonViewer":return{...i,openSeadragonViewer:e.openSeadragonViewer};case"updateViewerId":return{...i,viewerId:e.viewerId};case"updateActiveSelector":return{...i,activeSelector:e.selector};case"updateVisibleCanvases":return{...i,visibleCanvases:e.visibleCanvases};case"updateViewingDirection":return{...i,viewingDirection:e.viewingDirection};case"updateIsPaged":return{...i,isPaged:e.isPaged};default:throw new Error(`Unhandled action type: ${e.type}`)}}const RM=({initialState:i,children:e})=>{const[t,n]=ho(AM,i,s=>s?{...s,configOptions:Ff(s.configOptions??un),viewerId:s.viewerId??To()}:Vx()),{openSeadragonViewer:r}=t;return ne(()=>{if(r)return r.addHandler("update-viewport",()=>{const s=r.viewport,o=s.getBounds(),a=s.viewportToImageRectangle(o),c=`xywh=${[Math.round(a.x),Math.round(a.y),Math.round(a.width),Math.round(a.height)].join(",")}`;n({type:"updateActiveSelector",selector:{type:"FragmentSelector",value:c}})}),()=>{r.removeAllHandlers("update-viewport")}},[r]),T(Gx.Provider,{value:t,children:T(Wx.Provider,{value:n,children:e})})};function gt(){const i=et.useContext(Gx);if(i===void 0)throw new Error("useViewerState must be used within a ViewerProvider");return i}function Ti(){const i=et.useContext(Wx);if(i===void 0)throw new Error("useViewerDispatch must be used within a ViewerProvider");return i}const jx=oe("button",{display:"flex",height:"2rem",width:"2rem",borderRadius:"2rem",padding:"0",margin:"0",fontFamily:"inherit",background:"none",backgroundColor:"$primary",border:"none",color:"white",cursor:"pointer",marginLeft:"0.618rem",filter:"drop-shadow(2px 2px 5px #0003)",transition:"$all",boxSizing:"content-box !important","&:first-child":{marginLeft:"0"},"@xs":{marginBottom:"0.618rem",marginLeft:"0","&:last-child":{marginBottom:"0"}},svg:{height:"60%",width:"60%",padding:"20%",fill:"$secondary",stroke:"$secondary",filter:"drop-shadow(2px 2px 5px #0003)",transition:"$all",boxSizing:"inherit"},"&:hover, &:focus":{backgroundColor:"$accent"},"&[data-button=rotate-right]":{"&:hover, &:focus":{svg:{rotate:"45deg"}}},"&[data-button=rotate-left]":{transform:"scaleX(-1)","&:hover, &:focus":{svg:{rotate:"45deg"}}},"&[data-button=reset]":{"&:hover, &:focus":{svg:{rotate:"-15deg"}}}}),Eo=({className:i,id:e,label:t,children:n})=>{const s=e.split("-")[0].replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"");return T(jx,{id:e,className:i,"data-testid":"openseadragon-button","data-button":s,children:T("svg",{xmlns:"http://www.w3.org/2000/svg","aria-labelledby":`${e}-svg-title`,"data-testid":"openseadragon-button-svg",focusable:"false",viewBox:"0 0 512 512",role:"img",children:[T("title",{id:`${e}-svg-title`,children:t}),n]})})},CM=oe("div",{position:"absolute",zIndex:"1",top:"1rem",right:"1rem",display:"flex","@xs":{flexDirection:"column",zIndex:"2"},variants:{hasPlaceholder:{true:{right:"3.618rem","@xs":{top:"3.618rem",right:"1rem"}},false:{right:"1rem","@xs":{top:"1rem",right:"1rem"}}}}}),IM=(i,e,t,n)=>{var s,o,a,l;const r=[t,{code:e,...n||{}}];if((o=(s=i==null?void 0:i.services)==null?void 0:s.logger)!=null&&o.forward)return i.services.logger.forward(r,"warn","react-i18next::",!0);Ds(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),(l=(a=i==null?void 0:i.services)==null?void 0:a.logger)!=null&&l.warn?i.services.logger.warn(...r):console!=null&&console.warn&&console.warn(...r)},Kx={},Uf=(i,e,t,n)=>{Ds(t)&&Kx[t]||(Ds(t)&&(Kx[t]=new Date),IM(i,e,t,n))},qx=(i,e)=>()=>{if(i.isInitialized)e();else{const t=()=>{setTimeout(()=>{i.off("initialized",t)},0),e()};i.on("initialized",t)}},$f=(i,e,t)=>{i.loadNamespaces(e,qx(i,t))},Yx=(i,e,t,n)=>{if(Ds(t)&&(t=[t]),i.options.preload&&i.options.preload.indexOf(e)>-1)return $f(i,t,n);t.forEach(r=>{i.options.ns.indexOf(r)<0&&i.options.ns.push(r)}),i.loadLanguages(e,qx(i,n))},PM=(i,e,t={})=>!e.languages||!e.languages.length?(Uf(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(i,{lng:t.lng,precheck:(n,r)=>{if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,i))return!1}}),Ds=i=>typeof i=="string",LM=i=>typeof i=="object"&&i!==null,kM=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,DM={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},OM=i=>DM[i];let Hf={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:i=>i.replace(kM,OM)};const MM=(i={})=>{Hf={...Hf,...i}},FM=()=>Hf;let Xx;const NM=i=>{Xx=i},BM=()=>Xx,UM={type:"3rdParty",init(i){MM(i.options.react),NM(i)}},$M=ln();class HM{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(t=>{this.usedNamespaces[t]||(this.usedNamespaces[t]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const zM=(i,e)=>{const t=ge();return ne(()=>{t.current=i},[i,e]),t.current},Zx=(i,e,t,n)=>i.getFixedT(e,t,n),VM=(i,e,t,n)=>Ce(Zx(i,e,t,n),[i,e,t,n]),GM=(i,e={})=>{var x,E,C,b;const{i18n:t}=e,{i18n:n,defaultNS:r}=Cn($M)||{},s=t||n||BM();if(s&&!s.reportNamespaces&&(s.reportNamespaces=new HM),!s){Uf(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const I=(P,k)=>Ds(k)?k:LM(k)&&Ds(k.defaultValue)?k.defaultValue:Array.isArray(P)?P[P.length-1]:P,D=[I,{},!1];return D.t=I,D.i18n={},D.ready=!1,D}(x=s.options.react)!=null&&x.wait&&Uf(s,"DEPRECATED_OPTION","useTranslation: It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const o={...FM(),...s.options.react,...e},{useSuspense:a,keyPrefix:l}=o;let c=i||r||((E=s.options)==null?void 0:E.defaultNS);c=Ds(c)?[c]:c||["translation"],(b=(C=s.reportNamespaces).addUsedNamespaces)==null||b.call(C,c);const u=(s.isInitialized||s.initializedStoreOnce)&&c.every(I=>PM(I,s,o)),d=VM(s,e.lng||null,o.nsMode==="fallback"?c:c[0],l),h=()=>d,f=()=>Zx(s,e.lng||null,o.nsMode==="fallback"?c:c[0],l),[p,g]=se(h);let m=c.join();e.lng&&(m=`${e.lng}${m}`);const v=zM(m),y=ge(!0);ne(()=>{const{bindI18n:I,bindI18nStore:D}=o;y.current=!0,!u&&!a&&(e.lng?Yx(s,e.lng,c,()=>{y.current&&g(f)}):$f(s,c,()=>{y.current&&g(f)})),u&&v&&v!==m&&y.current&&g(f);const P=()=>{y.current&&g(f)};return I&&(s==null||s.on(I,P)),D&&(s==null||s.store.on(D,P)),()=>{y.current=!1,s&&I&&(I==null||I.split(" ").forEach(k=>s.off(k,P))),D&&s&&D.split(" ").forEach(k=>s.store.off(k,P))}},[s,m]),ne(()=>{y.current&&u&&g(h)},[s,l,u]);const S=[p,s,u];if(S.t=p,S.i18n=s,S.ready=u,u||!u&&!a)return S;throw new Promise(I=>{e.lng?Yx(s,e.lng,c,()=>I()):$f(s,c,()=>I())})},Qx={commonClose:"Close",commonNext:"Next",commonOpen:"Open",commonPrevious:"Previous",commonSearch:"Search",commonSearchPlaceholder:"Search...",commonShare:"Share",commonViewAll:"View All",copyFailure:"Failed",copySuccess:"Copied",contentSearchLoading:"Loading...",contentSearchPlaceholder:"Search",contentSearchResultsNone:"No Results",contentSearchResultsMore:"More Results",imageFullScreen:"Full screen",imageResetZoom:"Reset zoom",imageRotateLeft:"Rotate left",imageRotateRight:"Rotate right",imageZoomIn:"Zoom in",imageZoomOut:"Zoom out",informationPanelTabs:"Select",informationPanelTabsClose:"Viewer",informationPanelTabsAbout:"About",informationPanelTabsAnnotations:"Annotations",informationPanelTabsSearch:"Search",informationPanelToggle:"More Information",shareCollectionJson:"View Collection",shareCollectionCopy:"Copy Collection URL",shareManifestJson:"View Manifest",shareManifestCopy:"Copy Manifest URL",canvasAnimationPlay:"Play",canvasAnimationPause:"Pause",canvasAnimationPreviousFrame:"Previous frame",canvasAnimationNextFrame:"Next frame",canvasAnimationRepeat:"Repeat",canvasAnimationSpeed:"Speed"},{slice:WM,forEach:jM}=[];function KM(i){return jM.call(WM.call(arguments,1),e=>{if(e)for(const t in e)i[t]===void 0&&(i[t]=e[t])}),i}function qM(i){return typeof i!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(i))}const Jx=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,YM=function(i,e){const n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},r=encodeURIComponent(e);let s=`${i}=${r}`;if(n.maxAge>0){const o=n.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(o)}`}if(n.domain){if(!Jx.test(n.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${n.domain}`}if(n.path){if(!Jx.test(n.path))throw new TypeError("option path is invalid");s+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(s+="; HttpOnly"),n.secure&&(s+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return n.partitioned&&(s+="; Partitioned"),s},eT={create(i,e,t,n){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(r.expires=new Date,r.expires.setTime(r.expires.getTime()+t*60*1e3)),n&&(r.domain=n),document.cookie=YM(i,e,r)},read(i){const e=`${i}=`,t=document.cookie.split(";");for(let n=0;n<t.length;n++){let r=t[n];for(;r.charAt(0)===" ";)r=r.substring(1,r.length);if(r.indexOf(e)===0)return r.substring(e.length,r.length)}return null},remove(i,e){this.create(i,"",-1,e)}};var XM={name:"cookie",lookup(i){let{lookupCookie:e}=i;if(e&&typeof document<"u")return eT.read(e)||void 0},cacheUserLanguage(i,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:r,cookieOptions:s}=e;t&&typeof document<"u"&&eT.create(t,i,n,r,s)}},ZM={name:"querystring",lookup(i){var n;let{lookupQuerystring:e}=i,t;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const o=r.substring(1).split("&");for(let a=0;a<o.length;a++){const l=o[a].indexOf("=");l>0&&o[a].substring(0,l)===e&&(t=o[a].substring(l+1))}}return t}},QM={name:"hash",lookup(i){var r;let{lookupHash:e,lookupFromHashIndex:t}=i,n;if(typeof window<"u"){const{hash:s}=window.location;if(s&&s.length>2){const o=s.substring(1);if(e){const a=o.split("&");for(let l=0;l<a.length;l++){const c=a[l].indexOf("=");c>0&&a[l].substring(0,c)===e&&(n=a[l].substring(c+1))}}if(n)return n;if(!n&&t>-1){const a=s.match(/\/([a-zA-Z-]*)/g);return Array.isArray(a)?(r=a[typeof t=="number"?t:0])==null?void 0:r.replace("/",""):void 0}}}return n}};let wo=null;const tT=()=>{if(wo!==null)return wo;try{if(wo=typeof window<"u"&&window.localStorage!==null,!wo)return!1;const i="i18next.translate.boo";window.localStorage.setItem(i,"foo"),window.localStorage.removeItem(i)}catch{wo=!1}return wo};var JM={name:"localStorage",lookup(i){let{lookupLocalStorage:e}=i;if(e&&tT())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(i,e){let{lookupLocalStorage:t}=e;t&&tT()&&window.localStorage.setItem(t,i)}};let bo=null;const iT=()=>{if(bo!==null)return bo;try{if(bo=typeof window<"u"&&window.sessionStorage!==null,!bo)return!1;const i="i18next.translate.boo";window.sessionStorage.setItem(i,"foo"),window.sessionStorage.removeItem(i)}catch{bo=!1}return bo};var eF={name:"sessionStorage",lookup(i){let{lookupSessionStorage:e}=i;if(e&&iT())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(i,e){let{lookupSessionStorage:t}=e;t&&iT()&&window.sessionStorage.setItem(t,i)}},tF={name:"navigator",lookup(i){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:n,language:r}=navigator;if(t)for(let s=0;s<t.length;s++)e.push(t[s]);n&&e.push(n),r&&e.push(r)}return e.length>0?e:void 0}},iF={name:"htmlTag",lookup(i){let{htmlTag:e}=i,t;const n=e||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(t=n.getAttribute("lang")),t}},nF={name:"path",lookup(i){var r;let{lookupFromPathIndex:e}=i;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(r=t[typeof e=="number"?e:0])==null?void 0:r.replace("/",""):void 0}},rF={name:"subdomain",lookup(i){var r,s;let{lookupFromSubdomainIndex:e}=i;const t=typeof e=="number"?e+1:1,n=typeof window<"u"&&((s=(r=window.location)==null?void 0:r.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[t]}};let nT=!1;try{document.cookie,nT=!0}catch{}const rT=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];nT||rT.splice(1,1);const sF=()=>({order:rT,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:i=>i});class sT{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=KM(t,this.options||{},sF()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=r=>r.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(XM),this.addDetector(ZM),this.addDetector(JM),this.addDetector(eF),this.addDetector(tF),this.addDetector(iF),this.addDetector(nF),this.addDetector(rF),this.addDetector(QM)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(n=>{if(this.detectors[n]){let r=this.detectors[n].lookup(this.options);r&&typeof r=="string"&&(r=[r]),r&&(t=t.concat(r))}}),t=t.filter(n=>n!=null&&!qM(n)).map(n=>this.options.convertDetectedLanguage(n)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(e,this.options)}))}}sT.type="languageDetector";const Ne=i=>typeof i=="string",Ha=()=>{let i,e;const t=new Promise((n,r)=>{i=n,e=r});return t.resolve=i,t.reject=e,t},oT=i=>i==null?"":""+i,oF=(i,e,t)=>{i.forEach(n=>{e[n]&&(t[n]=e[n])})},aF=/###/g,aT=i=>i&&i.indexOf("###")>-1?i.replace(aF,"."):i,lT=i=>!i||Ne(i),za=(i,e,t)=>{const n=Ne(e)?e.split("."):e;let r=0;for(;r<n.length-1;){if(lT(i))return{};const s=aT(n[r]);!i[s]&&t&&(i[s]=new t),Object.prototype.hasOwnProperty.call(i,s)?i=i[s]:i={},++r}return lT(i)?{}:{obj:i,k:aT(n[r])}},cT=(i,e,t)=>{const{obj:n,k:r}=za(i,e,Object);if(n!==void 0||e.length===1){n[r]=t;return}let s=e[e.length-1],o=e.slice(0,e.length-1),a=za(i,o,Object);for(;a.obj===void 0&&o.length;)s=`${o[o.length-1]}.${s}`,o=o.slice(0,o.length-1),a=za(i,o,Object),a&&a.obj&&typeof a.obj[`${a.k}.${s}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${s}`]=t},lF=(i,e,t,n)=>{const{obj:r,k:s}=za(i,e,Object);r[s]=r[s]||[],r[s].push(t)},Rc=(i,e)=>{const{obj:t,k:n}=za(i,e);if(t)return t[n]},cF=(i,e,t)=>{const n=Rc(i,t);return n!==void 0?n:Rc(e,t)},uT=(i,e,t)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(n in i?Ne(i[n])||i[n]instanceof String||Ne(e[n])||e[n]instanceof String?t&&(i[n]=e[n]):uT(i[n],e[n],t):i[n]=e[n]);return i},_o=i=>i.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var uF={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const dF=i=>Ne(i)?i.replace(/[&<>"'\/]/g,e=>uF[e]):i;class hF{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(t!==void 0)return t;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const fF=[" ",",","?","!",";"],pF=new hF(20),gF=(i,e,t)=>{e=e||"",t=t||"";const n=fF.filter(o=>e.indexOf(o)<0&&t.indexOf(o)<0);if(n.length===0)return!0;const r=pF.getRegExp(`(${n.map(o=>o==="?"?"\\?":o).join("|")})`);let s=!r.test(i);if(!s){const o=i.indexOf(t);o>0&&!r.test(i.substring(0,o))&&(s=!0)}return s},zf=function(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!i)return;if(i[e])return i[e];const n=e.split(t);let r=i;for(let s=0;s<n.length;){if(!r||typeof r!="object")return;let o,a="";for(let l=s;l<n.length;++l)if(l!==s&&(a+=t),a+=n[l],o=r[a],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&l<n.length-1)continue;s+=l-s+1;break}r=o}return r},Cc=i=>i&&i.replace("_","-"),mF={type:"logger",log(i){this.output("log",i)},warn(i){this.output("warn",i)},error(i){this.output("error",i)},output(i,e){console&&console[i]&&console[i].apply(console,e)}};let vF=class L0{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(e,t)}init(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=t.prefix||"i18next:",this.logger=e||mF,this.options=t,this.debug=t.debug}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.forward(t,"log","",!0)}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.forward(t,"warn","",!0)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.forward(t,"error","")}deprecate(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,n,r){return r&&!this.debug?null:(Ne(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new L0(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new L0(this.logger,e)}};var Pn=new vF;let Ic=class{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const r=this.observers[n].get(t)||0;this.observers[n].set(t,r+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];this.observers[e]&&Array.from(this.observers[e].entries()).forEach(o=>{let[a,l]=o;for(let c=0;c<l;c++)a(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(o=>{let[a,l]=o;for(let c=0;c<l;c++)a.apply(a,[e,...n])})}};class dT extends Ic{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const s=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,o=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,t],n&&(Array.isArray(n)?a.push(...n):Ne(n)&&s?a.push(...n.split(s)):a.push(n)));const l=Rc(this.data,a);return!l&&!t&&!n&&e.indexOf(".")>-1&&(e=a[0],t=a[1],n=a.slice(2).join(".")),l||!o||!Ne(n)?l:zf(this.data&&this.data[e]&&this.data[e][t],n,s)}addResource(e,t,n,r){let s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let a=[e,t];n&&(a=a.concat(o?n.split(o):n)),e.indexOf(".")>-1&&(a=e.split("."),r=t,t=a[1]),this.addNamespaces(t),cT(this.data,a,r),s.silent||this.emit("added",e,t,n,r)}addResources(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const s in n)(Ne(n[s])||Array.isArray(n[s]))&&this.addResource(e,t,s,n[s],{silent:!0});r.silent||this.emit("added",e,t,n)}addResourceBundle(e,t,n,r,s){let o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},a=[e,t];e.indexOf(".")>-1&&(a=e.split("."),r=n,n=t,t=a[1]),this.addNamespaces(t);let l=Rc(this.data,a)||{};o.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?uT(l,n,s):l={...l,...n},cT(this.data,a,l),o.silent||this.emit("added",e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(e,t)}:this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(r=>t[r]&&Object.keys(t[r]).length>0)}toJSON(){return this.data}}var hT={processors:{},addPostProcessor(i){this.processors[i.name]=i},handle(i,e,t,n,r){return i.forEach(s=>{this.processors[s]&&(e=this.processors[s].process(e,t,n,r))}),e}};const fT={};class Pc extends Ic{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),oF(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Pn.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(e==null)return!1;const n=this.resolve(e,t);return n&&n.res!==void 0}extractFromKey(e,t){let n=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const r=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let s=t.ns||this.options.defaultNS||[];const o=n&&e.indexOf(n)>-1,a=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!gF(e,n,r);if(o&&!a){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:Ne(s)?[s]:s};const c=e.split(n);(n!==r||n===r&&this.options.ns.indexOf(c[0])>-1)&&(s=c.shift()),e=c.join(r)}return{key:e,namespaces:Ne(s)?[s]:s}}translate(e,t,n){if(typeof t!="object"&&this.options.overloadTranslationOptionHandler&&(t=this.options.overloadTranslationOptionHandler(arguments)),typeof t=="object"&&(t={...t}),t||(t={}),e==null)return"";Array.isArray(e)||(e=[String(e)]);const r=t.returnDetails!==void 0?t.returnDetails:this.options.returnDetails,s=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator,{key:o,namespaces:a}=this.extractFromKey(e[e.length-1],t),l=a[a.length-1],c=t.lng||this.language,u=t.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(c&&c.toLowerCase()==="cimode"){if(u){const x=t.nsSeparator||this.options.nsSeparator;return r?{res:`${l}${x}${o}`,usedKey:o,exactUsedKey:o,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(t)}:`${l}${x}${o}`}return r?{res:o,usedKey:o,exactUsedKey:o,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(t)}:o}const d=this.resolve(e,t);let h=d&&d.res;const f=d&&d.usedKey||o,p=d&&d.exactUsedKey||o,g=Object.prototype.toString.apply(h),m=["[object Number]","[object Function]","[object RegExp]"],v=t.joinArrays!==void 0?t.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject,S=!Ne(h)&&typeof h!="boolean"&&typeof h!="number";if(y&&h&&S&&m.indexOf(g)<0&&!(Ne(v)&&Array.isArray(h))){if(!t.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const x=this.options.returnedObjectHandler?this.options.returnedObjectHandler(f,h,{...t,ns:a}):`key '${o} (${this.language})' returned an object instead of string.`;return r?(d.res=x,d.usedParams=this.getUsedParamsDetails(t),d):x}if(s){const x=Array.isArray(h),E=x?[]:{},C=x?p:f;for(const b in h)if(Object.prototype.hasOwnProperty.call(h,b)){const I=`${C}${s}${b}`;E[b]=this.translate(I,{...t,joinArrays:!1,ns:a}),E[b]===I&&(E[b]=h[b])}h=E}}else if(y&&Ne(v)&&Array.isArray(h))h=h.join(v),h&&(h=this.extendTranslation(h,e,t,n));else{let x=!1,E=!1;const C=t.count!==void 0&&!Ne(t.count),b=Pc.hasDefaultValue(t),I=C?this.pluralResolver.getSuffix(c,t.count,t):"",D=t.ordinal&&C?this.pluralResolver.getSuffix(c,t.count,{ordinal:!1}):"",P=C&&!t.ordinal&&t.count===0&&this.pluralResolver.shouldUseIntlApi(),k=P&&t[`defaultValue${this.options.pluralSeparator}zero`]||t[`defaultValue${I}`]||t[`defaultValue${D}`]||t.defaultValue;!this.isValidLookup(h)&&b&&(x=!0,h=k),this.isValidLookup(h)||(E=!0,h=o);const B=(t.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:h,K=b&&k!==h&&this.options.updateMissing;if(E||x||K){if(this.logger.log(K?"updateKey":"missingKey",c,l,o,K?k:h),s){const F=this.resolve(o,{...t,keySeparator:!1});F&&F.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let q=[];const H=this.languageUtils.getFallbackCodes(this.options.fallbackLng,t.lng||this.language);if(this.options.saveMissingTo==="fallback"&&H&&H[0])for(let F=0;F<H.length;F++)q.push(H[F]);else this.options.saveMissingTo==="all"?q=this.languageUtils.toResolveHierarchy(t.lng||this.language):q.push(t.lng||this.language);const X=(F,U,j)=>{const V=b&&j!==h?j:B;this.options.missingKeyHandler?this.options.missingKeyHandler(F,l,U,V,K,t):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(F,l,U,V,K,t),this.emit("missingKey",F,l,U,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?q.forEach(F=>{const U=this.pluralResolver.getSuffixes(F,t);P&&t[`defaultValue${this.options.pluralSeparator}zero`]&&U.indexOf(`${this.options.pluralSeparator}zero`)<0&&U.push(`${this.options.pluralSeparator}zero`),U.forEach(j=>{X([F],o+j,t[`defaultValue${j}`]||k)})}):X(q,o,k))}h=this.extendTranslation(h,e,t,d,n),E&&h===o&&this.options.appendNamespaceToMissingKey&&(h=`${l}:${o}`),(E||x)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}:${o}`:o,x?h:void 0):h=this.options.parseMissingKeyHandler(h))}return r?(d.res=h,d.usedParams=this.getUsedParamsDetails(t),d):h}extendTranslation(e,t,n,r,s){var o=this;if(this.i18nFormat&&this.i18nFormat.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const c=Ne(e)&&(n&&n.interpolation&&n.interpolation.skipOnVariables!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(c){const h=e.match(this.interpolator.nestingRegexp);u=h&&h.length}let d=n.replace&&!Ne(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),e=this.interpolator.interpolate(e,d,n.lng||this.language||r.usedLng,n),c){const h=e.match(this.interpolator.nestingRegexp),f=h&&h.length;u<f&&(n.nest=!1)}!n.lng&&this.options.compatibilityAPI!=="v1"&&r&&r.res&&(n.lng=this.language||r.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,function(){for(var h=arguments.length,f=new Array(h),p=0;p<h;p++)f[p]=arguments[p];return s&&s[0]===f[0]&&!n.context?(o.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${t[0]}`),null):o.translate(...f,t)},n)),n.interpolation&&this.interpolator.reset()}const a=n.postProcess||this.options.postProcess,l=Ne(a)?[a]:a;return e!=null&&l&&l.length&&n.applyPostProcessor!==!1&&(e=hT.handle(l,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n,r,s,o,a;return Ne(e)&&(e=[e]),e.forEach(l=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(l,t),u=c.key;r=u;let d=c.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const h=t.count!==void 0&&!Ne(t.count),f=h&&!t.ordinal&&t.count===0&&this.pluralResolver.shouldUseIntlApi(),p=t.context!==void 0&&(Ne(t.context)||typeof t.context=="number")&&t.context!=="",g=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);d.forEach(m=>{this.isValidLookup(n)||(a=m,!fT[`${g[0]}-${m}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(a)&&(fT[`${g[0]}-${m}`]=!0,this.logger.warn(`key "${r}" for languages "${g.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(v=>{if(this.isValidLookup(n))return;o=v;const y=[u];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,u,v,m,t);else{let x;h&&(x=this.pluralResolver.getSuffix(v,t.count,t));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(y.push(u+x),t.ordinal&&x.indexOf(C)===0&&y.push(u+x.replace(C,this.options.pluralSeparator)),f&&y.push(u+E)),p){const b=`${u}${this.options.contextSeparator}${t.context}`;y.push(b),h&&(y.push(b+x),t.ordinal&&x.indexOf(C)===0&&y.push(b+x.replace(C,this.options.pluralSeparator)),f&&y.push(b+E))}}let S;for(;S=y.pop();)this.isValidLookup(n)||(s=S,n=this.getResource(v,m,S,t))}))})}),{res:n,usedKey:r,exactUsedKey:s,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!Ne(e.replace);let r=n?e.replace:e;if(n&&typeof e.count<"u"&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(const s of t)delete r[s]}return r}static hasDefaultValue(e){const t="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t===n.substring(0,t.length)&&e[n]!==void 0)return!0;return!1}}const Vf=i=>i.charAt(0).toUpperCase()+i.slice(1);class pT{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Pn.create("languageUtils")}getScriptPartFromCode(e){if(e=Cc(e),!e||e.indexOf("-")<0)return null;const t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=Cc(e),!e||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(Ne(e)&&e.indexOf("-")>-1){if(typeof Intl<"u"&&typeof Intl.getCanonicalLocales<"u")try{let r=Intl.getCanonicalLocales(e)[0];if(r&&this.options.lowerCaseLng&&(r=r.toLowerCase()),r)return r}catch{}const t=["hans","hant","latn","cyrl","cans","mong","arab"];let n=e.split("-");return this.options.lowerCaseLng?n=n.map(r=>r.toLowerCase()):n.length===2?(n[0]=n[0].toLowerCase(),n[1]=n[1].toUpperCase(),t.indexOf(n[1].toLowerCase())>-1&&(n[1]=Vf(n[1].toLowerCase()))):n.length===3&&(n[0]=n[0].toLowerCase(),n[1].length===2&&(n[1]=n[1].toUpperCase()),n[0]!=="sgn"&&n[2].length===2&&(n[2]=n[2].toUpperCase()),t.indexOf(n[1].toLowerCase())>-1&&(n[1]=Vf(n[1].toLowerCase())),t.indexOf(n[2].toLowerCase())>-1&&(n[2]=Vf(n[2].toLowerCase()))),n.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(n=>{if(t)return;const r=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(r))&&(t=r)}),!t&&this.options.supportedLngs&&e.forEach(n=>{if(t)return;const r=this.getLanguagePartFromCode(n);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(s=>{if(s===r)return s;if(!(s.indexOf("-")<0&&r.indexOf("-")<0)&&(s.indexOf("-")>0&&r.indexOf("-")<0&&s.substring(0,s.indexOf("-"))===r||s.indexOf(r)===0&&r.length>1))return s})}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),Ne(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||(n=e[this.getScriptPartFromCode(t)]),n||(n=e[this.formatLanguageCode(t)]),n||(n=e[this.getLanguagePartFromCode(t)]),n||(n=e.default),n||[]}toResolveHierarchy(e,t){const n=this.getFallbackCodes(t||this.options.fallbackLng||[],e),r=[],s=o=>{o&&(this.isSupportedCode(o)?r.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return Ne(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(e))):Ne(e)&&s(this.formatLanguageCode(e)),n.forEach(o=>{r.indexOf(o)<0&&s(this.formatLanguageCode(o))}),r}}let yF=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],SF={1:i=>+(i>1),2:i=>+(i!=1),3:i=>0,4:i=>i%10==1&&i%100!=11?0:i%10>=2&&i%10<=4&&(i%100<10||i%100>=20)?1:2,5:i=>i==0?0:i==1?1:i==2?2:i%100>=3&&i%100<=10?3:i%100>=11?4:5,6:i=>i==1?0:i>=2&&i<=4?1:2,7:i=>i==1?0:i%10>=2&&i%10<=4&&(i%100<10||i%100>=20)?1:2,8:i=>i==1?0:i==2?1:i!=8&&i!=11?2:3,9:i=>+(i>=2),10:i=>i==1?0:i==2?1:i<7?2:i<11?3:4,11:i=>i==1||i==11?0:i==2||i==12?1:i>2&&i<20?2:3,12:i=>+(i%10!=1||i%100==11),13:i=>+(i!==0),14:i=>i==1?0:i==2?1:i==3?2:3,15:i=>i%10==1&&i%100!=11?0:i%10>=2&&(i%100<10||i%100>=20)?1:2,16:i=>i%10==1&&i%100!=11?0:i!==0?1:2,17:i=>i==1||i%10==1&&i%100!=11?0:1,18:i=>i==0?0:i==1?1:2,19:i=>i==1?0:i==0||i%100>1&&i%100<11?1:i%100>10&&i%100<20?2:3,20:i=>i==1?0:i==0||i%100>0&&i%100<20?1:2,21:i=>i%100==1?1:i%100==2?2:i%100==3||i%100==4?3:0,22:i=>i==1?0:i==2?1:(i<0||i>10)&&i%10==0?2:3};const xF=["v1","v2","v3"],TF=["v4"],gT={zero:0,one:1,two:2,few:3,many:4,other:5},EF=()=>{const i={};return yF.forEach(e=>{e.lngs.forEach(t=>{i[t]={numbers:e.nr,plurals:SF[e.fc]}})}),i};class wF{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=e,this.options=t,this.logger=Pn.create("pluralResolver"),(!this.options.compatibilityJSON||TF.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=EF(),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi()){const n=Cc(e==="dev"?"en":e),r=t.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:n,type:r});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let o;try{o=new Intl.PluralRules(n,{type:r})}catch{if(!e.match(/-|_/))return;const l=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(l,t)}return this.pluralRulesCache[s]=o,o}return this.rules[e]||this.rules[this.languageUtils.getLanguagePartFromCode(e)]}needsPlural(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=this.getRule(e,t);return this.shouldUseIntlApi()?n&&n.resolvedOptions().pluralCategories.length>1:n&&n.numbers.length>1}getPluralFormsOfKey(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(e,n).map(r=>`${t}${r}`)}getSuffixes(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=this.getRule(e,t);return n?this.shouldUseIntlApi()?n.resolvedOptions().pluralCategories.sort((r,s)=>gT[r]-gT[s]).map(r=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${r}`):n.numbers.map(r=>this.getSuffix(e,r,t)):[]}getSuffix(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=this.getRule(e,n);return r?this.shouldUseIntlApi()?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${r.select(t)}`:this.getSuffixRetroCompatible(r,t):(this.logger.warn(`no plural rule found for: ${e}`),"")}getSuffixRetroCompatible(e,t){const n=e.noAbs?e.plurals(t):e.plurals(Math.abs(t));let r=e.numbers[n];this.options.simplifyPluralSuffix&&e.numbers.length===2&&e.numbers[0]===1&&(r===2?r="plural":r===1&&(r=""));const s=()=>this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString();return this.options.compatibilityJSON==="v1"?r===1?"":typeof r=="number"?`_plural_${r.toString()}`:s():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&e.numbers.length===2&&e.numbers[0]===1?s():this.options.prepend&&n.toString()?this.options.prepend+n.toString():n.toString()}shouldUseIntlApi(){return!xF.includes(this.options.compatibilityJSON)}}const mT=function(i,e,t){let n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=cF(i,e,t);return!s&&r&&Ne(t)&&(s=zf(i,t,n),s===void 0&&(s=zf(e,t,n))),s},Gf=i=>i.replace(/\$/g,"$$$$");class bF{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Pn.create("interpolator"),this.options=e,this.format=e.interpolation&&e.interpolation.format||(t=>t),this.init(e)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:s,prefixEscaped:o,suffix:a,suffixEscaped:l,formatSeparator:c,unescapeSuffix:u,unescapePrefix:d,nestingPrefix:h,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:g,nestingOptionsSeparator:m,maxReplaces:v,alwaysFormat:y}=e.interpolation;this.escape=t!==void 0?t:dF,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=s?_o(s):o||"{{",this.suffix=a?_o(a):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=u?"":d||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=h?_o(h):f||_o("$t("),this.nestingSuffix=p?_o(p):g||_o(")"),this.nestingOptionsSeparator=m||",",this.maxReplaces=v||1e3,this.alwaysFormat=y!==void 0?y:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(t,n)=>t&&t.source===n?(t.lastIndex=0,t):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(e,t,n,r){let s,o,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=f=>{if(f.indexOf(this.formatSeparator)<0){const v=mT(t,l,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(v,void 0,n,{...r,...t,interpolationkey:f}):v}const p=f.split(this.formatSeparator),g=p.shift().trim(),m=p.join(this.formatSeparator).trim();return this.format(mT(t,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),m,n,{...r,...t,interpolationkey:g})};this.resetRegExp();const u=r&&r.missingInterpolationHandler||this.options.missingInterpolationHandler,d=r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>Gf(f)},{regex:this.regexp,safeValue:f=>this.escapeValue?Gf(this.escape(f)):Gf(f)}].forEach(f=>{for(a=0;s=f.regex.exec(e);){const p=s[1].trim();if(o=c(p),o===void 0)if(typeof u=="function"){const m=u(e,s,r);o=Ne(m)?m:""}else if(r&&Object.prototype.hasOwnProperty.call(r,p))o="";else if(d){o=s[0];continue}else this.logger.warn(`missed to pass in variable ${p} for interpolating ${e}`),o="";else!Ne(o)&&!this.useRawValueToEscape&&(o=oT(o));const g=f.safeValue(o);if(e=e.replace(s[0],g),d?(f.regex.lastIndex+=o.length,f.regex.lastIndex-=s[0].length):f.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,s,o;const a=(l,c)=>{const u=this.nestingOptionsSeparator;if(l.indexOf(u)<0)return l;const d=l.split(new RegExp(`${u}[ ]*{`));let h=`{${d[1]}`;l=d[0],h=this.interpolate(h,o);const f=h.match(/'/g),p=h.match(/"/g);(f&&f.length%2===0&&!p||p.length%2!==0)&&(h=h.replace(/'/g,'"'));try{o=JSON.parse(h),c&&(o={...c,...o})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${u}${h}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,l};for(;r=this.nestingRegexp.exec(e);){let l=[];o={...n},o=o.replace&&!Ne(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;let c=!1;if(r[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(r[1])){const u=r[1].split(this.formatSeparator).map(d=>d.trim());r[1]=u.shift(),l=u,c=!0}if(s=t(a.call(this,r[1].trim(),o),o),s&&r[0]===e&&!Ne(s))return s;Ne(s)||(s=oT(s)),s||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),s=""),c&&(s=l.reduce((u,d)=>this.format(u,d,n.lng,{...n,interpolationkey:r[1].trim()}),s.trim())),e=e.replace(r[0],s),this.regexp.lastIndex=0}return e}}const _F=i=>{let e=i.toLowerCase().trim();const t={};if(i.indexOf("(")>-1){const n=i.split("(");e=n[0].toLowerCase().trim();const r=n[1].substring(0,n[1].length-1);e==="currency"&&r.indexOf(":")<0?t.currency||(t.currency=r.trim()):e==="relativetime"&&r.indexOf(":")<0?t.range||(t.range=r.trim()):r.split(";").forEach(o=>{if(o){const[a,...l]=o.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),u=a.trim();t[u]||(t[u]=c),c==="false"&&(t[u]=!1),c==="true"&&(t[u]=!0),isNaN(c)||(t[u]=parseInt(c,10))}})}return{formatName:e,formatOptions:t}},Ao=i=>{const e={};return(t,n,r)=>{let s=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(s={...s,[r.interpolationkey]:void 0});const o=n+JSON.stringify(s);let a=e[o];return a||(a=i(Cc(n),r),e[o]=a),a(t)}};class AF{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=Pn.create("formatter"),this.options=e,this.formats={number:Ao((t,n)=>{const r=new Intl.NumberFormat(t,{...n});return s=>r.format(s)}),currency:Ao((t,n)=>{const r=new Intl.NumberFormat(t,{...n,style:"currency"});return s=>r.format(s)}),datetime:Ao((t,n)=>{const r=new Intl.DateTimeFormat(t,{...n});return s=>r.format(s)}),relativetime:Ao((t,n)=>{const r=new Intl.RelativeTimeFormat(t,{...n});return s=>r.format(s,n.range||"day")}),list:Ao((t,n)=>{const r=new Intl.ListFormat(t,{...n});return s=>r.format(s)})},this.init(e)}init(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};this.formatSeparator=t.interpolation.formatSeparator||","}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Ao(t)}format(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const s=t.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(a=>a.indexOf(")")>-1)){const a=s.findIndex(l=>l.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,a)].join(this.formatSeparator)}return s.reduce((a,l)=>{const{formatName:c,formatOptions:u}=_F(l);if(this.formats[c]){let d=a;try{const h=r&&r.formatParams&&r.formatParams[r.interpolationkey]||{},f=h.locale||h.lng||r.locale||r.lng||n;d=this.formats[c](a,f,{...u,...r,...h})}catch(h){this.logger.warn(h)}return d}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const RF=(i,e)=>{i.pending[e]!==void 0&&(delete i.pending[e],i.pendingCount--)};class CF extends Ic{constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=Pn.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(n,r.backend,r)}queueLoad(e,t,n,r){const s={},o={},a={},l={};return e.forEach(c=>{let u=!0;t.forEach(d=>{const h=`${c}|${d}`;!n.reload&&this.store.hasResourceBundle(c,d)?this.state[h]=2:this.state[h]<0||(this.state[h]===1?o[h]===void 0&&(o[h]=!0):(this.state[h]=1,u=!1,o[h]===void 0&&(o[h]=!0),s[h]===void 0&&(s[h]=!0),l[d]===void 0&&(l[d]=!0)))}),u||(a[c]=!0)}),(Object.keys(s).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(s),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(l)}}loaded(e,t,n){const r=e.split("|"),s=r[0],o=r[1];t&&this.emit("failedLoading",s,o,t),!t&&n&&this.store.addResourceBundle(s,o,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);const a={};this.queue.forEach(l=>{lF(l.loaded,[s],o),RF(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{a[c]||(a[c]={});const u=l.loaded[c];u.length&&u.forEach(d=>{a[c][d]===void 0&&(a[c][d]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(l=>!l.done)}read(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,o=arguments.length>5?arguments[5]:void 0;if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:s,callback:o});return}this.readingCalls++;const a=(c,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const d=this.waitingReads.shift();this.read(d.lng,d.ns,d.fcName,d.tried,d.wait,d.callback)}if(c&&u&&r<this.maxRetries){setTimeout(()=>{this.read.call(this,e,t,n,r+1,s*2,o)},s);return}o(c,u)},l=this.backend[n].bind(this.backend);if(l.length===2){try{const c=l(e,t);c&&typeof c.then=="function"?c.then(u=>a(null,u)).catch(a):a(null,c)}catch(c){a(c)}return}return l(e,t,a)}prepareLoading(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();Ne(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Ne(t)&&(t=[t]);const s=this.queueLoad(e,t,n,r);if(!s.toLoad.length)return s.pending.length||r(),null;s.toLoad.forEach(o=>{this.loadOne(o)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const n=e.split("|"),r=n[0],s=n[1];this.read(r,s,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${t}loading namespace ${s} for language ${r} failed`,o),!o&&a&&this.logger.log(`${t}loaded namespace ${s} for language ${r}`,a),this.loaded(e,o,a)})}saveMissing(e,t,n,r,s){let o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if(this.backend&&this.backend.create){const l={...o,isUpdate:s},c=this.backend.create.bind(this.backend);if(c.length<6)try{let u;c.length===5?u=c(e,t,n,r,l):u=c(e,t,n,r),u&&typeof u.then=="function"?u.then(d=>a(null,d)).catch(a):a(null,u)}catch(u){a(u)}else c(e,t,n,r,a,l)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}}const vT=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:i=>{let e={};if(typeof i[1]=="object"&&(e=i[1]),Ne(i[1])&&(e.defaultValue=i[1]),Ne(i[2])&&(e.tDescription=i[2]),typeof i[2]=="object"||typeof i[3]=="object"){const t=i[3]||i[2];Object.keys(t).forEach(n=>{e[n]=t[n]})}return e},interpolation:{escapeValue:!0,format:i=>i,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),yT=i=>(Ne(i.ns)&&(i.ns=[i.ns]),Ne(i.fallbackLng)&&(i.fallbackLng=[i.fallbackLng]),Ne(i.fallbackNS)&&(i.fallbackNS=[i.fallbackNS]),i.supportedLngs&&i.supportedLngs.indexOf("cimode")<0&&(i.supportedLngs=i.supportedLngs.concat(["cimode"])),i),Lc=()=>{},IF=i=>{Object.getOwnPropertyNames(Object.getPrototypeOf(i)).forEach(t=>{typeof i[t]=="function"&&(i[t]=i[t].bind(i))})};class Va extends Ic{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;if(super(),this.options=yT(e),this.services={},this.logger=Pn,this.modules={external:[]},IF(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initImmediate)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof t=="function"&&(n=t,t={}),!t.defaultNS&&t.defaultNS!==!1&&t.ns&&(Ne(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=vT();this.options={...r,...this.options,...yT(t)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...r.interpolation,...this.options.interpolation}),t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator);const s=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?Pn.init(s(this.modules.logger),this.options):Pn.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:typeof Intl<"u"&&(u=AF);const d=new pT(this.options);this.store=new dT(this.options.resources,this.options);const h=this.services;h.logger=Pn,h.resourceStore=this.store,h.languageUtils=d,h.pluralResolver=new wF(d,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(h.formatter=s(u),h.formatter.init(h,this.options),this.options.interpolation.format=h.formatter.format.bind(h.formatter)),h.interpolator=new bF(this.options),h.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},h.backendConnector=new CF(s(this.modules.backend),h.resourceStore,h,this.options),h.backendConnector.on("*",function(f){for(var p=arguments.length,g=new Array(p>1?p-1:0),m=1;m<p;m++)g[m-1]=arguments[m];e.emit(f,...g)}),this.modules.languageDetector&&(h.languageDetector=s(this.modules.languageDetector),h.languageDetector.init&&h.languageDetector.init(h,this.options.detection,this.options)),this.modules.i18nFormat&&(h.i18nFormat=s(this.modules.i18nFormat),h.i18nFormat.init&&h.i18nFormat.init(this)),this.translator=new Pc(this.services,this.options),this.translator.on("*",function(f){for(var p=arguments.length,g=new Array(p>1?p-1:0),m=1;m<p;m++)g[m-1]=arguments[m];e.emit(f,...g)}),this.modules.external.forEach(f=>{f.init&&f.init(this)})}if(this.format=this.options.interpolation.format,n||(n=Lc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=function(){return e.store[u](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=function(){return e.store[u](...arguments),e}});const l=Ha(),c=()=>{const u=(d,h)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(h),n(d,h)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initImmediate?c():setTimeout(c,0),l}loadResources(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lc;const r=Ne(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(r&&r.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const s=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&s.indexOf(c)<0&&s.push(c)})};r?o(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>o(l)),this.options.preload&&this.options.preload.forEach(a=>o(a)),this.services.backendConnector.load(s,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(a)})}else n(null)}reloadResources(e,t,n){const r=Ha();return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),n||(n=Lc),this.services.backendConnector.reload(e,t,s=>{r.resolve(),n(s)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&hT.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1))for(let t=0;t<this.languages.length;t++){const n=this.languages[t];if(!(["cimode","dev"].indexOf(n)>-1)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}}changeLanguage(e,t){var n=this;this.isLanguageChangingTo=e;const r=Ha();this.emit("languageChanging",e);const s=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},o=(l,c)=>{c?(s(c),this.translator.changeLanguage(c),this.isLanguageChangingTo=void 0,this.emit("languageChanged",c),this.logger.log("languageChanged",c)):this.isLanguageChangingTo=void 0,r.resolve(function(){return n.t(...arguments)}),t&&t(l,function(){return n.t(...arguments)})},a=l=>{!e&&!l&&this.services.languageDetector&&(l=[]);const c=Ne(l)?l:this.services.languageUtils.getBestMatchFromCodes(l);c&&(this.language||s(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(c)),this.loadResources(c,u=>{o(u,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),r}getFixedT(e,t,n){var r=this;const s=function(o,a){let l;if(typeof a!="object"){for(var c=arguments.length,u=new Array(c>2?c-2:0),d=2;d<c;d++)u[d-2]=arguments[d];l=r.options.overloadTranslationOptionHandler([o,a].concat(u))}else l={...a};l.lng=l.lng||s.lng,l.lngs=l.lngs||s.lngs,l.ns=l.ns||s.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||n||s.keyPrefix);const h=r.options.keySeparator||".";let f;return l.keyPrefix&&Array.isArray(o)?f=o.map(p=>`${l.keyPrefix}${h}${p}`):f=l.keyPrefix?`${l.keyPrefix}${h}${o}`:o,r.t(f,l)};return Ne(e)?s.lng=e:s.lngs=e,s.ns=t,s.keyPrefix=n,s}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const o=(a,l)=>{const c=this.services.backendConnector.state[`${a}|${l}`];return c===-1||c===0||c===2};if(t.precheck){const a=t.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(n,e)&&(!r||o(s,e)))}loadNamespaces(e,t){const n=Ha();return this.options.ns?(Ne(e)&&(e=[e]),e.forEach(r=>{this.options.ns.indexOf(r)<0&&this.options.ns.push(r)}),this.loadResources(r=>{n.resolve(),t&&t(r)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){const n=Ha();Ne(e)&&(e=[e]);const r=this.options.preload||[],s=e.filter(o=>r.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return s.length?(this.options.preload=r.concat(s),this.loadResources(o=>{n.resolve(),t&&t(o)}),n):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!e)return"rtl";const t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=this.services&&this.services.languageUtils||new pT(vT());return t.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return new Va(e,t)}cloneInstance(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lc;const n=e.forkResourceStore;n&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},s=new Va(r);return(e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(a=>{s[a]=this[a]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},n&&(s.store=new dT(this.store.data,r),s.services.resourceStore=s.store),s.translator=new Pc(s.services,r),s.translator.on("*",function(a){for(var l=arguments.length,c=new Array(l>1?l-1:0),u=1;u<l;u++)c[u-1]=arguments[u];s.emit(a,...c)}),s.init(r,t),s.translator.options=r,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Ot=Va.createInstance();Ot.createInstance=Va.createInstance,Ot.createInstance,Ot.dir,Ot.init,Ot.loadResources,Ot.reloadResources,Ot.use,Ot.changeLanguage,Ot.getFixedT,Ot.t,Ot.exists,Ot.setDefaultNamespace,Ot.hasLoadedNamespace,Ot.loadNamespaces,Ot.loadLanguages;const PF={en:Qx,es:{commonClose:"Cerrar",commonNext:"Siguiente",commonOpen:"Abrir",commonPrevious:"Anterior",commonSearch:"Buscar",commonSearchPlaceholder:"Buscar...",commonShare:"Compartir",commonViewAll:"Ver todo",copyFailure:"Fallido",copySuccess:"Copiado",contentSearchLoading:"Cargando...",contentSearchPlaceholder:"Buscar",contentSearchResultsNone:"Sin resultados",contentSearchResultsMore:"Más resultados",imageFullScreen:"Pantalla completa",imageResetZoom:"Restablecer zoom",imageRotateLeft:"Girar a la izquierda",imageRotateRight:"Girar a la derecha",imageZoomIn:"Acercar",imageZoomOut:"Alejar",informationPanelTabs:"Seleccionar",informationPanelTabsClose:"Visor",informationPanelTabsAbout:"Acerca de",informationPanelTabsAnnotations:"Anotaciones",informationPanelTabsSearch:"Buscar",informationPanelToggle:"Más información",shareCollectionJson:"Ver colección",shareCollectionCopy:"Copiar URL de la colección",shareManifestJson:"Ver manifiesto",shareManifestCopy:"Copiar URL del manifiesto",canvasAnimationPlay:"Reproducir",canvasAnimationPause:"Pausar",canvasAnimationPreviousFrame:"Fotograma anterior",canvasAnimationNextFrame:"Fotograma siguiente",canvasAnimationRepeat:"Repetir",canvasAnimationSpeed:"Velocidad"},fi:{commonClose:"Sulje",commonNext:"Seuraava",commonPrevious:"Edellinen",commonSearch:"Hae",commonSearchPlaceholder:"Hae...",commonShare:"Jaa",commonViewAll:"Näytä kaikki",copyFailure:"Kopiointi epäonnistui",copySuccess:"Kopioitu",contentSearchLoading:"Ladataan...",contentSearchPlaceholder:"Haku",contentSearchResultsNone:"Ei osumia",contentSearchResultsMore:"Lisää osumia",informationPanelTabs:"Valitse",informationPanelTabsClose:"Katselu",informationPanelTabsAbout:"Tiedot",informationPanelTabsAnnotations:"Annotaatiot",informationPanelTabsSearch:"Haku",informationPanelToggle:"Lisätiedot",shareCollectionJson:"Näytä kokoelma",shareCollectionCopy:"Kopioi kokoelman osoite",shareManifestJson:"Näytä manifesti",shareManifestCopy:"Kopioi manifestin osoite",canvasAnimationPlay:"Toista",canvasAnimationPause:"Keskeytä",canvasAnimationPreviousFrame:"Edellinen ruutu",canvasAnimationNextFrame:"Seuraava ruutu",canvasAnimationRepeat:"Toista uudelleen",canvasAnimationSpeed:"Nopeus"},fr:{commonClose:"Fermer",commonNext:"Suivant",commonOpen:"Ouvrir",commonPrevious:"Précédent",commonSearch:"Rechercher",commonSearchPlaceholder:"Rechercher…",commonShare:"Partager",commonViewAll:"Tout afficher",copyFailure:"Échec",copySuccess:"Copié",contentSearchLoading:"Chargement…",contentSearchPlaceholder:"Rechercher",contentSearchResultsNone:"Aucun résultat",contentSearchResultsMore:"Plus de résultats",imageFullScreen:"Plein écran",imageResetZoom:"Réinitialiser le zoom",imageRotateLeft:"Rotation à gauche",imageRotateRight:"Rotation à droite",imageZoomIn:"Zoom avant",imageZoomOut:"Zoom arrière",informationPanelTabs:"Sélectionner",informationPanelTabsClose:"Visionneuse",informationPanelTabsAbout:"À propos",informationPanelTabsAnnotations:"Annotations",informationPanelTabsSearch:"Recherche",informationPanelToggle:"Plus d’informations",shareCollectionJson:"Afficher la collection",shareCollectionCopy:"Copier l’URL de la collection",shareManifestJson:"Afficher le manifeste",shareManifestCopy:"Copier l’URL du manifeste",canvasAnimationPlay:"Lire",canvasAnimationPause:"Pause",canvasAnimationPreviousFrame:"Image précédente",canvasAnimationNextFrame:"Image suivante",canvasAnimationRepeat:"Répéter",canvasAnimationSpeed:"Vitesse"},nb:{commonClose:"Lukk",commonNext:"Neste",commonPrevious:"Forrige",commonSearch:"Søk",commonSearchPlaceholder:"Søk...",commonShare:"Del",commonViewAll:"Se alle",copyFailure:"Feilet",copySuccess:"Kopiert",contentSearchLoading:"Laster inn...",contentSearchPlaceholder:"Søk",contentSearchResultsNone:"Ingen resultat",contentSearchResultsMore:"Flere resultat",informationPanelTabs:"Velg",informationPanelTabsClose:"Viewer",informationPanelTabsAbout:"Om",informationPanelTabsAnnotations:"Annoteringer",informationPanelTabsSearch:"Søk",informationPanelToggle:"Mer informasjon",shareCollectionJson:"Se samlingen",shareCollectionCopy:"Kopiér samlingens URL",shareManifestJson:"Se manifestet",shareManifestCopy:"Kopiér manifestets URL",canvasAnimationPlay:"Spill av",canvasAnimationPause:"Pause",canvasAnimationPreviousFrame:"Forrige bilde",canvasAnimationNextFrame:"Neste bilde",canvasAnimationRepeat:"Gjenta",canvasAnimationSpeed:"Hastighet"},nn:{commonClose:"Lukk",commonNext:"Neste",commonPrevious:"Førre",commonSearch:"Søk",commonSearchPlaceholder:"Søk...",commonShare:"Del",commonViewAll:"Sjå alle",copyFailure:"Feila",copySuccess:"Kopiert",contentSearchLoading:"Laster inn...",contentSearchPlaceholder:"Søk",contentSearchResultsNone:"Ingen resultat",contentSearchResultsMore:"Fleire resultat",informationPanelTabs:"Vel",informationPanelTabsClose:"Viewer",informationPanelTabsAbout:"Om",informationPanelTabsAnnotations:"Annoteringa",informationPanelTabsSearch:"Søk",informationPanelToggle:"Meir informasjon",shareCollectionJson:"Sjå samlinga",shareCollectionCopy:"Kopiér samlingas URL",shareManifestJson:"Sjå manifestet",shareManifestCopy:"Kopiér manifestets URL",canvasAnimationPlay:"Spel av",canvasAnimationPause:"Pause",canvasAnimationPreviousFrame:"Førre bilete",canvasAnimationNextFrame:"Neste bilete",canvasAnimationRepeat:"Gjenta",canvasAnimationSpeed:"Hastigheit"},no:{commonClose:"Lukk",commonNext:"Neste",commonPrevious:"Forrige",commonSearch:"Søk",commonSearchPlaceholder:"Søk...",commonShare:"Del",commonViewAll:"Se alle",copyFailure:"Feilet",copySuccess:"Kopiert",contentSearchLoading:"Laster inn...",contentSearchPlaceholder:"Søk",contentSearchResultsNone:"Ingen resultat",contentSearchResultsMore:"Flere resultat",informationPanelTabs:"Velg",informationPanelTabsClose:"Viewer",informationPanelTabsAbout:"Om",informationPanelTabsAnnotations:"Annoteringer",informationPanelTabsSearch:"Søk",informationPanelToggle:"Mer informasjon",shareCollectionJson:"Se samlingen",shareCollectionCopy:"Kopiér samlingens URL",shareManifestJson:"Se manifestet",shareManifestCopy:"Kopiér manifestets URL",canvasAnimationPlay:"Spill av",canvasAnimationPause:"Pause",canvasAnimationPreviousFrame:"Forrige bilde",canvasAnimationNextFrame:"Neste bilde",canvasAnimationRepeat:"Gjenta",canvasAnimationSpeed:"Hastighet"},pt:{canvasAnimationPlay:"Reproduzir",canvasAnimationPause:"Pausar",canvasAnimationPreviousFrame:"Fotograma anterior",canvasAnimationNextFrame:"Próximo fotograma",canvasAnimationRepeat:"Repetir",canvasAnimationSpeed:"Velocidade"}},kc="clover",LF=Object.fromEntries(Object.entries(PF).map(([i,e])=>[i,{[kc]:e}])),Ga={defaultNS:kc,fallbackLng:"en",ns:[kc],resources:{...LF}},kF=(i,e)=>({...i||{},...e||{}});let ST=!1;function DF(i){if(i){for(const[e,t]of Object.entries(i))if(t)for(const[n,r]of Object.entries(t))r&&Ot.addResourceBundle(e,n,r,!0,!0)}}function OF(i={}){if(ST)DF(i.resources),i.lng&&Ot.changeLanguage(i.lng),i.fallbackLng&&(Ot.options.fallbackLng=i.fallbackLng);else{const e=kF(Ga.resources,i.resources);Ot.use(sT).use(UM).init({...Ga,...i,resources:e,ns:i.ns??Ga.ns,defaultNS:i.defaultNS??Ga.defaultNS,fallbackLng:i.fallbackLng??Ga.fallbackLng}),ST=!0}return Ot}OF();const MF=Qx;function FF(i){return MF[i]??i}function dn(i=kc){const e=GM(i),{t}=e,n=Ce((r,s)=>{const o=t(r,s);return typeof o!="string"||o===r?FF(r):o},[t]);return{...e,t:n}}const NF=()=>T("path",{strokeLinecap:"round",strokeMiterlimit:"10",strokeWidth:"45",d:"M256 112v288M400 256H112"}),BF=()=>T("path",{strokeLinecap:"round",strokeMiterlimit:"10",strokeWidth:"45",d:"M400 256H112"}),UF=()=>T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32",d:"M432 320v112H320M421.8 421.77L304 304M80 192V80h112M90.2 90.23L208 208M320 80h112v112M421.77 90.2L304 208M192 432H80V320M90.23 421.8L208 304"}),$F=()=>T("path",{d:"M448 440a16 16 0 01-12.61-6.15c-22.86-29.27-44.07-51.86-73.32-67C335 352.88 301 345.59 256 344.23V424a16 16 0 01-27 11.57l-176-168a16 16 0 010-23.14l176-168A16 16 0 01256 88v80.36c74.14 3.41 129.38 30.91 164.35 81.87C449.32 292.44 464 350.9 464 424a16 16 0 01-16 16z"}),xT=()=>T(Ee,{children:[T("path",{fill:"none",strokeLinecap:"round",strokeMiterlimit:"10",strokeWidth:"45",d:"M400 148l-21.12-24.57A191.43 191.43 0 00240 64C134 64 48 150 48 256s86 192 192 192a192.09 192.09 0 00181.07-128"}),T("path",{d:"M464 97.42V208a16 16 0 01-16 16H337.42c-14.26 0-21.4-17.23-11.32-27.31L436.69 86.1C446.77 76 464 83.16 464 97.42z"})]}),HF=({_cloverViewerHasPlaceholder:i,config:e})=>{const{t}=dn(),n=gt(),{activeCanvas:r,plugins:s,vault:o,openSeadragonViewer:a}=n,l=o.get({id:r,type:"Canvas"});function c(){return s.filter(u=>{var d;return(d=u.imageViewer)==null?void 0:d.controls}).map((u,d)=>{var f,p,g,m;const h=(p=(f=u.imageViewer)==null?void 0:f.controls)==null?void 0:p.component;return T(h,{...(m=(g=u==null?void 0:u.imageViewer)==null?void 0:g.controls)==null?void 0:m.componentProps,canvas:l,useViewerDispatch:Ti,useViewerState:gt},d)})}return ne(()=>{if(!a)return;const u=a.viewport.getRotation();a.addHandler("home",()=>{a.viewport.setRotation(u)})},[a]),T(CM,{"data-testid":"clover-iiif-image-openseadragon-controls",hasPlaceholder:i,children:[e.showZoomControl&&T(Ee,{children:[T(Eo,{id:e.zoomInButton,label:t("imageZoomIn"),children:T(NF,{})}),T(Eo,{id:e.zoomOutButton,label:t("imageZoomOut"),children:T(BF,{})})]}),e.showFullPageControl&&T(Eo,{id:e.fullPageButton,label:t("imageFullScreen"),children:T(UF,{})}),e.showRotationControl&&T(Ee,{children:[T(Eo,{id:e.rotateRightButton,label:t("imageRotateRight"),children:T(xT,{})}),T(Eo,{id:e.rotateLeftButton,label:t("imageRotateLeft"),children:T(xT,{})})]}),e.showHomeControl&&T(Eo,{id:e.homeButton,label:t("imageResetZoom"),children:T($F,{})}),c()]})};async function TT(i,e=3,t=500){try{return await i()}catch(n){if(e<=0)throw n;return await new Promise(r=>setTimeout(r,t)),TT(i,e-1,t)}}const zF=i=>new Promise(e=>setTimeout(e,i)),ET=async(i,e,t=3,n=300)=>{for(let r=0;r<t;r++){const s=e?e-1:0,o=i.getItemAt(s);if(o)return o;await zF(n)}throw new Error("No base item found at index 0 after retries")},VF=({annotations:i,ariaLabel:e,config:t,uri:n,_cloverViewerHasPlaceholder:r,imageType:s,openSeadragonCallback:o})=>{const[a,l]=se([]),[c,u]=se([]),[d,h]=se(),[f,p]=se([]),g=Ti(),m=ge(!1),v=ge(!0),y="clover-iiif-image-openseadragon-annotation",S=t.gestureSettingsMouse.scrollToZoom===!1;ne(()=>(m.current||(m.current=!0,d||h(Ia(t))),()=>d==null?void 0:d.destroy()),[]),ne(()=>{x()},[d,o]),ne(()=>{d&&JSON.stringify(n)!==JSON.stringify(c)&&(d.forceRedraw(),S&&d.addHandler("canvas-scroll",function(E){E.preventDefault=!1}),u(n))},[S,d,c,n]),ne(()=>{if(!c.length||!d)return;const E=[];d.world.getItemCount()===1&&c.length===1?E.push(d.world.getItemAt(0)):d.close();const b=c.length;let I=0;const D=()=>{if(I++,!v.current||I<b)return;v.current=!1;const k=3;let N=0;const B=()=>{if(N>=k)return;const K=d==null?void 0:d.world.getHomeBounds();K&&(d==null||d.viewport.fitBounds(K,!0)),N++,setTimeout(B,50)};B()};(async()=>{switch(s){case"simpleImage":let k=1,N=0;for(let B=0;B<c.length;B++){const K=c[B];if(i){const q=new Image;q.src=K,await q.decode(),p(H=>[...H,{width:q==null?void 0:q.width,height:q==null?void 0:q.height}])}try{if(B!==0){const H=(await ET(d.world,B)).getBounds();N=H.x+H.width,k=H.height}d.addSimpleImage({url:K,x:N,y:0,height:k,success:()=>{E.forEach(q=>d.world.removeItem(q)),D(),l(q=>[...q,K]),typeof g=="function"&&g({type:"updateOSDImageLoaded",OSDImageLoaded:!0})}})}catch(q){console.error(`Failed to load image at ${K}:`,q)}}break;case"tiledImage":{let B=1,K=0;for(let q=0;q<c.length;q++){const H=c[q];try{const X=await TT(()=>AO(H),3,1e3);if(!X)throw new Error(`No tile source for ${H}`);if(q!==0){const U=(await ET(d.world,q)).getBounds();K=U.x+U.width,B=U.height}d.addTiledImage({tileSource:X,x:K,y:0,height:B,success:()=>{E.forEach(F=>d.world.removeItem(F)),D(),l(F=>[...F,H]),typeof g=="function"&&g({type:"updateOSDImageLoaded",OSDImageLoaded:!0})}})}catch(X){console.error(`Failed to load tile at ${H}:`,X)}}break}default:console.warn(`Unsupported imageType: "${s}"`);break}})().catch(k=>console.error("Error drawing tiles",k))},[c,s,d]),ne(()=>{a.length&&(d==null||d.addHandler("canvas-click",E=>{const C=d==null?void 0:d.getOverlayById(E.originalTarget.id);if(C){const b=C==null?void 0:C.getBounds(d.viewport);return b.x-=.1,b.y-=.1,b.width+=.2,b.height+=.2,d==null||d.viewport.fitBounds(b,!1),E.preventDefaultAction=!0}}))},[a]),ne(()=>{function E(C,b,I){let D=C*I;if(b===0)return D;for(;b>0;){const P=d==null?void 0:d.world.getItemAt(b-1);if(P){const k=P.getBounds().width;D+=k,b--}else break}return D}i&&(d==null||d.clearOverlays(),i.forEach(C=>{var K,q,H,X;const{annotation:b,targetIndex:I}=C,D=((q=(K=d==null?void 0:d.viewport)==null?void 0:K.getBounds())==null?void 0:q.width)||1,P=d==null?void 0:d.world.getItemAt(I),k=P?(P==null?void 0:P.getBounds().width)/(P==null?void 0:P.getContentSize().x):((H=f[I])==null?void 0:H.width)/D,N=Ny(b==null?void 0:b.target),B=b!=null&&b.body?(X=b==null?void 0:b.body[0])==null?void 0:X.value:void 0;if(N!=null&&N.rect){const{x:F,y:U,w:j,h:V}=N==null?void 0:N.rect,Z=E(F,I,k),Q=new Ia.Rect(Z,U*k,j*k,V*k),le=document.createElement("button");if(le.classList.add(y),le.id=b.id,le.setAttribute("tabindex","0"),le.setAttribute("role","button"),le.setAttribute("data-active","true"),le.setAttribute("tabindex","0"),le.setAttribute("role","button"),le.setAttribute("data-active","false"),B){le.setAttribute("aria-label",B);const re=document.createElement("label");re.innerHTML=B,le.appendChild(re)}le.addEventListener("mousedown",re=>{re.stopPropagation(),re.preventDefault()}),le.addEventListener("touchstart",re=>{re.stopPropagation(),re.preventDefault()}),le.addEventListener("click",re=>{re.stopPropagation(),re.preventDefault()}),le.addEventListener("keydown",re=>{if(re.key==="Enter"){re.stopPropagation(),re.preventDefault();const ye=new Ia.Rect(Q.x-.1,Q.y-.1,Q.width+.2,Q.height+.2);d==null||d.viewport.fitBounds(ye,!1)}}),le.addEventListener("focus",()=>{le.setAttribute("data-active","true")}),le.addEventListener("mouseover",()=>{le.setAttribute("data-active","true")}),le.addEventListener("mouseout",()=>{le.removeAttribute("data-active")}),le.addEventListener("blur",()=>{le.removeAttribute("data-active")}),d==null||d.addOverlay(le,Q,Ia.Placement.CENTER)}}),x())},[a,i]);function x(){d&&(o==null||o(d))}return T(yM,{className:"clover-iiif-image-openseadragon","data-testid":"clover-iiif-image-openseadragon","data-openseadragon-instance":t.id,hasNavigator:t.showNavigator,children:[T(HF,{_cloverViewerHasPlaceholder:r,config:t}),t.showNavigator&&T(Mf,{id:t.navigatorId,"data-testid":"clover-iiif-image-openseadragon-navigator"}),T(vM,{id:t.id,"data-testid":"clover-iiif-image-openseadragon-viewport",role:"img",...e&&{"aria-label":e}})]})};function GF(i){return{id:`openseadragon-${i}`,navigatorId:`openseadragon-navigator-${i}`,loadTilesWithAjax:!0,fullPageButton:`fullPage-${i}`,homeButton:`reset-${i}`,rotateLeftButton:`rotateLeft-${i}`,rotateRightButton:`rotateRight-${i}`,zoomInButton:`zoomIn-${i}`,zoomOutButton:`zoomOut-${i}`,showNavigator:!0,showFullPageControl:!0,showHomeControl:!0,showRotationControl:!0,showZoomControl:!0,navigatorBorderColor:"transparent",gestureSettingsMouse:{clickToZoom:!0,dblClickToZoom:!0,pinchToZoom:!0,scrollToZoom:!1},preserveViewport:!0}}const wT=(i,e="none")=>{if(!i)return null;if(typeof i=="string")return[i];if(!i[e]){const t=Object.getOwnPropertyNames(i);if(t.length>0)return i[t[0]]}return!i[e]||!Array.isArray(i[e])?null:i[e]},Di=(i,e="none",t=", ")=>{const n=wT(i,e);return Array.isArray(n)?n.join(`${t}`):n},bT=({_cloverViewerHasPlaceholder:i=!1,annotations:e,body:t,instanceId:n,isTiledImage:r=!1,label:s,src:o="",openSeadragonCallback:a,openSeadragonConfig:l={}})=>{const c=n??To(),u=typeof s=="string"?s:Di(s),d={...GF(c),...l},h=Array.isArray(t)?t:t?[t]:[],f=Array.isArray(o)?o:o?[o]:[];let p=[],g=Yi.SimpleImage;if(h.length){const v=h.map(OO);p=v.map(y=>y.uri).filter(Boolean),g=v.some(y=>y.imageType===Yi.TiledImage)?Yi.TiledImage:Yi.SimpleImage}else if(f.length){const v=f.map(y=>MO(y,r));p=v.map(y=>y.uri).filter(Boolean),g=v.some(y=>y.imageType===Yi.TiledImage)?Yi.TiledImage:Yi.SimpleImage}return p.length?T(If,{FallbackComponent:Of,children:T(VF,{_cloverViewerHasPlaceholder:i,annotations:e,ariaLabel:u,config:d,imageType:g,uri:p,openSeadragonCallback:v=>{a==null||a(v)}},c)}):null};function _T(i,e,t,n){function r(){const o=Reflect.construct(HTMLElement,[],r);return o._vdomComponent=i,o._shadowEnabled=n&&n.shadow,o._root=o._shadowEnabled?o.attachShadow({mode:"open"}):o,n.onConstruct&&n.onConstruct(o),o.ready=!1,o.whenReady=a=>{o.ready?a():o.addEventListener("ready",a)},o}r.prototype=Object.create(HTMLElement.prototype),r.prototype.constructor=r,r.prototype.connectedCallback=jF,r.prototype.attributeChangedCallback=KF,r.prototype.disconnectedCallback=qF,t=t||i.observedAttributes||Object.keys(i.propTypes||{}),r.observedAttributes=t,t.forEach(o=>{Object.defineProperty(r.prototype,o,{get(){return this._vdom?this._vdom.props[o]:(this._props||(this._props={}),this._props[o])},set(a){this._vdom?(this._props[o]=a,this.attributeChangedCallback(o,null,a)):(this._props||(this._props={}),this._props[o]=a,this._props[Wf(o)]=a);const l=typeof a;(a==null||l==="string"||l==="boolean"||l==="number")&&this.setAttribute(o,a)}})}),n.beforeCreate&&n.beforeCreate(r);const s=e||i.tagName||i.displayName||i.name;if(!customElements.get(s))return customElements.define(e||i.tagName||i.displayName||i.name,r)}function WF(i){this.getChildContext=()=>i.context;const{context:e,children:t,...n}=i;return $h(t,n)}function jF(){const i=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(i);const e=i.detail.context;this._vdom=Ve(WF,{...this._props,context:e},RT(this,this._vdomComponent,this._shadowEnabled)),(this.hasAttribute("hydrate")?Uh:Pr)(this._vdom,this._root),this.ready||(this.ready=!0,this.dispatchEvent(new CustomEvent("ready",{detail:{},bubbles:!1,cancelable:!1})))}function Wf(i){return i.replace(/-(\w)/g,(e,t)=>t?t.toUpperCase():"")}function KF(i,e,t){if(!this._vdom)return;t=t??void 0;const n={};n[i]=t,n[Wf(i)]=t,this._vdom=$h(this._vdom,n),Pr(this._vdom,this._root)}function qF(){Pr(this._vdom=null,this._root)}function AT(i,e){const{shadow:t,addContextListener:n,removeContextListener:r,...s}=i,o=a=>{a?(this.ref=a,this._listener||(this._listener=l=>{l.stopPropagation(),l.detail.context=e},n(this._listener,this.ref))):r(this._listener,this.ref)};return!t&&!this._listener&&(this._listener=a=>{a.stopPropagation(),a.detail.context=e},n(this._listener)),Ve(t?"slot":Ee,{...s,ref:o})}function RT(i,e,t){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;let n=[],r={},s=0,o=i.attributes,a=i.childNodes;for(s=o.length;s--;)o[s].name!=="slot"&&(r[o[s].name]=o[s].value,r[Wf(o[s].name)]=o[s].value);for(s=a.length;s--;){const u=a[s],d=RT(u,null,t),h=u.slot;h?r[h]=Ve(AT,{name:h,shadow:t,addContextListener(f,p=u){p.addEventListener("_preact",f)},removeContextListener(f,p=u){p.removeEventListener("_preact",f)}},d):n[s]=d}const c=e?Ve(AT,{shadow:t,addContextListener(u,d=i){d.addEventListener("_preact",u)},removeContextListener(u,d=i){d.removeEventListener("_preact",u)}},n):n;return!t&&e&&(i.innerHTML=""),Ve(e||i.nodeName.toLowerCase(),r,c)}typeof window<"u"&&_T(i=>{const e=ge(),{"aria-label":t,"is-tiled-image":n,src:r}=i;return Ki(()=>{i.__registerPublicApi&&i.__registerPublicApi(s=>{e.current=s})},[i,i.__registerPublicApi]),T(bT,{label:t,isTiledImage:n===!0||n==="true",src:r})},"clover-image",["aria-label","src","is-tiled-image"],{shadow:!1,onConstruct:i=>{i._props={__registerPublicApi:e=>{Object.assign(i,e(i))}}}});function Ge(i,e,{checkForDefaultPrevented:t=!0}={}){return function(r){if(i==null||i(r),t===!1||!r.defaultPrevented)return e==null?void 0:e(r)}}function Ln(i,e=[]){let t=[];function n(s,o){const a=ln(o),l=t.length;t=[...t,o];const c=d=>{var v;const{scope:h,children:f,...p}=d,g=((v=h==null?void 0:h[i])==null?void 0:v[l])||a,m=Ct(()=>p,Object.values(p));return T(g.Provider,{value:m,children:f})};c.displayName=s+"Provider";function u(d,h){var g;const f=((g=h==null?void 0:h[i])==null?void 0:g[l])||a,p=Cn(f);if(p)return p;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${s}\``)}return[c,u]}const r=()=>{const s=t.map(o=>ln(o));return function(a){const l=(a==null?void 0:a[i])||s;return Ct(()=>({[`__scope${i}`]:{...a,[i]:l}}),[a,l])}};return r.scopeName=i,[n,YF(r,...e)]}function YF(...i){const e=i[0];if(i.length===1)return e;const t=()=>{const n=i.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(s){const o=n.reduce((a,{useScope:l,scopeName:c})=>{const d=l(s)[`__scope${c}`];return{...a,...d}},{});return Ct(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return t.scopeName=e.scopeName,t}var Yt=globalThis!=null&&globalThis.document?Ki:()=>{},XF=vc[" useInsertionEffect ".trim().toString()]||Yt;function Fr({prop:i,defaultProp:e,onChange:t=()=>{},caller:n}){const[r,s,o]=ZF({defaultProp:e,onChange:t}),a=i!==void 0,l=a?i:r;{const u=ge(i!==void 0);ne(()=>{const d=u.current;d!==a&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,n])}const c=Ce(u=>{var d;if(a){const h=QF(u)?u(i):u;h!==i&&((d=o.current)==null||d.call(o,h))}else s(u)},[a,i,s,o]);return[l,c]}function ZF({defaultProp:i,onChange:e}){const[t,n]=se(i),r=ge(t),s=ge(e);return XF(()=>{s.current=e},[e]),ne(()=>{var o;r.current!==t&&((o=s.current)==null||o.call(s,t),r.current=t)},[t,r]),[t,n,s]}function QF(i){return typeof i=="function"}function CT(i,e){if(typeof i=="function")return i(e);i!=null&&(i.current=e)}function IT(...i){return e=>{let t=!1;const n=i.map(r=>{const s=CT(r,e);return!t&&typeof s=="function"&&(t=!0),s});if(t)return()=>{for(let r=0;r<n.length;r++){const s=n[r];typeof s=="function"?s():CT(i[r],null)}}}}function ut(...i){return Ce(IT(...i),i)}var PT={exports:{}},Oi={};const JF=FL(vc);var LT={exports:{}},kT={};/**
|
|
22
|
+
* @license React
|
|
23
|
+
* scheduler.production.min.js
|
|
24
|
+
*
|
|
25
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
26
|
+
*
|
|
27
|
+
* This source code is licensed under the MIT license found in the
|
|
28
|
+
* LICENSE file in the root directory of this source tree.
|
|
29
|
+
*/(function(i){function e(F,U){var j=F.length;F.push(U);e:for(;0<j;){var V=j-1>>>1,Z=F[V];if(0<r(Z,U))F[V]=U,F[j]=Z,j=V;else break e}}function t(F){return F.length===0?null:F[0]}function n(F){if(F.length===0)return null;var U=F[0],j=F.pop();if(j!==U){F[0]=j;e:for(var V=0,Z=F.length,Q=Z>>>1;V<Q;){var le=2*(V+1)-1,re=F[le],ye=le+1,de=F[ye];if(0>r(re,j))ye<Z&&0>r(de,re)?(F[V]=de,F[ye]=j,V=ye):(F[V]=re,F[le]=j,V=le);else if(ye<Z&&0>r(de,j))F[V]=de,F[ye]=j,V=ye;else break e}}return U}function r(F,U){var j=F.sortIndex-U.sortIndex;return j!==0?j:F.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;i.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();i.unstable_now=function(){return o.now()-a}}var l=[],c=[],u=1,d=null,h=3,f=!1,p=!1,g=!1,m=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function S(F){for(var U=t(c);U!==null;){if(U.callback===null)n(c);else if(U.startTime<=F)n(c),U.sortIndex=U.expirationTime,e(l,U);else break;U=t(c)}}function x(F){if(g=!1,S(F),!p)if(t(l)!==null)p=!0,H(E);else{var U=t(c);U!==null&&X(x,U.startTime-F)}}function E(F,U){p=!1,g&&(g=!1,v(I),I=-1),f=!0;var j=h;try{for(S(U),d=t(l);d!==null&&(!(d.expirationTime>U)||F&&!k());){var V=d.callback;if(typeof V=="function"){d.callback=null,h=d.priorityLevel;var Z=V(d.expirationTime<=U);U=i.unstable_now(),typeof Z=="function"?d.callback=Z:d===t(l)&&n(l),S(U)}else n(l);d=t(l)}if(d!==null)var Q=!0;else{var le=t(c);le!==null&&X(x,le.startTime-U),Q=!1}return Q}finally{d=null,h=j,f=!1}}var C=!1,b=null,I=-1,D=5,P=-1;function k(){return!(i.unstable_now()-P<D)}function N(){if(b!==null){var F=i.unstable_now();P=F;var U=!0;try{U=b(!0,F)}finally{U?B():(C=!1,b=null)}}else C=!1}var B;if(typeof y=="function")B=function(){y(N)};else if(typeof MessageChannel<"u"){var K=new MessageChannel,q=K.port2;K.port1.onmessage=N,B=function(){q.postMessage(null)}}else B=function(){m(N,0)};function H(F){b=F,C||(C=!0,B())}function X(F,U){I=m(function(){F(i.unstable_now())},U)}i.unstable_IdlePriority=5,i.unstable_ImmediatePriority=1,i.unstable_LowPriority=4,i.unstable_NormalPriority=3,i.unstable_Profiling=null,i.unstable_UserBlockingPriority=2,i.unstable_cancelCallback=function(F){F.callback=null},i.unstable_continueExecution=function(){p||f||(p=!0,H(E))},i.unstable_forceFrameRate=function(F){0>F||125<F?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):D=0<F?Math.floor(1e3/F):5},i.unstable_getCurrentPriorityLevel=function(){return h},i.unstable_getFirstCallbackNode=function(){return t(l)},i.unstable_next=function(F){switch(h){case 1:case 2:case 3:var U=3;break;default:U=h}var j=h;h=U;try{return F()}finally{h=j}},i.unstable_pauseExecution=function(){},i.unstable_requestPaint=function(){},i.unstable_runWithPriority=function(F,U){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var j=h;h=F;try{return U()}finally{h=j}},i.unstable_scheduleCallback=function(F,U,j){var V=i.unstable_now();switch(typeof j=="object"&&j!==null?(j=j.delay,j=typeof j=="number"&&0<j?V+j:V):j=V,F){case 1:var Z=-1;break;case 2:Z=250;break;case 5:Z=1073741823;break;case 4:Z=1e4;break;default:Z=5e3}return Z=j+Z,F={id:u++,callback:U,priorityLevel:F,startTime:j,expirationTime:Z,sortIndex:-1},j>V?(F.sortIndex=j,e(c,F),t(l)===null&&F===t(c)&&(g?(v(I),I=-1):g=!0,X(x,j-V))):(F.sortIndex=Z,e(l,F),p||f||(p=!0,H(E))),F},i.unstable_shouldYield=k,i.unstable_wrapCallback=function(F){var U=h;return function(){var j=h;h=U;try{return F.apply(this,arguments)}finally{h=j}}}})(kT),LT.exports=kT;var eN=LT.exports;/**
|
|
30
|
+
* @license React
|
|
31
|
+
* react-dom.production.min.js
|
|
32
|
+
*
|
|
33
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the MIT license found in the
|
|
36
|
+
* LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/var tN=JF,Mi=eN;function ae(i){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+i,t=1;t<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+i+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var DT=new Set,Wa={};function Os(i,e){Ro(i,e),Ro(i+"Capture",e)}function Ro(i,e){for(Wa[i]=e,i=0;i<e.length;i++)DT.add(e[i])}var lr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),jf=Object.prototype.hasOwnProperty,iN=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,OT={},MT={};function nN(i){return jf.call(MT,i)?!0:jf.call(OT,i)?!1:iN.test(i)?MT[i]=!0:(OT[i]=!0,!1)}function rN(i,e,t,n){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:t!==null?!t.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function sN(i,e,t,n){if(e===null||typeof e>"u"||rN(i,e,t,n))return!0;if(n)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function ci(i,e,t,n,r,s,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=r,this.mustUseProperty=t,this.propertyName=i,this.type=e,this.sanitizeURL=s,this.removeEmptyString=o}var Xt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){Xt[i]=new ci(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var e=i[0];Xt[e]=new ci(e,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){Xt[i]=new ci(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){Xt[i]=new ci(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){Xt[i]=new ci(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){Xt[i]=new ci(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){Xt[i]=new ci(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){Xt[i]=new ci(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){Xt[i]=new ci(i,5,!1,i.toLowerCase(),null,!1,!1)});var Kf=/[\-:]([a-z])/g;function qf(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var e=i.replace(Kf,qf);Xt[e]=new ci(e,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var e=i.replace(Kf,qf);Xt[e]=new ci(e,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var e=i.replace(Kf,qf);Xt[e]=new ci(e,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){Xt[i]=new ci(i,1,!1,i.toLowerCase(),null,!1,!1)}),Xt.xlinkHref=new ci("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){Xt[i]=new ci(i,1,!1,i.toLowerCase(),null,!0,!0)});function Yf(i,e,t,n){var r=Xt.hasOwnProperty(e)?Xt[e]:null;(r!==null?r.type!==0:n||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(sN(e,t,r,n)&&(t=null),n||r===null?nN(e)&&(t===null?i.removeAttribute(e):i.setAttribute(e,""+t)):r.mustUseProperty?i[r.propertyName]=t===null?r.type===3?!1:"":t:(e=r.attributeName,n=r.attributeNamespace,t===null?i.removeAttribute(e):(r=r.type,t=r===3||r===4&&t===!0?"":""+t,n?i.setAttributeNS(n,e,t):i.setAttribute(e,t))))}var cr=tN.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Dc=Symbol.for("react.element"),Co=Symbol.for("react.portal"),Io=Symbol.for("react.fragment"),Xf=Symbol.for("react.strict_mode"),Zf=Symbol.for("react.profiler"),FT=Symbol.for("react.provider"),NT=Symbol.for("react.context"),Qf=Symbol.for("react.forward_ref"),Jf=Symbol.for("react.suspense"),ep=Symbol.for("react.suspense_list"),tp=Symbol.for("react.memo"),Nr=Symbol.for("react.lazy"),BT=Symbol.for("react.offscreen"),UT=Symbol.iterator;function ja(i){return i===null||typeof i!="object"?null:(i=UT&&i[UT]||i["@@iterator"],typeof i=="function"?i:null)}var _t=Object.assign,ip;function Ka(i){if(ip===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);ip=e&&e[1]||""}return`
|
|
38
|
+
`+ip+i}var np=!1;function rp(i,e){if(!i||np)return"";np=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var n=c}Reflect.construct(i,[],e)}else{try{e.call()}catch(c){n=c}i.call(e.prototype)}else{try{throw Error()}catch(c){n=c}i()}}catch(c){if(c&&n&&typeof c.stack=="string"){for(var r=c.stack.split(`
|
|
39
|
+
`),s=n.stack.split(`
|
|
40
|
+
`),o=r.length-1,a=s.length-1;1<=o&&0<=a&&r[o]!==s[a];)a--;for(;1<=o&&0<=a;o--,a--)if(r[o]!==s[a]){if(o!==1||a!==1)do if(o--,a--,0>a||r[o]!==s[a]){var l=`
|
|
41
|
+
`+r[o].replace(" at new "," at ");return i.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",i.displayName)),l}while(1<=o&&0<=a);break}}}finally{np=!1,Error.prepareStackTrace=t}return(i=i?i.displayName||i.name:"")?Ka(i):""}function oN(i){switch(i.tag){case 5:return Ka(i.type);case 16:return Ka("Lazy");case 13:return Ka("Suspense");case 19:return Ka("SuspenseList");case 0:case 2:case 15:return i=rp(i.type,!1),i;case 11:return i=rp(i.type.render,!1),i;case 1:return i=rp(i.type,!0),i;default:return""}}function sp(i){if(i==null)return null;if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case Io:return"Fragment";case Co:return"Portal";case Zf:return"Profiler";case Xf:return"StrictMode";case Jf:return"Suspense";case ep:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case NT:return(i.displayName||"Context")+".Consumer";case FT:return(i._context.displayName||"Context")+".Provider";case Qf:var e=i.render;return i=i.displayName,i||(i=e.displayName||e.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case tp:return e=i.displayName||null,e!==null?e:sp(i.type)||"Memo";case Nr:e=i._payload,i=i._init;try{return sp(i(e))}catch{}}return null}function aN(i){var e=i.type;switch(i.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return i=e.render,i=i.displayName||i.name||"",e.displayName||(i!==""?"ForwardRef("+i+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return sp(e);case 8:return e===Xf?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function Br(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function $T(i){var e=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function lN(i){var e=$T(i)?"checked":"value",t=Object.getOwnPropertyDescriptor(i.constructor.prototype,e),n=""+i[e];if(!i.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var r=t.get,s=t.set;return Object.defineProperty(i,e,{configurable:!0,get:function(){return r.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(i,e,{enumerable:t.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){i._valueTracker=null,delete i[e]}}}}function Oc(i){i._valueTracker||(i._valueTracker=lN(i))}function HT(i){if(!i)return!1;var e=i._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return i&&(n=$T(i)?i.checked?"true":"false":i.value),i=n,i!==t?(e.setValue(i),!0):!1}function Mc(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}function op(i,e){var t=e.checked;return _t({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??i._wrapperState.initialChecked})}function zT(i,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=Br(e.value!=null?e.value:t),i._wrapperState={initialChecked:n,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function VT(i,e){e=e.checked,e!=null&&Yf(i,"checked",e,!1)}function ap(i,e){VT(i,e);var t=Br(e.value),n=e.type;if(t!=null)n==="number"?(t===0&&i.value===""||i.value!=t)&&(i.value=""+t):i.value!==""+t&&(i.value=""+t);else if(n==="submit"||n==="reset"){i.removeAttribute("value");return}e.hasOwnProperty("value")?lp(i,e.type,t):e.hasOwnProperty("defaultValue")&&lp(i,e.type,Br(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(i.defaultChecked=!!e.defaultChecked)}function GT(i,e,t){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+i._wrapperState.initialValue,t||e===i.value||(i.value=e),i.defaultValue=e}t=i.name,t!==""&&(i.name=""),i.defaultChecked=!!i._wrapperState.initialChecked,t!==""&&(i.name=t)}function lp(i,e,t){(e!=="number"||Mc(i.ownerDocument)!==i)&&(t==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+t&&(i.defaultValue=""+t))}var qa=Array.isArray;function Po(i,e,t,n){if(i=i.options,e){e={};for(var r=0;r<t.length;r++)e["$"+t[r]]=!0;for(t=0;t<i.length;t++)r=e.hasOwnProperty("$"+i[t].value),i[t].selected!==r&&(i[t].selected=r),r&&n&&(i[t].defaultSelected=!0)}else{for(t=""+Br(t),e=null,r=0;r<i.length;r++){if(i[r].value===t){i[r].selected=!0,n&&(i[r].defaultSelected=!0);return}e!==null||i[r].disabled||(e=i[r])}e!==null&&(e.selected=!0)}}function cp(i,e){if(e.dangerouslySetInnerHTML!=null)throw Error(ae(91));return _t({},e,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function WT(i,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(ae(92));if(qa(t)){if(1<t.length)throw Error(ae(93));t=t[0]}e=t}e==null&&(e=""),t=e}i._wrapperState={initialValue:Br(t)}}function jT(i,e){var t=Br(e.value),n=Br(e.defaultValue);t!=null&&(t=""+t,t!==i.value&&(i.value=t),e.defaultValue==null&&i.defaultValue!==t&&(i.defaultValue=t)),n!=null&&(i.defaultValue=""+n)}function KT(i){var e=i.textContent;e===i._wrapperState.initialValue&&e!==""&&e!==null&&(i.value=e)}function qT(i){switch(i){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function up(i,e){return i==null||i==="http://www.w3.org/1999/xhtml"?qT(e):i==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var Fc,YT=function(i){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,n,r){MSApp.execUnsafeLocalFunction(function(){return i(e,t,n,r)})}:i}(function(i,e){if(i.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in i)i.innerHTML=e;else{for(Fc=Fc||document.createElement("div"),Fc.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=Fc.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;e.firstChild;)i.appendChild(e.firstChild)}});function Ya(i,e){if(e){var t=i.firstChild;if(t&&t===i.lastChild&&t.nodeType===3){t.nodeValue=e;return}}i.textContent=e}var Xa={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},cN=["Webkit","ms","Moz","O"];Object.keys(Xa).forEach(function(i){cN.forEach(function(e){e=e+i.charAt(0).toUpperCase()+i.substring(1),Xa[e]=Xa[i]})});function XT(i,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||Xa.hasOwnProperty(i)&&Xa[i]?(""+e).trim():e+"px"}function ZT(i,e){i=i.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,r=XT(t,e[t],n);t==="float"&&(t="cssFloat"),n?i.setProperty(t,r):i[t]=r}}var uN=_t({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function dp(i,e){if(e){if(uN[i]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ae(137,i));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ae(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ae(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ae(62))}}function hp(i,e){if(i.indexOf("-")===-1)return typeof e.is=="string";switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var fp=null;function pp(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var gp=null,Lo=null,ko=null;function QT(i){if(i=yl(i)){if(typeof gp!="function")throw Error(ae(280));var e=i.stateNode;e&&(e=su(e),gp(i.stateNode,i.type,e))}}function JT(i){Lo?ko?ko.push(i):ko=[i]:Lo=i}function eE(){if(Lo){var i=Lo,e=ko;if(ko=Lo=null,QT(i),e)for(i=0;i<e.length;i++)QT(e[i])}}function tE(i,e){return i(e)}function iE(){}var mp=!1;function nE(i,e,t){if(mp)return i(e,t);mp=!0;try{return tE(i,e,t)}finally{mp=!1,(Lo!==null||ko!==null)&&(iE(),eE())}}function Za(i,e){var t=i.stateNode;if(t===null)return null;var n=su(t);if(n===null)return null;t=n[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(i=i.type,n=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!n;break e;default:i=!1}if(i)return null;if(t&&typeof t!="function")throw Error(ae(231,e,typeof t));return t}var vp=!1;if(lr)try{var Qa={};Object.defineProperty(Qa,"passive",{get:function(){vp=!0}}),window.addEventListener("test",Qa,Qa),window.removeEventListener("test",Qa,Qa)}catch{vp=!1}function dN(i,e,t,n,r,s,o,a,l){var c=Array.prototype.slice.call(arguments,3);try{e.apply(t,c)}catch(u){this.onError(u)}}var Ja=!1,Nc=null,Bc=!1,yp=null,hN={onError:function(i){Ja=!0,Nc=i}};function fN(i,e,t,n,r,s,o,a,l){Ja=!1,Nc=null,dN.apply(hN,arguments)}function pN(i,e,t,n,r,s,o,a,l){if(fN.apply(this,arguments),Ja){if(Ja){var c=Nc;Ja=!1,Nc=null}else throw Error(ae(198));Bc||(Bc=!0,yp=c)}}function Ms(i){var e=i,t=i;if(i.alternate)for(;e.return;)e=e.return;else{i=e;do e=i,e.flags&4098&&(t=e.return),i=e.return;while(i)}return e.tag===3?t:null}function rE(i){if(i.tag===13){var e=i.memoizedState;if(e===null&&(i=i.alternate,i!==null&&(e=i.memoizedState)),e!==null)return e.dehydrated}return null}function sE(i){if(Ms(i)!==i)throw Error(ae(188))}function gN(i){var e=i.alternate;if(!e){if(e=Ms(i),e===null)throw Error(ae(188));return e!==i?null:i}for(var t=i,n=e;;){var r=t.return;if(r===null)break;var s=r.alternate;if(s===null){if(n=r.return,n!==null){t=n;continue}break}if(r.child===s.child){for(s=r.child;s;){if(s===t)return sE(r),i;if(s===n)return sE(r),e;s=s.sibling}throw Error(ae(188))}if(t.return!==n.return)t=r,n=s;else{for(var o=!1,a=r.child;a;){if(a===t){o=!0,t=r,n=s;break}if(a===n){o=!0,n=r,t=s;break}a=a.sibling}if(!o){for(a=s.child;a;){if(a===t){o=!0,t=s,n=r;break}if(a===n){o=!0,n=s,t=r;break}a=a.sibling}if(!o)throw Error(ae(189))}}if(t.alternate!==n)throw Error(ae(190))}if(t.tag!==3)throw Error(ae(188));return t.stateNode.current===t?i:e}function oE(i){return i=gN(i),i!==null?aE(i):null}function aE(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var e=aE(i);if(e!==null)return e;i=i.sibling}return null}var lE=Mi.unstable_scheduleCallback,cE=Mi.unstable_cancelCallback,mN=Mi.unstable_shouldYield,vN=Mi.unstable_requestPaint,Lt=Mi.unstable_now,yN=Mi.unstable_getCurrentPriorityLevel,Sp=Mi.unstable_ImmediatePriority,uE=Mi.unstable_UserBlockingPriority,Uc=Mi.unstable_NormalPriority,SN=Mi.unstable_LowPriority,dE=Mi.unstable_IdlePriority,$c=null,kn=null;function xN(i){if(kn&&typeof kn.onCommitFiberRoot=="function")try{kn.onCommitFiberRoot($c,i,void 0,(i.current.flags&128)===128)}catch{}}var hn=Math.clz32?Math.clz32:wN,TN=Math.log,EN=Math.LN2;function wN(i){return i>>>=0,i===0?32:31-(TN(i)/EN|0)|0}var Hc=64,zc=4194304;function el(i){switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return i&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return i}}function Vc(i,e){var t=i.pendingLanes;if(t===0)return 0;var n=0,r=i.suspendedLanes,s=i.pingedLanes,o=t&268435455;if(o!==0){var a=o&~r;a!==0?n=el(a):(s&=o,s!==0&&(n=el(s)))}else o=t&~r,o!==0?n=el(o):s!==0&&(n=el(s));if(n===0)return 0;if(e!==0&&e!==n&&!(e&r)&&(r=n&-n,s=e&-e,r>=s||r===16&&(s&4194240)!==0))return e;if(n&4&&(n|=t&16),e=i.entangledLanes,e!==0)for(i=i.entanglements,e&=n;0<e;)t=31-hn(e),r=1<<t,n|=i[t],e&=~r;return n}function bN(i,e){switch(i){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function _N(i,e){for(var t=i.suspendedLanes,n=i.pingedLanes,r=i.expirationTimes,s=i.pendingLanes;0<s;){var o=31-hn(s),a=1<<o,l=r[o];l===-1?(!(a&t)||a&n)&&(r[o]=bN(a,e)):l<=e&&(i.expiredLanes|=a),s&=~a}}function xp(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function hE(){var i=Hc;return Hc<<=1,!(Hc&4194240)&&(Hc=64),i}function Tp(i){for(var e=[],t=0;31>t;t++)e.push(i);return e}function tl(i,e,t){i.pendingLanes|=e,e!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,e=31-hn(e),i[e]=t}function AN(i,e){var t=i.pendingLanes&~e;i.pendingLanes=e,i.suspendedLanes=0,i.pingedLanes=0,i.expiredLanes&=e,i.mutableReadLanes&=e,i.entangledLanes&=e,e=i.entanglements;var n=i.eventTimes;for(i=i.expirationTimes;0<t;){var r=31-hn(t),s=1<<r;e[r]=0,n[r]=-1,i[r]=-1,t&=~s}}function Ep(i,e){var t=i.entangledLanes|=e;for(i=i.entanglements;t;){var n=31-hn(t),r=1<<n;r&e|i[n]&e&&(i[n]|=e),t&=~r}}var nt=0;function fE(i){return i&=-i,1<i?4<i?i&268435455?16:536870912:4:1}var pE,wp,gE,mE,vE,bp=!1,Gc=[],Ur=null,$r=null,Hr=null,il=new Map,nl=new Map,zr=[],RN="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function yE(i,e){switch(i){case"focusin":case"focusout":Ur=null;break;case"dragenter":case"dragleave":$r=null;break;case"mouseover":case"mouseout":Hr=null;break;case"pointerover":case"pointerout":il.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":nl.delete(e.pointerId)}}function rl(i,e,t,n,r,s){return i===null||i.nativeEvent!==s?(i={blockedOn:e,domEventName:t,eventSystemFlags:n,nativeEvent:s,targetContainers:[r]},e!==null&&(e=yl(e),e!==null&&wp(e)),i):(i.eventSystemFlags|=n,e=i.targetContainers,r!==null&&e.indexOf(r)===-1&&e.push(r),i)}function CN(i,e,t,n,r){switch(e){case"focusin":return Ur=rl(Ur,i,e,t,n,r),!0;case"dragenter":return $r=rl($r,i,e,t,n,r),!0;case"mouseover":return Hr=rl(Hr,i,e,t,n,r),!0;case"pointerover":var s=r.pointerId;return il.set(s,rl(il.get(s)||null,i,e,t,n,r)),!0;case"gotpointercapture":return s=r.pointerId,nl.set(s,rl(nl.get(s)||null,i,e,t,n,r)),!0}return!1}function SE(i){var e=Fs(i.target);if(e!==null){var t=Ms(e);if(t!==null){if(e=t.tag,e===13){if(e=rE(t),e!==null){i.blockedOn=e,vE(i.priority,function(){gE(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){i.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}i.blockedOn=null}function Wc(i){if(i.blockedOn!==null)return!1;for(var e=i.targetContainers;0<e.length;){var t=Ap(i.domEventName,i.eventSystemFlags,e[0],i.nativeEvent);if(t===null){t=i.nativeEvent;var n=new t.constructor(t.type,t);fp=n,t.target.dispatchEvent(n),fp=null}else return e=yl(t),e!==null&&wp(e),i.blockedOn=t,!1;e.shift()}return!0}function xE(i,e,t){Wc(i)&&t.delete(e)}function IN(){bp=!1,Ur!==null&&Wc(Ur)&&(Ur=null),$r!==null&&Wc($r)&&($r=null),Hr!==null&&Wc(Hr)&&(Hr=null),il.forEach(xE),nl.forEach(xE)}function sl(i,e){i.blockedOn===e&&(i.blockedOn=null,bp||(bp=!0,Mi.unstable_scheduleCallback(Mi.unstable_NormalPriority,IN)))}function ol(i){function e(r){return sl(r,i)}if(0<Gc.length){sl(Gc[0],i);for(var t=1;t<Gc.length;t++){var n=Gc[t];n.blockedOn===i&&(n.blockedOn=null)}}for(Ur!==null&&sl(Ur,i),$r!==null&&sl($r,i),Hr!==null&&sl(Hr,i),il.forEach(e),nl.forEach(e),t=0;t<zr.length;t++)n=zr[t],n.blockedOn===i&&(n.blockedOn=null);for(;0<zr.length&&(t=zr[0],t.blockedOn===null);)SE(t),t.blockedOn===null&&zr.shift()}var Do=cr.ReactCurrentBatchConfig,jc=!0;function PN(i,e,t,n){var r=nt,s=Do.transition;Do.transition=null;try{nt=1,_p(i,e,t,n)}finally{nt=r,Do.transition=s}}function LN(i,e,t,n){var r=nt,s=Do.transition;Do.transition=null;try{nt=4,_p(i,e,t,n)}finally{nt=r,Do.transition=s}}function _p(i,e,t,n){if(jc){var r=Ap(i,e,t,n);if(r===null)Vp(i,e,n,Kc,t),yE(i,n);else if(CN(r,i,e,t,n))n.stopPropagation();else if(yE(i,n),e&4&&-1<RN.indexOf(i)){for(;r!==null;){var s=yl(r);if(s!==null&&pE(s),s=Ap(i,e,t,n),s===null&&Vp(i,e,n,Kc,t),s===r)break;r=s}r!==null&&n.stopPropagation()}else Vp(i,e,n,null,t)}}var Kc=null;function Ap(i,e,t,n){if(Kc=null,i=pp(n),i=Fs(i),i!==null)if(e=Ms(i),e===null)i=null;else if(t=e.tag,t===13){if(i=rE(e),i!==null)return i;i=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;i=null}else e!==i&&(i=null);return Kc=i,null}function TE(i){switch(i){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(yN()){case Sp:return 1;case uE:return 4;case Uc:case SN:return 16;case dE:return 536870912;default:return 16}default:return 16}}var Vr=null,Rp=null,qc=null;function EE(){if(qc)return qc;var i,e=Rp,t=e.length,n,r="value"in Vr?Vr.value:Vr.textContent,s=r.length;for(i=0;i<t&&e[i]===r[i];i++);var o=t-i;for(n=1;n<=o&&e[t-n]===r[s-n];n++);return qc=r.slice(i,1<n?1-n:void 0)}function Yc(i){var e=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&e===13&&(i=13)):i=e,i===10&&(i=13),32<=i||i===13?i:0}function Xc(){return!0}function wE(){return!1}function Fi(i){function e(t,n,r,s,o){this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=s,this.target=o,this.currentTarget=null;for(var a in i)i.hasOwnProperty(a)&&(t=i[a],this[a]=t?t(s):s[a]);return this.isDefaultPrevented=(s.defaultPrevented!=null?s.defaultPrevented:s.returnValue===!1)?Xc:wE,this.isPropagationStopped=wE,this}return _t(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=Xc)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=Xc)},persist:function(){},isPersistent:Xc}),e}var Oo={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Cp=Fi(Oo),al=_t({},Oo,{view:0,detail:0}),kN=Fi(al),Ip,Pp,ll,Zc=_t({},al,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:kp,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==ll&&(ll&&i.type==="mousemove"?(Ip=i.screenX-ll.screenX,Pp=i.screenY-ll.screenY):Pp=Ip=0,ll=i),Ip)},movementY:function(i){return"movementY"in i?i.movementY:Pp}}),bE=Fi(Zc),DN=_t({},Zc,{dataTransfer:0}),ON=Fi(DN),MN=_t({},al,{relatedTarget:0}),Lp=Fi(MN),FN=_t({},Oo,{animationName:0,elapsedTime:0,pseudoElement:0}),NN=Fi(FN),BN=_t({},Oo,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),UN=Fi(BN),$N=_t({},Oo,{data:0}),_E=Fi($N),HN={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},zN={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},VN={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function GN(i){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(i):(i=VN[i])?!!e[i]:!1}function kp(){return GN}var WN=_t({},al,{key:function(i){if(i.key){var e=HN[i.key]||i.key;if(e!=="Unidentified")return e}return i.type==="keypress"?(i=Yc(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?zN[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:kp,charCode:function(i){return i.type==="keypress"?Yc(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?Yc(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),jN=Fi(WN),KN=_t({},Zc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),AE=Fi(KN),qN=_t({},al,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:kp}),YN=Fi(qN),XN=_t({},Oo,{propertyName:0,elapsedTime:0,pseudoElement:0}),ZN=Fi(XN),QN=_t({},Zc,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),JN=Fi(QN),e2=[9,13,27,32],Dp=lr&&"CompositionEvent"in window,cl=null;lr&&"documentMode"in document&&(cl=document.documentMode);var t2=lr&&"TextEvent"in window&&!cl,RE=lr&&(!Dp||cl&&8<cl&&11>=cl),CE=" ",IE=!1;function PE(i,e){switch(i){case"keyup":return e2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function LE(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var Mo=!1;function i2(i,e){switch(i){case"compositionend":return LE(e);case"keypress":return e.which!==32?null:(IE=!0,CE);case"textInput":return i=e.data,i===CE&&IE?null:i;default:return null}}function n2(i,e){if(Mo)return i==="compositionend"||!Dp&&PE(i,e)?(i=EE(),qc=Rp=Vr=null,Mo=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return RE&&e.locale!=="ko"?null:e.data;default:return null}}var r2={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function kE(i){var e=i&&i.nodeName&&i.nodeName.toLowerCase();return e==="input"?!!r2[i.type]:e==="textarea"}function DE(i,e,t,n){JT(n),e=iu(e,"onChange"),0<e.length&&(t=new Cp("onChange","change",null,t,n),i.push({event:t,listeners:e}))}var ul=null,dl=null;function s2(i){ZE(i,0)}function Qc(i){var e=$o(i);if(HT(e))return i}function o2(i,e){if(i==="change")return e}var OE=!1;if(lr){var Op;if(lr){var Mp="oninput"in document;if(!Mp){var ME=document.createElement("div");ME.setAttribute("oninput","return;"),Mp=typeof ME.oninput=="function"}Op=Mp}else Op=!1;OE=Op&&(!document.documentMode||9<document.documentMode)}function FE(){ul&&(ul.detachEvent("onpropertychange",NE),dl=ul=null)}function NE(i){if(i.propertyName==="value"&&Qc(dl)){var e=[];DE(e,dl,i,pp(i)),nE(s2,e)}}function a2(i,e,t){i==="focusin"?(FE(),ul=e,dl=t,ul.attachEvent("onpropertychange",NE)):i==="focusout"&&FE()}function l2(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return Qc(dl)}function c2(i,e){if(i==="click")return Qc(e)}function u2(i,e){if(i==="input"||i==="change")return Qc(e)}function d2(i,e){return i===e&&(i!==0||1/i===1/e)||i!==i&&e!==e}var fn=typeof Object.is=="function"?Object.is:d2;function hl(i,e){if(fn(i,e))return!0;if(typeof i!="object"||i===null||typeof e!="object"||e===null)return!1;var t=Object.keys(i),n=Object.keys(e);if(t.length!==n.length)return!1;for(n=0;n<t.length;n++){var r=t[n];if(!jf.call(e,r)||!fn(i[r],e[r]))return!1}return!0}function BE(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function UE(i,e){var t=BE(i);i=0;for(var n;t;){if(t.nodeType===3){if(n=i+t.textContent.length,i<=e&&n>=e)return{node:t,offset:e-i};i=n}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=BE(t)}}function $E(i,e){return i&&e?i===e?!0:i&&i.nodeType===3?!1:e&&e.nodeType===3?$E(i,e.parentNode):"contains"in i?i.contains(e):i.compareDocumentPosition?!!(i.compareDocumentPosition(e)&16):!1:!1}function HE(){for(var i=window,e=Mc();e instanceof i.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)i=e.contentWindow;else break;e=Mc(i.document)}return e}function Fp(i){var e=i&&i.nodeName&&i.nodeName.toLowerCase();return e&&(e==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||e==="textarea"||i.contentEditable==="true")}function h2(i){var e=HE(),t=i.focusedElem,n=i.selectionRange;if(e!==t&&t&&t.ownerDocument&&$E(t.ownerDocument.documentElement,t)){if(n!==null&&Fp(t)){if(e=n.start,i=n.end,i===void 0&&(i=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(i,t.value.length);else if(i=(e=t.ownerDocument||document)&&e.defaultView||window,i.getSelection){i=i.getSelection();var r=t.textContent.length,s=Math.min(n.start,r);n=n.end===void 0?s:Math.min(n.end,r),!i.extend&&s>n&&(r=n,n=s,s=r),r=UE(t,s);var o=UE(t,n);r&&o&&(i.rangeCount!==1||i.anchorNode!==r.node||i.anchorOffset!==r.offset||i.focusNode!==o.node||i.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(r.node,r.offset),i.removeAllRanges(),s>n?(i.addRange(e),i.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),i.addRange(e)))}}for(e=[],i=t;i=i.parentNode;)i.nodeType===1&&e.push({element:i,left:i.scrollLeft,top:i.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<e.length;t++)i=e[t],i.element.scrollLeft=i.left,i.element.scrollTop=i.top}}var f2=lr&&"documentMode"in document&&11>=document.documentMode,Fo=null,Np=null,fl=null,Bp=!1;function zE(i,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;Bp||Fo==null||Fo!==Mc(n)||(n=Fo,"selectionStart"in n&&Fp(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),fl&&hl(fl,n)||(fl=n,n=iu(Np,"onSelect"),0<n.length&&(e=new Cp("onSelect","select",null,e,t),i.push({event:e,listeners:n}),e.target=Fo)))}function Jc(i,e){var t={};return t[i.toLowerCase()]=e.toLowerCase(),t["Webkit"+i]="webkit"+e,t["Moz"+i]="moz"+e,t}var No={animationend:Jc("Animation","AnimationEnd"),animationiteration:Jc("Animation","AnimationIteration"),animationstart:Jc("Animation","AnimationStart"),transitionend:Jc("Transition","TransitionEnd")},Up={},VE={};lr&&(VE=document.createElement("div").style,"AnimationEvent"in window||(delete No.animationend.animation,delete No.animationiteration.animation,delete No.animationstart.animation),"TransitionEvent"in window||delete No.transitionend.transition);function eu(i){if(Up[i])return Up[i];if(!No[i])return i;var e=No[i],t;for(t in e)if(e.hasOwnProperty(t)&&t in VE)return Up[i]=e[t];return i}var GE=eu("animationend"),WE=eu("animationiteration"),jE=eu("animationstart"),KE=eu("transitionend"),qE=new Map,YE="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Gr(i,e){qE.set(i,e),Os(e,[i])}for(var $p=0;$p<YE.length;$p++){var Hp=YE[$p],p2=Hp.toLowerCase(),g2=Hp[0].toUpperCase()+Hp.slice(1);Gr(p2,"on"+g2)}Gr(GE,"onAnimationEnd"),Gr(WE,"onAnimationIteration"),Gr(jE,"onAnimationStart"),Gr("dblclick","onDoubleClick"),Gr("focusin","onFocus"),Gr("focusout","onBlur"),Gr(KE,"onTransitionEnd"),Ro("onMouseEnter",["mouseout","mouseover"]),Ro("onMouseLeave",["mouseout","mouseover"]),Ro("onPointerEnter",["pointerout","pointerover"]),Ro("onPointerLeave",["pointerout","pointerover"]),Os("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Os("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Os("onBeforeInput",["compositionend","keypress","textInput","paste"]),Os("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Os("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Os("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var pl="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),m2=new Set("cancel close invalid load scroll toggle".split(" ").concat(pl));function XE(i,e,t){var n=i.type||"unknown-event";i.currentTarget=t,pN(n,e,void 0,i),i.currentTarget=null}function ZE(i,e){e=(e&4)!==0;for(var t=0;t<i.length;t++){var n=i[t],r=n.event;n=n.listeners;e:{var s=void 0;if(e)for(var o=n.length-1;0<=o;o--){var a=n[o],l=a.instance,c=a.currentTarget;if(a=a.listener,l!==s&&r.isPropagationStopped())break e;XE(r,a,c),s=l}else for(o=0;o<n.length;o++){if(a=n[o],l=a.instance,c=a.currentTarget,a=a.listener,l!==s&&r.isPropagationStopped())break e;XE(r,a,c),s=l}}}if(Bc)throw i=yp,Bc=!1,yp=null,i}function mt(i,e){var t=e[Yp];t===void 0&&(t=e[Yp]=new Set);var n=i+"__bubble";t.has(n)||(QE(e,i,2,!1),t.add(n))}function zp(i,e,t){var n=0;e&&(n|=4),QE(t,i,n,e)}var tu="_reactListening"+Math.random().toString(36).slice(2);function gl(i){if(!i[tu]){i[tu]=!0,DT.forEach(function(t){t!=="selectionchange"&&(m2.has(t)||zp(t,!1,i),zp(t,!0,i))});var e=i.nodeType===9?i:i.ownerDocument;e===null||e[tu]||(e[tu]=!0,zp("selectionchange",!1,e))}}function QE(i,e,t,n){switch(TE(e)){case 1:var r=PN;break;case 4:r=LN;break;default:r=_p}t=r.bind(null,e,t,i),r=void 0,!vp||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(r=!0),n?r!==void 0?i.addEventListener(e,t,{capture:!0,passive:r}):i.addEventListener(e,t,!0):r!==void 0?i.addEventListener(e,t,{passive:r}):i.addEventListener(e,t,!1)}function Vp(i,e,t,n,r){var s=n;if(!(e&1)&&!(e&2)&&n!==null)e:for(;;){if(n===null)return;var o=n.tag;if(o===3||o===4){var a=n.stateNode.containerInfo;if(a===r||a.nodeType===8&&a.parentNode===r)break;if(o===4)for(o=n.return;o!==null;){var l=o.tag;if((l===3||l===4)&&(l=o.stateNode.containerInfo,l===r||l.nodeType===8&&l.parentNode===r))return;o=o.return}for(;a!==null;){if(o=Fs(a),o===null)return;if(l=o.tag,l===5||l===6){n=s=o;continue e}a=a.parentNode}}n=n.return}nE(function(){var c=s,u=pp(t),d=[];e:{var h=qE.get(i);if(h!==void 0){var f=Cp,p=i;switch(i){case"keypress":if(Yc(t)===0)break e;case"keydown":case"keyup":f=jN;break;case"focusin":p="focus",f=Lp;break;case"focusout":p="blur",f=Lp;break;case"beforeblur":case"afterblur":f=Lp;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":f=bE;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=ON;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=YN;break;case GE:case WE:case jE:f=NN;break;case KE:f=ZN;break;case"scroll":f=kN;break;case"wheel":f=JN;break;case"copy":case"cut":case"paste":f=UN;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=AE}var g=(e&4)!==0,m=!g&&i==="scroll",v=g?h!==null?h+"Capture":null:h;g=[];for(var y=c,S;y!==null;){S=y;var x=S.stateNode;if(S.tag===5&&x!==null&&(S=x,v!==null&&(x=Za(y,v),x!=null&&g.push(ml(y,x,S)))),m)break;y=y.return}0<g.length&&(h=new f(h,p,null,t,u),d.push({event:h,listeners:g}))}}if(!(e&7)){e:{if(h=i==="mouseover"||i==="pointerover",f=i==="mouseout"||i==="pointerout",h&&t!==fp&&(p=t.relatedTarget||t.fromElement)&&(Fs(p)||p[ur]))break e;if((f||h)&&(h=u.window===u?u:(h=u.ownerDocument)?h.defaultView||h.parentWindow:window,f?(p=t.relatedTarget||t.toElement,f=c,p=p?Fs(p):null,p!==null&&(m=Ms(p),p!==m||p.tag!==5&&p.tag!==6)&&(p=null)):(f=null,p=c),f!==p)){if(g=bE,x="onMouseLeave",v="onMouseEnter",y="mouse",(i==="pointerout"||i==="pointerover")&&(g=AE,x="onPointerLeave",v="onPointerEnter",y="pointer"),m=f==null?h:$o(f),S=p==null?h:$o(p),h=new g(x,y+"leave",f,t,u),h.target=m,h.relatedTarget=S,x=null,Fs(u)===c&&(g=new g(v,y+"enter",p,t,u),g.target=S,g.relatedTarget=m,x=g),m=x,f&&p)t:{for(g=f,v=p,y=0,S=g;S;S=Bo(S))y++;for(S=0,x=v;x;x=Bo(x))S++;for(;0<y-S;)g=Bo(g),y--;for(;0<S-y;)v=Bo(v),S--;for(;y--;){if(g===v||v!==null&&g===v.alternate)break t;g=Bo(g),v=Bo(v)}g=null}else g=null;f!==null&&JE(d,h,f,g,!1),p!==null&&m!==null&&JE(d,m,p,g,!0)}}e:{if(h=c?$o(c):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var E=o2;else if(kE(h))if(OE)E=u2;else{E=l2;var C=a2}else(f=h.nodeName)&&f.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(E=c2);if(E&&(E=E(i,c))){DE(d,E,t,u);break e}C&&C(i,h,c),i==="focusout"&&(C=h._wrapperState)&&C.controlled&&h.type==="number"&&lp(h,"number",h.value)}switch(C=c?$o(c):window,i){case"focusin":(kE(C)||C.contentEditable==="true")&&(Fo=C,Np=c,fl=null);break;case"focusout":fl=Np=Fo=null;break;case"mousedown":Bp=!0;break;case"contextmenu":case"mouseup":case"dragend":Bp=!1,zE(d,t,u);break;case"selectionchange":if(f2)break;case"keydown":case"keyup":zE(d,t,u)}var b;if(Dp)e:{switch(i){case"compositionstart":var I="onCompositionStart";break e;case"compositionend":I="onCompositionEnd";break e;case"compositionupdate":I="onCompositionUpdate";break e}I=void 0}else Mo?PE(i,t)&&(I="onCompositionEnd"):i==="keydown"&&t.keyCode===229&&(I="onCompositionStart");I&&(RE&&t.locale!=="ko"&&(Mo||I!=="onCompositionStart"?I==="onCompositionEnd"&&Mo&&(b=EE()):(Vr=u,Rp="value"in Vr?Vr.value:Vr.textContent,Mo=!0)),C=iu(c,I),0<C.length&&(I=new _E(I,i,null,t,u),d.push({event:I,listeners:C}),b?I.data=b:(b=LE(t),b!==null&&(I.data=b)))),(b=t2?i2(i,t):n2(i,t))&&(c=iu(c,"onBeforeInput"),0<c.length&&(u=new _E("onBeforeInput","beforeinput",null,t,u),d.push({event:u,listeners:c}),u.data=b))}ZE(d,e)})}function ml(i,e,t){return{instance:i,listener:e,currentTarget:t}}function iu(i,e){for(var t=e+"Capture",n=[];i!==null;){var r=i,s=r.stateNode;r.tag===5&&s!==null&&(r=s,s=Za(i,t),s!=null&&n.unshift(ml(i,s,r)),s=Za(i,e),s!=null&&n.push(ml(i,s,r))),i=i.return}return n}function Bo(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function JE(i,e,t,n,r){for(var s=e._reactName,o=[];t!==null&&t!==n;){var a=t,l=a.alternate,c=a.stateNode;if(l!==null&&l===n)break;a.tag===5&&c!==null&&(a=c,r?(l=Za(t,s),l!=null&&o.unshift(ml(t,l,a))):r||(l=Za(t,s),l!=null&&o.push(ml(t,l,a)))),t=t.return}o.length!==0&&i.push({event:e,listeners:o})}var v2=/\r\n?/g,y2=/\u0000|\uFFFD/g;function ew(i){return(typeof i=="string"?i:""+i).replace(v2,`
|
|
42
|
+
`).replace(y2,"")}function nu(i,e,t){if(e=ew(e),ew(i)!==e&&t)throw Error(ae(425))}function ru(){}var Gp=null,Wp=null;function jp(i,e){return i==="textarea"||i==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var Kp=typeof setTimeout=="function"?setTimeout:void 0,S2=typeof clearTimeout=="function"?clearTimeout:void 0,tw=typeof Promise=="function"?Promise:void 0,x2=typeof queueMicrotask=="function"?queueMicrotask:typeof tw<"u"?function(i){return tw.resolve(null).then(i).catch(T2)}:Kp;function T2(i){setTimeout(function(){throw i})}function qp(i,e){var t=e,n=0;do{var r=t.nextSibling;if(i.removeChild(t),r&&r.nodeType===8)if(t=r.data,t==="/$"){if(n===0){i.removeChild(r),ol(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=r}while(t);ol(e)}function Wr(i){for(;i!=null;i=i.nextSibling){var e=i.nodeType;if(e===1||e===3)break;if(e===8){if(e=i.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return i}function iw(i){i=i.previousSibling;for(var e=0;i;){if(i.nodeType===8){var t=i.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return i;e--}else t==="/$"&&e++}i=i.previousSibling}return null}var Uo=Math.random().toString(36).slice(2),Dn="__reactFiber$"+Uo,vl="__reactProps$"+Uo,ur="__reactContainer$"+Uo,Yp="__reactEvents$"+Uo,E2="__reactListeners$"+Uo,w2="__reactHandles$"+Uo;function Fs(i){var e=i[Dn];if(e)return e;for(var t=i.parentNode;t;){if(e=t[ur]||t[Dn]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(i=iw(i);i!==null;){if(t=i[Dn])return t;i=iw(i)}return e}i=t,t=i.parentNode}return null}function yl(i){return i=i[Dn]||i[ur],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function $o(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(ae(33))}function su(i){return i[vl]||null}var Xp=[],Ho=-1;function jr(i){return{current:i}}function vt(i){0>Ho||(i.current=Xp[Ho],Xp[Ho]=null,Ho--)}function ft(i,e){Ho++,Xp[Ho]=i.current,i.current=e}var Kr={},ei=jr(Kr),Ei=jr(!1),Ns=Kr;function zo(i,e){var t=i.type.contextTypes;if(!t)return Kr;var n=i.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var r={},s;for(s in t)r[s]=e[s];return n&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=e,i.__reactInternalMemoizedMaskedChildContext=r),r}function wi(i){return i=i.childContextTypes,i!=null}function ou(){vt(Ei),vt(ei)}function nw(i,e,t){if(ei.current!==Kr)throw Error(ae(168));ft(ei,e),ft(Ei,t)}function rw(i,e,t){var n=i.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return t;n=n.getChildContext();for(var r in n)if(!(r in e))throw Error(ae(108,aN(i)||"Unknown",r));return _t({},t,n)}function au(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||Kr,Ns=ei.current,ft(ei,i),ft(Ei,Ei.current),!0}function sw(i,e,t){var n=i.stateNode;if(!n)throw Error(ae(169));t?(i=rw(i,e,Ns),n.__reactInternalMemoizedMergedChildContext=i,vt(Ei),vt(ei),ft(ei,i)):vt(Ei),ft(Ei,t)}var dr=null,lu=!1,Zp=!1;function ow(i){dr===null?dr=[i]:dr.push(i)}function b2(i){lu=!0,ow(i)}function qr(){if(!Zp&&dr!==null){Zp=!0;var i=0,e=nt;try{var t=dr;for(nt=1;i<t.length;i++){var n=t[i];do n=n(!0);while(n!==null)}dr=null,lu=!1}catch(r){throw dr!==null&&(dr=dr.slice(i+1)),lE(Sp,qr),r}finally{nt=e,Zp=!1}}return null}var Vo=[],Go=0,cu=null,uu=0,Xi=[],Zi=0,Bs=null,hr=1,fr="";function Us(i,e){Vo[Go++]=uu,Vo[Go++]=cu,cu=i,uu=e}function aw(i,e,t){Xi[Zi++]=hr,Xi[Zi++]=fr,Xi[Zi++]=Bs,Bs=i;var n=hr;i=fr;var r=32-hn(n)-1;n&=~(1<<r),t+=1;var s=32-hn(e)+r;if(30<s){var o=r-r%5;s=(n&(1<<o)-1).toString(32),n>>=o,r-=o,hr=1<<32-hn(e)+r|t<<r|n,fr=s+i}else hr=1<<s|t<<r|n,fr=i}function Qp(i){i.return!==null&&(Us(i,1),aw(i,1,0))}function Jp(i){for(;i===cu;)cu=Vo[--Go],Vo[Go]=null,uu=Vo[--Go],Vo[Go]=null;for(;i===Bs;)Bs=Xi[--Zi],Xi[Zi]=null,fr=Xi[--Zi],Xi[Zi]=null,hr=Xi[--Zi],Xi[Zi]=null}var Ni=null,Bi=null,St=!1,pn=null;function lw(i,e){var t=tn(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=i,e=i.deletions,e===null?(i.deletions=[t],i.flags|=16):e.push(t)}function cw(i,e){switch(i.tag){case 5:var t=i.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(i.stateNode=e,Ni=i,Bi=Wr(e.firstChild),!0):!1;case 6:return e=i.pendingProps===""||e.nodeType!==3?null:e,e!==null?(i.stateNode=e,Ni=i,Bi=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=Bs!==null?{id:hr,overflow:fr}:null,i.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=tn(18,null,null,0),t.stateNode=e,t.return=i,i.child=t,Ni=i,Bi=null,!0):!1;default:return!1}}function eg(i){return(i.mode&1)!==0&&(i.flags&128)===0}function tg(i){if(St){var e=Bi;if(e){var t=e;if(!cw(i,e)){if(eg(i))throw Error(ae(418));e=Wr(t.nextSibling);var n=Ni;e&&cw(i,e)?lw(n,t):(i.flags=i.flags&-4097|2,St=!1,Ni=i)}}else{if(eg(i))throw Error(ae(418));i.flags=i.flags&-4097|2,St=!1,Ni=i}}}function uw(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;Ni=i}function du(i){if(i!==Ni)return!1;if(!St)return uw(i),St=!0,!1;var e;if((e=i.tag!==3)&&!(e=i.tag!==5)&&(e=i.type,e=e!=="head"&&e!=="body"&&!jp(i.type,i.memoizedProps)),e&&(e=Bi)){if(eg(i))throw dw(),Error(ae(418));for(;e;)lw(i,e),e=Wr(e.nextSibling)}if(uw(i),i.tag===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(ae(317));e:{for(i=i.nextSibling,e=0;i;){if(i.nodeType===8){var t=i.data;if(t==="/$"){if(e===0){Bi=Wr(i.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}i=i.nextSibling}Bi=null}}else Bi=Ni?Wr(i.stateNode.nextSibling):null;return!0}function dw(){for(var i=Bi;i;)i=Wr(i.nextSibling)}function Wo(){Bi=Ni=null,St=!1}function ig(i){pn===null?pn=[i]:pn.push(i)}var _2=cr.ReactCurrentBatchConfig;function Sl(i,e,t){if(i=t.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(ae(309));var n=t.stateNode}if(!n)throw Error(ae(147,i));var r=n,s=""+i;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===s?e.ref:(e=function(o){var a=r.refs;o===null?delete a[s]:a[s]=o},e._stringRef=s,e)}if(typeof i!="string")throw Error(ae(284));if(!t._owner)throw Error(ae(290,i))}return i}function hu(i,e){throw i=Object.prototype.toString.call(e),Error(ae(31,i==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":i))}function hw(i){var e=i._init;return e(i._payload)}function fw(i){function e(v,y){if(i){var S=v.deletions;S===null?(v.deletions=[y],v.flags|=16):S.push(y)}}function t(v,y){if(!i)return null;for(;y!==null;)e(v,y),y=y.sibling;return null}function n(v,y){for(v=new Map;y!==null;)y.key!==null?v.set(y.key,y):v.set(y.index,y),y=y.sibling;return v}function r(v,y){return v=is(v,y),v.index=0,v.sibling=null,v}function s(v,y,S){return v.index=S,i?(S=v.alternate,S!==null?(S=S.index,S<y?(v.flags|=2,y):S):(v.flags|=2,y)):(v.flags|=1048576,y)}function o(v){return i&&v.alternate===null&&(v.flags|=2),v}function a(v,y,S,x){return y===null||y.tag!==6?(y=Kg(S,v.mode,x),y.return=v,y):(y=r(y,S),y.return=v,y)}function l(v,y,S,x){var E=S.type;return E===Io?u(v,y,S.props.children,x,S.key):y!==null&&(y.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Nr&&hw(E)===y.type)?(x=r(y,S.props),x.ref=Sl(v,y,S),x.return=v,x):(x=Fu(S.type,S.key,S.props,null,v.mode,x),x.ref=Sl(v,y,S),x.return=v,x)}function c(v,y,S,x){return y===null||y.tag!==4||y.stateNode.containerInfo!==S.containerInfo||y.stateNode.implementation!==S.implementation?(y=qg(S,v.mode,x),y.return=v,y):(y=r(y,S.children||[]),y.return=v,y)}function u(v,y,S,x,E){return y===null||y.tag!==7?(y=Ks(S,v.mode,x,E),y.return=v,y):(y=r(y,S),y.return=v,y)}function d(v,y,S){if(typeof y=="string"&&y!==""||typeof y=="number")return y=Kg(""+y,v.mode,S),y.return=v,y;if(typeof y=="object"&&y!==null){switch(y.$$typeof){case Dc:return S=Fu(y.type,y.key,y.props,null,v.mode,S),S.ref=Sl(v,null,y),S.return=v,S;case Co:return y=qg(y,v.mode,S),y.return=v,y;case Nr:var x=y._init;return d(v,x(y._payload),S)}if(qa(y)||ja(y))return y=Ks(y,v.mode,S,null),y.return=v,y;hu(v,y)}return null}function h(v,y,S,x){var E=y!==null?y.key:null;if(typeof S=="string"&&S!==""||typeof S=="number")return E!==null?null:a(v,y,""+S,x);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case Dc:return S.key===E?l(v,y,S,x):null;case Co:return S.key===E?c(v,y,S,x):null;case Nr:return E=S._init,h(v,y,E(S._payload),x)}if(qa(S)||ja(S))return E!==null?null:u(v,y,S,x,null);hu(v,S)}return null}function f(v,y,S,x,E){if(typeof x=="string"&&x!==""||typeof x=="number")return v=v.get(S)||null,a(y,v,""+x,E);if(typeof x=="object"&&x!==null){switch(x.$$typeof){case Dc:return v=v.get(x.key===null?S:x.key)||null,l(y,v,x,E);case Co:return v=v.get(x.key===null?S:x.key)||null,c(y,v,x,E);case Nr:var C=x._init;return f(v,y,S,C(x._payload),E)}if(qa(x)||ja(x))return v=v.get(S)||null,u(y,v,x,E,null);hu(y,x)}return null}function p(v,y,S,x){for(var E=null,C=null,b=y,I=y=0,D=null;b!==null&&I<S.length;I++){b.index>I?(D=b,b=null):D=b.sibling;var P=h(v,b,S[I],x);if(P===null){b===null&&(b=D);break}i&&b&&P.alternate===null&&e(v,b),y=s(P,y,I),C===null?E=P:C.sibling=P,C=P,b=D}if(I===S.length)return t(v,b),St&&Us(v,I),E;if(b===null){for(;I<S.length;I++)b=d(v,S[I],x),b!==null&&(y=s(b,y,I),C===null?E=b:C.sibling=b,C=b);return St&&Us(v,I),E}for(b=n(v,b);I<S.length;I++)D=f(b,v,I,S[I],x),D!==null&&(i&&D.alternate!==null&&b.delete(D.key===null?I:D.key),y=s(D,y,I),C===null?E=D:C.sibling=D,C=D);return i&&b.forEach(function(k){return e(v,k)}),St&&Us(v,I),E}function g(v,y,S,x){var E=ja(S);if(typeof E!="function")throw Error(ae(150));if(S=E.call(S),S==null)throw Error(ae(151));for(var C=E=null,b=y,I=y=0,D=null,P=S.next();b!==null&&!P.done;I++,P=S.next()){b.index>I?(D=b,b=null):D=b.sibling;var k=h(v,b,P.value,x);if(k===null){b===null&&(b=D);break}i&&b&&k.alternate===null&&e(v,b),y=s(k,y,I),C===null?E=k:C.sibling=k,C=k,b=D}if(P.done)return t(v,b),St&&Us(v,I),E;if(b===null){for(;!P.done;I++,P=S.next())P=d(v,P.value,x),P!==null&&(y=s(P,y,I),C===null?E=P:C.sibling=P,C=P);return St&&Us(v,I),E}for(b=n(v,b);!P.done;I++,P=S.next())P=f(b,v,I,P.value,x),P!==null&&(i&&P.alternate!==null&&b.delete(P.key===null?I:P.key),y=s(P,y,I),C===null?E=P:C.sibling=P,C=P);return i&&b.forEach(function(N){return e(v,N)}),St&&Us(v,I),E}function m(v,y,S,x){if(typeof S=="object"&&S!==null&&S.type===Io&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case Dc:e:{for(var E=S.key,C=y;C!==null;){if(C.key===E){if(E=S.type,E===Io){if(C.tag===7){t(v,C.sibling),y=r(C,S.props.children),y.return=v,v=y;break e}}else if(C.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Nr&&hw(E)===C.type){t(v,C.sibling),y=r(C,S.props),y.ref=Sl(v,C,S),y.return=v,v=y;break e}t(v,C);break}else e(v,C);C=C.sibling}S.type===Io?(y=Ks(S.props.children,v.mode,x,S.key),y.return=v,v=y):(x=Fu(S.type,S.key,S.props,null,v.mode,x),x.ref=Sl(v,y,S),x.return=v,v=x)}return o(v);case Co:e:{for(C=S.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===S.containerInfo&&y.stateNode.implementation===S.implementation){t(v,y.sibling),y=r(y,S.children||[]),y.return=v,v=y;break e}else{t(v,y);break}else e(v,y);y=y.sibling}y=qg(S,v.mode,x),y.return=v,v=y}return o(v);case Nr:return C=S._init,m(v,y,C(S._payload),x)}if(qa(S))return p(v,y,S,x);if(ja(S))return g(v,y,S,x);hu(v,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,y!==null&&y.tag===6?(t(v,y.sibling),y=r(y,S),y.return=v,v=y):(t(v,y),y=Kg(S,v.mode,x),y.return=v,v=y),o(v)):t(v,y)}return m}var jo=fw(!0),pw=fw(!1),fu=jr(null),pu=null,Ko=null,ng=null;function rg(){ng=Ko=pu=null}function sg(i){var e=fu.current;vt(fu),i._currentValue=e}function og(i,e,t){for(;i!==null;){var n=i.alternate;if((i.childLanes&e)!==e?(i.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),i===t)break;i=i.return}}function qo(i,e){pu=i,ng=Ko=null,i=i.dependencies,i!==null&&i.firstContext!==null&&(i.lanes&e&&(bi=!0),i.firstContext=null)}function Qi(i){var e=i._currentValue;if(ng!==i)if(i={context:i,memoizedValue:e,next:null},Ko===null){if(pu===null)throw Error(ae(308));Ko=i,pu.dependencies={lanes:0,firstContext:i}}else Ko=Ko.next=i;return e}var $s=null;function ag(i){$s===null?$s=[i]:$s.push(i)}function gw(i,e,t,n){var r=e.interleaved;return r===null?(t.next=t,ag(e)):(t.next=r.next,r.next=t),e.interleaved=t,pr(i,n)}function pr(i,e){i.lanes|=e;var t=i.alternate;for(t!==null&&(t.lanes|=e),t=i,i=i.return;i!==null;)i.childLanes|=e,t=i.alternate,t!==null&&(t.childLanes|=e),t=i,i=i.return;return t.tag===3?t.stateNode:null}var Yr=!1;function lg(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function mw(i,e){i=i.updateQueue,e.updateQueue===i&&(e.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,effects:i.effects})}function gr(i,e){return{eventTime:i,lane:e,tag:0,payload:null,callback:null,next:null}}function Xr(i,e,t){var n=i.updateQueue;if(n===null)return null;if(n=n.shared,Je&2){var r=n.pending;return r===null?e.next=e:(e.next=r.next,r.next=e),n.pending=e,pr(i,t)}return r=n.interleaved,r===null?(e.next=e,ag(n)):(e.next=r.next,r.next=e),n.interleaved=e,pr(i,t)}function gu(i,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var n=e.lanes;n&=i.pendingLanes,t|=n,e.lanes=t,Ep(i,t)}}function vw(i,e){var t=i.updateQueue,n=i.alternate;if(n!==null&&(n=n.updateQueue,t===n)){var r=null,s=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};s===null?r=s=o:s=s.next=o,t=t.next}while(t!==null);s===null?r=s=e:s=s.next=e}else r=s=e;t={baseState:n.baseState,firstBaseUpdate:r,lastBaseUpdate:s,shared:n.shared,effects:n.effects},i.updateQueue=t;return}i=t.lastBaseUpdate,i===null?t.firstBaseUpdate=e:i.next=e,t.lastBaseUpdate=e}function mu(i,e,t,n){var r=i.updateQueue;Yr=!1;var s=r.firstBaseUpdate,o=r.lastBaseUpdate,a=r.shared.pending;if(a!==null){r.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?s=c:o.next=c,o=l;var u=i.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==o&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(s!==null){var d=r.baseState;o=0,u=c=l=null,a=s;do{var h=a.lane,f=a.eventTime;if((n&h)===h){u!==null&&(u=u.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var p=i,g=a;switch(h=e,f=t,g.tag){case 1:if(p=g.payload,typeof p=="function"){d=p.call(f,d,h);break e}d=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=g.payload,h=typeof p=="function"?p.call(f,d,h):p,h==null)break e;d=_t({},d,h);break e;case 2:Yr=!0}}a.callback!==null&&a.lane!==0&&(i.flags|=64,h=r.effects,h===null?r.effects=[a]:h.push(a))}else f={eventTime:f,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=f,l=d):u=u.next=f,o|=h;if(a=a.next,a===null){if(a=r.shared.pending,a===null)break;h=a,a=h.next,h.next=null,r.lastBaseUpdate=h,r.shared.pending=null}}while(!0);if(u===null&&(l=d),r.baseState=l,r.firstBaseUpdate=c,r.lastBaseUpdate=u,e=r.shared.interleaved,e!==null){r=e;do o|=r.lane,r=r.next;while(r!==e)}else s===null&&(r.shared.lanes=0);Vs|=o,i.lanes=o,i.memoizedState=d}}function yw(i,e,t){if(i=e.effects,e.effects=null,i!==null)for(e=0;e<i.length;e++){var n=i[e],r=n.callback;if(r!==null){if(n.callback=null,n=t,typeof r!="function")throw Error(ae(191,r));r.call(n)}}}var xl={},On=jr(xl),Tl=jr(xl),El=jr(xl);function Hs(i){if(i===xl)throw Error(ae(174));return i}function cg(i,e){switch(ft(El,e),ft(Tl,i),ft(On,xl),i=e.nodeType,i){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:up(null,"");break;default:i=i===8?e.parentNode:e,e=i.namespaceURI||null,i=i.tagName,e=up(e,i)}vt(On),ft(On,e)}function Yo(){vt(On),vt(Tl),vt(El)}function Sw(i){Hs(El.current);var e=Hs(On.current),t=up(e,i.type);e!==t&&(ft(Tl,i),ft(On,t))}function ug(i){Tl.current===i&&(vt(On),vt(Tl))}var At=jr(0);function vu(i){for(var e=i;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===i)break;for(;e.sibling===null;){if(e.return===null||e.return===i)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var dg=[];function hg(){for(var i=0;i<dg.length;i++)dg[i]._workInProgressVersionPrimary=null;dg.length=0}var yu=cr.ReactCurrentDispatcher,fg=cr.ReactCurrentBatchConfig,zs=0,Rt=null,Bt=null,Vt=null,Su=!1,wl=!1,bl=0,A2=0;function ti(){throw Error(ae(321))}function pg(i,e){if(e===null)return!1;for(var t=0;t<e.length&&t<i.length;t++)if(!fn(i[t],e[t]))return!1;return!0}function gg(i,e,t,n,r,s){if(zs=s,Rt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,yu.current=i===null||i.memoizedState===null?P2:L2,i=t(n,r),wl){s=0;do{if(wl=!1,bl=0,25<=s)throw Error(ae(301));s+=1,Vt=Bt=null,e.updateQueue=null,yu.current=k2,i=t(n,r)}while(wl)}if(yu.current=Eu,e=Bt!==null&&Bt.next!==null,zs=0,Vt=Bt=Rt=null,Su=!1,e)throw Error(ae(300));return i}function mg(){var i=bl!==0;return bl=0,i}function Mn(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Vt===null?Rt.memoizedState=Vt=i:Vt=Vt.next=i,Vt}function Ji(){if(Bt===null){var i=Rt.alternate;i=i!==null?i.memoizedState:null}else i=Bt.next;var e=Vt===null?Rt.memoizedState:Vt.next;if(e!==null)Vt=e,Bt=i;else{if(i===null)throw Error(ae(310));Bt=i,i={memoizedState:Bt.memoizedState,baseState:Bt.baseState,baseQueue:Bt.baseQueue,queue:Bt.queue,next:null},Vt===null?Rt.memoizedState=Vt=i:Vt=Vt.next=i}return Vt}function _l(i,e){return typeof e=="function"?e(i):e}function vg(i){var e=Ji(),t=e.queue;if(t===null)throw Error(ae(311));t.lastRenderedReducer=i;var n=Bt,r=n.baseQueue,s=t.pending;if(s!==null){if(r!==null){var o=r.next;r.next=s.next,s.next=o}n.baseQueue=r=s,t.pending=null}if(r!==null){s=r.next,n=n.baseState;var a=o=null,l=null,c=s;do{var u=c.lane;if((zs&u)===u)l!==null&&(l=l.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),n=c.hasEagerState?c.eagerState:i(n,c.action);else{var d={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};l===null?(a=l=d,o=n):l=l.next=d,Rt.lanes|=u,Vs|=u}c=c.next}while(c!==null&&c!==s);l===null?o=n:l.next=a,fn(n,e.memoizedState)||(bi=!0),e.memoizedState=n,e.baseState=o,e.baseQueue=l,t.lastRenderedState=n}if(i=t.interleaved,i!==null){r=i;do s=r.lane,Rt.lanes|=s,Vs|=s,r=r.next;while(r!==i)}else r===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function yg(i){var e=Ji(),t=e.queue;if(t===null)throw Error(ae(311));t.lastRenderedReducer=i;var n=t.dispatch,r=t.pending,s=e.memoizedState;if(r!==null){t.pending=null;var o=r=r.next;do s=i(s,o.action),o=o.next;while(o!==r);fn(s,e.memoizedState)||(bi=!0),e.memoizedState=s,e.baseQueue===null&&(e.baseState=s),t.lastRenderedState=s}return[s,n]}function xw(){}function Tw(i,e){var t=Rt,n=Ji(),r=e(),s=!fn(n.memoizedState,r);if(s&&(n.memoizedState=r,bi=!0),n=n.queue,Sg(bw.bind(null,t,n,i),[i]),n.getSnapshot!==e||s||Vt!==null&&Vt.memoizedState.tag&1){if(t.flags|=2048,Al(9,ww.bind(null,t,n,r,e),void 0,null),Gt===null)throw Error(ae(349));zs&30||Ew(t,e,r)}return r}function Ew(i,e,t){i.flags|=16384,i={getSnapshot:e,value:t},e=Rt.updateQueue,e===null?(e={lastEffect:null,stores:null},Rt.updateQueue=e,e.stores=[i]):(t=e.stores,t===null?e.stores=[i]:t.push(i))}function ww(i,e,t,n){e.value=t,e.getSnapshot=n,_w(e)&&Aw(i)}function bw(i,e,t){return t(function(){_w(e)&&Aw(i)})}function _w(i){var e=i.getSnapshot;i=i.value;try{var t=e();return!fn(i,t)}catch{return!0}}function Aw(i){var e=pr(i,1);e!==null&&yn(e,i,1,-1)}function Rw(i){var e=Mn();return typeof i=="function"&&(i=i()),e.memoizedState=e.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:_l,lastRenderedState:i},e.queue=i,i=i.dispatch=I2.bind(null,Rt,i),[e.memoizedState,i]}function Al(i,e,t,n){return i={tag:i,create:e,destroy:t,deps:n,next:null},e=Rt.updateQueue,e===null?(e={lastEffect:null,stores:null},Rt.updateQueue=e,e.lastEffect=i.next=i):(t=e.lastEffect,t===null?e.lastEffect=i.next=i:(n=t.next,t.next=i,i.next=n,e.lastEffect=i)),i}function Cw(){return Ji().memoizedState}function xu(i,e,t,n){var r=Mn();Rt.flags|=i,r.memoizedState=Al(1|e,t,void 0,n===void 0?null:n)}function Tu(i,e,t,n){var r=Ji();n=n===void 0?null:n;var s=void 0;if(Bt!==null){var o=Bt.memoizedState;if(s=o.destroy,n!==null&&pg(n,o.deps)){r.memoizedState=Al(e,t,s,n);return}}Rt.flags|=i,r.memoizedState=Al(1|e,t,s,n)}function Iw(i,e){return xu(8390656,8,i,e)}function Sg(i,e){return Tu(2048,8,i,e)}function Pw(i,e){return Tu(4,2,i,e)}function Lw(i,e){return Tu(4,4,i,e)}function kw(i,e){if(typeof e=="function")return i=i(),e(i),function(){e(null)};if(e!=null)return i=i(),e.current=i,function(){e.current=null}}function Dw(i,e,t){return t=t!=null?t.concat([i]):null,Tu(4,4,kw.bind(null,e,i),t)}function xg(){}function Ow(i,e){var t=Ji();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&pg(e,n[1])?n[0]:(t.memoizedState=[i,e],i)}function Mw(i,e){var t=Ji();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&pg(e,n[1])?n[0]:(i=i(),t.memoizedState=[i,e],i)}function Fw(i,e,t){return zs&21?(fn(t,e)||(t=hE(),Rt.lanes|=t,Vs|=t,i.baseState=!0),e):(i.baseState&&(i.baseState=!1,bi=!0),i.memoizedState=t)}function R2(i,e){var t=nt;nt=t!==0&&4>t?t:4,i(!0);var n=fg.transition;fg.transition={};try{i(!1),e()}finally{nt=t,fg.transition=n}}function Nw(){return Ji().memoizedState}function C2(i,e,t){var n=es(i);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},Bw(i))Uw(e,t);else if(t=gw(i,e,t,n),t!==null){var r=di();yn(t,i,n,r),$w(t,e,n)}}function I2(i,e,t){var n=es(i),r={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(Bw(i))Uw(e,r);else{var s=i.alternate;if(i.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,a=s(o,t);if(r.hasEagerState=!0,r.eagerState=a,fn(a,o)){var l=e.interleaved;l===null?(r.next=r,ag(e)):(r.next=l.next,l.next=r),e.interleaved=r;return}}catch{}finally{}t=gw(i,e,r,n),t!==null&&(r=di(),yn(t,i,n,r),$w(t,e,n))}}function Bw(i){var e=i.alternate;return i===Rt||e!==null&&e===Rt}function Uw(i,e){wl=Su=!0;var t=i.pending;t===null?e.next=e:(e.next=t.next,t.next=e),i.pending=e}function $w(i,e,t){if(t&4194240){var n=e.lanes;n&=i.pendingLanes,t|=n,e.lanes=t,Ep(i,t)}}var Eu={readContext:Qi,useCallback:ti,useContext:ti,useEffect:ti,useImperativeHandle:ti,useInsertionEffect:ti,useLayoutEffect:ti,useMemo:ti,useReducer:ti,useRef:ti,useState:ti,useDebugValue:ti,useDeferredValue:ti,useTransition:ti,useMutableSource:ti,useSyncExternalStore:ti,useId:ti,unstable_isNewReconciler:!1},P2={readContext:Qi,useCallback:function(i,e){return Mn().memoizedState=[i,e===void 0?null:e],i},useContext:Qi,useEffect:Iw,useImperativeHandle:function(i,e,t){return t=t!=null?t.concat([i]):null,xu(4194308,4,kw.bind(null,e,i),t)},useLayoutEffect:function(i,e){return xu(4194308,4,i,e)},useInsertionEffect:function(i,e){return xu(4,2,i,e)},useMemo:function(i,e){var t=Mn();return e=e===void 0?null:e,i=i(),t.memoizedState=[i,e],i},useReducer:function(i,e,t){var n=Mn();return e=t!==void 0?t(e):e,n.memoizedState=n.baseState=e,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:e},n.queue=i,i=i.dispatch=C2.bind(null,Rt,i),[n.memoizedState,i]},useRef:function(i){var e=Mn();return i={current:i},e.memoizedState=i},useState:Rw,useDebugValue:xg,useDeferredValue:function(i){return Mn().memoizedState=i},useTransition:function(){var i=Rw(!1),e=i[0];return i=R2.bind(null,i[1]),Mn().memoizedState=i,[e,i]},useMutableSource:function(){},useSyncExternalStore:function(i,e,t){var n=Rt,r=Mn();if(St){if(t===void 0)throw Error(ae(407));t=t()}else{if(t=e(),Gt===null)throw Error(ae(349));zs&30||Ew(n,e,t)}r.memoizedState=t;var s={value:t,getSnapshot:e};return r.queue=s,Iw(bw.bind(null,n,s,i),[i]),n.flags|=2048,Al(9,ww.bind(null,n,s,t,e),void 0,null),t},useId:function(){var i=Mn(),e=Gt.identifierPrefix;if(St){var t=fr,n=hr;t=(n&~(1<<32-hn(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=bl++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=A2++,e=":"+e+"r"+t.toString(32)+":";return i.memoizedState=e},unstable_isNewReconciler:!1},L2={readContext:Qi,useCallback:Ow,useContext:Qi,useEffect:Sg,useImperativeHandle:Dw,useInsertionEffect:Pw,useLayoutEffect:Lw,useMemo:Mw,useReducer:vg,useRef:Cw,useState:function(){return vg(_l)},useDebugValue:xg,useDeferredValue:function(i){var e=Ji();return Fw(e,Bt.memoizedState,i)},useTransition:function(){var i=vg(_l)[0],e=Ji().memoizedState;return[i,e]},useMutableSource:xw,useSyncExternalStore:Tw,useId:Nw,unstable_isNewReconciler:!1},k2={readContext:Qi,useCallback:Ow,useContext:Qi,useEffect:Sg,useImperativeHandle:Dw,useInsertionEffect:Pw,useLayoutEffect:Lw,useMemo:Mw,useReducer:yg,useRef:Cw,useState:function(){return yg(_l)},useDebugValue:xg,useDeferredValue:function(i){var e=Ji();return Bt===null?e.memoizedState=i:Fw(e,Bt.memoizedState,i)},useTransition:function(){var i=yg(_l)[0],e=Ji().memoizedState;return[i,e]},useMutableSource:xw,useSyncExternalStore:Tw,useId:Nw,unstable_isNewReconciler:!1};function gn(i,e){if(i&&i.defaultProps){e=_t({},e),i=i.defaultProps;for(var t in i)e[t]===void 0&&(e[t]=i[t]);return e}return e}function Tg(i,e,t,n){e=i.memoizedState,t=t(n,e),t=t==null?e:_t({},e,t),i.memoizedState=t,i.lanes===0&&(i.updateQueue.baseState=t)}var wu={isMounted:function(i){return(i=i._reactInternals)?Ms(i)===i:!1},enqueueSetState:function(i,e,t){i=i._reactInternals;var n=di(),r=es(i),s=gr(n,r);s.payload=e,t!=null&&(s.callback=t),e=Xr(i,s,r),e!==null&&(yn(e,i,r,n),gu(e,i,r))},enqueueReplaceState:function(i,e,t){i=i._reactInternals;var n=di(),r=es(i),s=gr(n,r);s.tag=1,s.payload=e,t!=null&&(s.callback=t),e=Xr(i,s,r),e!==null&&(yn(e,i,r,n),gu(e,i,r))},enqueueForceUpdate:function(i,e){i=i._reactInternals;var t=di(),n=es(i),r=gr(t,n);r.tag=2,e!=null&&(r.callback=e),e=Xr(i,r,n),e!==null&&(yn(e,i,n,t),gu(e,i,n))}};function Hw(i,e,t,n,r,s,o){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(n,s,o):e.prototype&&e.prototype.isPureReactComponent?!hl(t,n)||!hl(r,s):!0}function zw(i,e,t){var n=!1,r=Kr,s=e.contextType;return typeof s=="object"&&s!==null?s=Qi(s):(r=wi(e)?Ns:ei.current,n=e.contextTypes,s=(n=n!=null)?zo(i,r):Kr),e=new e(t,s),i.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=wu,i.stateNode=e,e._reactInternals=i,n&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=r,i.__reactInternalMemoizedMaskedChildContext=s),e}function Vw(i,e,t,n){i=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,n),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,n),e.state!==i&&wu.enqueueReplaceState(e,e.state,null)}function Eg(i,e,t,n){var r=i.stateNode;r.props=t,r.state=i.memoizedState,r.refs={},lg(i);var s=e.contextType;typeof s=="object"&&s!==null?r.context=Qi(s):(s=wi(e)?Ns:ei.current,r.context=zo(i,s)),r.state=i.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&(Tg(i,e,s,t),r.state=i.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof r.getSnapshotBeforeUpdate=="function"||typeof r.UNSAFE_componentWillMount!="function"&&typeof r.componentWillMount!="function"||(e=r.state,typeof r.componentWillMount=="function"&&r.componentWillMount(),typeof r.UNSAFE_componentWillMount=="function"&&r.UNSAFE_componentWillMount(),e!==r.state&&wu.enqueueReplaceState(r,r.state,null),mu(i,t,r,n),r.state=i.memoizedState),typeof r.componentDidMount=="function"&&(i.flags|=4194308)}function Xo(i,e){try{var t="",n=e;do t+=oN(n),n=n.return;while(n);var r=t}catch(s){r=`
|
|
43
|
+
Error generating stack: `+s.message+`
|
|
44
|
+
`+s.stack}return{value:i,source:e,stack:r,digest:null}}function wg(i,e,t){return{value:i,source:null,stack:t??null,digest:e??null}}function bg(i,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var D2=typeof WeakMap=="function"?WeakMap:Map;function Gw(i,e,t){t=gr(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){Pu||(Pu=!0,Ug=n),bg(i,e)},t}function Ww(i,e,t){t=gr(-1,t),t.tag=3;var n=i.type.getDerivedStateFromError;if(typeof n=="function"){var r=e.value;t.payload=function(){return n(r)},t.callback=function(){bg(i,e)}}var s=i.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(t.callback=function(){bg(i,e),typeof n!="function"&&(Qr===null?Qr=new Set([this]):Qr.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),t}function jw(i,e,t){var n=i.pingCache;if(n===null){n=i.pingCache=new D2;var r=new Set;n.set(e,r)}else r=n.get(e),r===void 0&&(r=new Set,n.set(e,r));r.has(t)||(r.add(t),i=K2.bind(null,i,e,t),e.then(i,i))}function Kw(i){do{var e;if((e=i.tag===13)&&(e=i.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return i;i=i.return}while(i!==null);return null}function qw(i,e,t,n,r){return i.mode&1?(i.flags|=65536,i.lanes=r,i):(i===e?i.flags|=65536:(i.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=gr(-1,1),e.tag=2,Xr(t,e,1))),t.lanes|=1),i)}var O2=cr.ReactCurrentOwner,bi=!1;function ui(i,e,t,n){e.child=i===null?pw(e,null,t,n):jo(e,i.child,t,n)}function Yw(i,e,t,n,r){t=t.render;var s=e.ref;return qo(e,r),n=gg(i,e,t,n,s,r),t=mg(),i!==null&&!bi?(e.updateQueue=i.updateQueue,e.flags&=-2053,i.lanes&=~r,mr(i,e,r)):(St&&t&&Qp(e),e.flags|=1,ui(i,e,n,r),e.child)}function Xw(i,e,t,n,r){if(i===null){var s=t.type;return typeof s=="function"&&!jg(s)&&s.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=s,Zw(i,e,s,n,r)):(i=Fu(t.type,null,n,e,e.mode,r),i.ref=e.ref,i.return=e,e.child=i)}if(s=i.child,!(i.lanes&r)){var o=s.memoizedProps;if(t=t.compare,t=t!==null?t:hl,t(o,n)&&i.ref===e.ref)return mr(i,e,r)}return e.flags|=1,i=is(s,n),i.ref=e.ref,i.return=e,e.child=i}function Zw(i,e,t,n,r){if(i!==null){var s=i.memoizedProps;if(hl(s,n)&&i.ref===e.ref)if(bi=!1,e.pendingProps=n=s,(i.lanes&r)!==0)i.flags&131072&&(bi=!0);else return e.lanes=i.lanes,mr(i,e,r)}return _g(i,e,t,n,r)}function Qw(i,e,t){var n=e.pendingProps,r=n.children,s=i!==null?i.memoizedState:null;if(n.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},ft(Qo,Ui),Ui|=t;else{if(!(t&1073741824))return i=s!==null?s.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:i,cachePool:null,transitions:null},e.updateQueue=null,ft(Qo,Ui),Ui|=i,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:t,ft(Qo,Ui),Ui|=n}else s!==null?(n=s.baseLanes|t,e.memoizedState=null):n=t,ft(Qo,Ui),Ui|=n;return ui(i,e,r,t),e.child}function Jw(i,e){var t=e.ref;(i===null&&t!==null||i!==null&&i.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function _g(i,e,t,n,r){var s=wi(t)?Ns:ei.current;return s=zo(e,s),qo(e,r),t=gg(i,e,t,n,s,r),n=mg(),i!==null&&!bi?(e.updateQueue=i.updateQueue,e.flags&=-2053,i.lanes&=~r,mr(i,e,r)):(St&&n&&Qp(e),e.flags|=1,ui(i,e,t,r),e.child)}function eb(i,e,t,n,r){if(wi(t)){var s=!0;au(e)}else s=!1;if(qo(e,r),e.stateNode===null)_u(i,e),zw(e,t,n),Eg(e,t,n,r),n=!0;else if(i===null){var o=e.stateNode,a=e.memoizedProps;o.props=a;var l=o.context,c=t.contextType;typeof c=="object"&&c!==null?c=Qi(c):(c=wi(t)?Ns:ei.current,c=zo(e,c));var u=t.getDerivedStateFromProps,d=typeof u=="function"||typeof o.getSnapshotBeforeUpdate=="function";d||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==n||l!==c)&&Vw(e,o,n,c),Yr=!1;var h=e.memoizedState;o.state=h,mu(e,n,o,r),l=e.memoizedState,a!==n||h!==l||Ei.current||Yr?(typeof u=="function"&&(Tg(e,t,u,n),l=e.memoizedState),(a=Yr||Hw(e,t,a,n,h,l,c))?(d||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(e.flags|=4194308)):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=l),o.props=n,o.state=l,o.context=c,n=a):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{o=e.stateNode,mw(i,e),a=e.memoizedProps,c=e.type===e.elementType?a:gn(e.type,a),o.props=c,d=e.pendingProps,h=o.context,l=t.contextType,typeof l=="object"&&l!==null?l=Qi(l):(l=wi(t)?Ns:ei.current,l=zo(e,l));var f=t.getDerivedStateFromProps;(u=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==d||h!==l)&&Vw(e,o,n,l),Yr=!1,h=e.memoizedState,o.state=h,mu(e,n,o,r);var p=e.memoizedState;a!==d||h!==p||Ei.current||Yr?(typeof f=="function"&&(Tg(e,t,f,n),p=e.memoizedState),(c=Yr||Hw(e,t,c,n,h,p,l)||!1)?(u||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(n,p,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(n,p,l)),typeof o.componentDidUpdate=="function"&&(e.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof o.componentDidUpdate!="function"||a===i.memoizedProps&&h===i.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===i.memoizedProps&&h===i.memoizedState||(e.flags|=1024),e.memoizedProps=n,e.memoizedState=p),o.props=n,o.state=p,o.context=l,n=c):(typeof o.componentDidUpdate!="function"||a===i.memoizedProps&&h===i.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===i.memoizedProps&&h===i.memoizedState||(e.flags|=1024),n=!1)}return Ag(i,e,t,n,s,r)}function Ag(i,e,t,n,r,s){Jw(i,e);var o=(e.flags&128)!==0;if(!n&&!o)return r&&sw(e,t,!1),mr(i,e,s);n=e.stateNode,O2.current=e;var a=o&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,i!==null&&o?(e.child=jo(e,i.child,null,s),e.child=jo(e,null,a,s)):ui(i,e,a,s),e.memoizedState=n.state,r&&sw(e,t,!0),e.child}function tb(i){var e=i.stateNode;e.pendingContext?nw(i,e.pendingContext,e.pendingContext!==e.context):e.context&&nw(i,e.context,!1),cg(i,e.containerInfo)}function ib(i,e,t,n,r){return Wo(),ig(r),e.flags|=256,ui(i,e,t,n),e.child}var Rg={dehydrated:null,treeContext:null,retryLane:0};function Cg(i){return{baseLanes:i,cachePool:null,transitions:null}}function nb(i,e,t){var n=e.pendingProps,r=At.current,s=!1,o=(e.flags&128)!==0,a;if((a=o)||(a=i!==null&&i.memoizedState===null?!1:(r&2)!==0),a?(s=!0,e.flags&=-129):(i===null||i.memoizedState!==null)&&(r|=1),ft(At,r&1),i===null)return tg(e),i=e.memoizedState,i!==null&&(i=i.dehydrated,i!==null)?(e.mode&1?i.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(o=n.children,i=n.fallback,s?(n=e.mode,s=e.child,o={mode:"hidden",children:o},!(n&1)&&s!==null?(s.childLanes=0,s.pendingProps=o):s=Nu(o,n,0,null),i=Ks(i,n,t,null),s.return=e,i.return=e,s.sibling=i,e.child=s,e.child.memoizedState=Cg(t),e.memoizedState=Rg,i):Ig(e,o));if(r=i.memoizedState,r!==null&&(a=r.dehydrated,a!==null))return M2(i,e,o,n,a,r,t);if(s){s=n.fallback,o=e.mode,r=i.child,a=r.sibling;var l={mode:"hidden",children:n.children};return!(o&1)&&e.child!==r?(n=e.child,n.childLanes=0,n.pendingProps=l,e.deletions=null):(n=is(r,l),n.subtreeFlags=r.subtreeFlags&14680064),a!==null?s=is(a,s):(s=Ks(s,o,t,null),s.flags|=2),s.return=e,n.return=e,n.sibling=s,e.child=n,n=s,s=e.child,o=i.child.memoizedState,o=o===null?Cg(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=i.childLanes&~t,e.memoizedState=Rg,n}return s=i.child,i=s.sibling,n=is(s,{mode:"visible",children:n.children}),!(e.mode&1)&&(n.lanes=t),n.return=e,n.sibling=null,i!==null&&(t=e.deletions,t===null?(e.deletions=[i],e.flags|=16):t.push(i)),e.child=n,e.memoizedState=null,n}function Ig(i,e){return e=Nu({mode:"visible",children:e},i.mode,0,null),e.return=i,i.child=e}function bu(i,e,t,n){return n!==null&&ig(n),jo(e,i.child,null,t),i=Ig(e,e.pendingProps.children),i.flags|=2,e.memoizedState=null,i}function M2(i,e,t,n,r,s,o){if(t)return e.flags&256?(e.flags&=-257,n=wg(Error(ae(422))),bu(i,e,o,n)):e.memoizedState!==null?(e.child=i.child,e.flags|=128,null):(s=n.fallback,r=e.mode,n=Nu({mode:"visible",children:n.children},r,0,null),s=Ks(s,r,o,null),s.flags|=2,n.return=e,s.return=e,n.sibling=s,e.child=n,e.mode&1&&jo(e,i.child,null,o),e.child.memoizedState=Cg(o),e.memoizedState=Rg,s);if(!(e.mode&1))return bu(i,e,o,null);if(r.data==="$!"){if(n=r.nextSibling&&r.nextSibling.dataset,n)var a=n.dgst;return n=a,s=Error(ae(419)),n=wg(s,n,void 0),bu(i,e,o,n)}if(a=(o&i.childLanes)!==0,bi||a){if(n=Gt,n!==null){switch(o&-o){case 4:r=2;break;case 16:r=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:r=32;break;case 536870912:r=268435456;break;default:r=0}r=r&(n.suspendedLanes|o)?0:r,r!==0&&r!==s.retryLane&&(s.retryLane=r,pr(i,r),yn(n,i,r,-1))}return Wg(),n=wg(Error(ae(421))),bu(i,e,o,n)}return r.data==="$?"?(e.flags|=128,e.child=i.child,e=q2.bind(null,i),r._reactRetry=e,null):(i=s.treeContext,Bi=Wr(r.nextSibling),Ni=e,St=!0,pn=null,i!==null&&(Xi[Zi++]=hr,Xi[Zi++]=fr,Xi[Zi++]=Bs,hr=i.id,fr=i.overflow,Bs=e),e=Ig(e,n.children),e.flags|=4096,e)}function rb(i,e,t){i.lanes|=e;var n=i.alternate;n!==null&&(n.lanes|=e),og(i.return,e,t)}function Pg(i,e,t,n,r){var s=i.memoizedState;s===null?i.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:n,tail:t,tailMode:r}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=n,s.tail=t,s.tailMode=r)}function sb(i,e,t){var n=e.pendingProps,r=n.revealOrder,s=n.tail;if(ui(i,e,n.children,t),n=At.current,n&2)n=n&1|2,e.flags|=128;else{if(i!==null&&i.flags&128)e:for(i=e.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&rb(i,t,e);else if(i.tag===19)rb(i,t,e);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===e)break e;for(;i.sibling===null;){if(i.return===null||i.return===e)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}n&=1}if(ft(At,n),!(e.mode&1))e.memoizedState=null;else switch(r){case"forwards":for(t=e.child,r=null;t!==null;)i=t.alternate,i!==null&&vu(i)===null&&(r=t),t=t.sibling;t=r,t===null?(r=e.child,e.child=null):(r=t.sibling,t.sibling=null),Pg(e,!1,r,t,s);break;case"backwards":for(t=null,r=e.child,e.child=null;r!==null;){if(i=r.alternate,i!==null&&vu(i)===null){e.child=r;break}i=r.sibling,r.sibling=t,t=r,r=i}Pg(e,!0,t,null,s);break;case"together":Pg(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function _u(i,e){!(e.mode&1)&&i!==null&&(i.alternate=null,e.alternate=null,e.flags|=2)}function mr(i,e,t){if(i!==null&&(e.dependencies=i.dependencies),Vs|=e.lanes,!(t&e.childLanes))return null;if(i!==null&&e.child!==i.child)throw Error(ae(153));if(e.child!==null){for(i=e.child,t=is(i,i.pendingProps),e.child=t,t.return=e;i.sibling!==null;)i=i.sibling,t=t.sibling=is(i,i.pendingProps),t.return=e;t.sibling=null}return e.child}function F2(i,e,t){switch(e.tag){case 3:tb(e),Wo();break;case 5:Sw(e);break;case 1:wi(e.type)&&au(e);break;case 4:cg(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,r=e.memoizedProps.value;ft(fu,n._currentValue),n._currentValue=r;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(ft(At,At.current&1),e.flags|=128,null):t&e.child.childLanes?nb(i,e,t):(ft(At,At.current&1),i=mr(i,e,t),i!==null?i.sibling:null);ft(At,At.current&1);break;case 19:if(n=(t&e.childLanes)!==0,i.flags&128){if(n)return sb(i,e,t);e.flags|=128}if(r=e.memoizedState,r!==null&&(r.rendering=null,r.tail=null,r.lastEffect=null),ft(At,At.current),n)break;return null;case 22:case 23:return e.lanes=0,Qw(i,e,t)}return mr(i,e,t)}var ob,Lg,ab,lb;ob=function(i,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)i.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}},Lg=function(){},ab=function(i,e,t,n){var r=i.memoizedProps;if(r!==n){i=e.stateNode,Hs(On.current);var s=null;switch(t){case"input":r=op(i,r),n=op(i,n),s=[];break;case"select":r=_t({},r,{value:void 0}),n=_t({},n,{value:void 0}),s=[];break;case"textarea":r=cp(i,r),n=cp(i,n),s=[];break;default:typeof r.onClick!="function"&&typeof n.onClick=="function"&&(i.onclick=ru)}dp(t,n);var o;t=null;for(c in r)if(!n.hasOwnProperty(c)&&r.hasOwnProperty(c)&&r[c]!=null)if(c==="style"){var a=r[c];for(o in a)a.hasOwnProperty(o)&&(t||(t={}),t[o]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(Wa.hasOwnProperty(c)?s||(s=[]):(s=s||[]).push(c,null));for(c in n){var l=n[c];if(a=r!=null?r[c]:void 0,n.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(o in a)!a.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(t||(t={}),t[o]="");for(o in l)l.hasOwnProperty(o)&&a[o]!==l[o]&&(t||(t={}),t[o]=l[o])}else t||(s||(s=[]),s.push(c,t)),t=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(s=s||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(s=s||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(Wa.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&mt("scroll",i),s||a===l||(s=[])):(s=s||[]).push(c,l))}t&&(s=s||[]).push("style",t);var c=s;(e.updateQueue=c)&&(e.flags|=4)}},lb=function(i,e,t,n){t!==n&&(e.flags|=4)};function Rl(i,e){if(!St)switch(i.tailMode){case"hidden":e=i.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?i.tail=null:t.sibling=null;break;case"collapsed":t=i.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e||i.tail===null?i.tail=null:i.tail.sibling=null:n.sibling=null}}function ii(i){var e=i.alternate!==null&&i.alternate.child===i.child,t=0,n=0;if(e)for(var r=i.child;r!==null;)t|=r.lanes|r.childLanes,n|=r.subtreeFlags&14680064,n|=r.flags&14680064,r.return=i,r=r.sibling;else for(r=i.child;r!==null;)t|=r.lanes|r.childLanes,n|=r.subtreeFlags,n|=r.flags,r.return=i,r=r.sibling;return i.subtreeFlags|=n,i.childLanes=t,e}function N2(i,e,t){var n=e.pendingProps;switch(Jp(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ii(e),null;case 1:return wi(e.type)&&ou(),ii(e),null;case 3:return n=e.stateNode,Yo(),vt(Ei),vt(ei),hg(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(i===null||i.child===null)&&(du(e)?e.flags|=4:i===null||i.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,pn!==null&&(zg(pn),pn=null))),Lg(i,e),ii(e),null;case 5:ug(e);var r=Hs(El.current);if(t=e.type,i!==null&&e.stateNode!=null)ab(i,e,t,n,r),i.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(ae(166));return ii(e),null}if(i=Hs(On.current),du(e)){n=e.stateNode,t=e.type;var s=e.memoizedProps;switch(n[Dn]=e,n[vl]=s,i=(e.mode&1)!==0,t){case"dialog":mt("cancel",n),mt("close",n);break;case"iframe":case"object":case"embed":mt("load",n);break;case"video":case"audio":for(r=0;r<pl.length;r++)mt(pl[r],n);break;case"source":mt("error",n);break;case"img":case"image":case"link":mt("error",n),mt("load",n);break;case"details":mt("toggle",n);break;case"input":zT(n,s),mt("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},mt("invalid",n);break;case"textarea":WT(n,s),mt("invalid",n)}dp(t,s),r=null;for(var o in s)if(s.hasOwnProperty(o)){var a=s[o];o==="children"?typeof a=="string"?n.textContent!==a&&(s.suppressHydrationWarning!==!0&&nu(n.textContent,a,i),r=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(s.suppressHydrationWarning!==!0&&nu(n.textContent,a,i),r=["children",""+a]):Wa.hasOwnProperty(o)&&a!=null&&o==="onScroll"&&mt("scroll",n)}switch(t){case"input":Oc(n),GT(n,s,!0);break;case"textarea":Oc(n),KT(n);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(n.onclick=ru)}n=r,e.updateQueue=n,n!==null&&(e.flags|=4)}else{o=r.nodeType===9?r:r.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=qT(t)),i==="http://www.w3.org/1999/xhtml"?t==="script"?(i=o.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof n.is=="string"?i=o.createElement(t,{is:n.is}):(i=o.createElement(t),t==="select"&&(o=i,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):i=o.createElementNS(i,t),i[Dn]=e,i[vl]=n,ob(i,e,!1,!1),e.stateNode=i;e:{switch(o=hp(t,n),t){case"dialog":mt("cancel",i),mt("close",i),r=n;break;case"iframe":case"object":case"embed":mt("load",i),r=n;break;case"video":case"audio":for(r=0;r<pl.length;r++)mt(pl[r],i);r=n;break;case"source":mt("error",i),r=n;break;case"img":case"image":case"link":mt("error",i),mt("load",i),r=n;break;case"details":mt("toggle",i),r=n;break;case"input":zT(i,n),r=op(i,n),mt("invalid",i);break;case"option":r=n;break;case"select":i._wrapperState={wasMultiple:!!n.multiple},r=_t({},n,{value:void 0}),mt("invalid",i);break;case"textarea":WT(i,n),r=cp(i,n),mt("invalid",i);break;default:r=n}dp(t,r),a=r;for(s in a)if(a.hasOwnProperty(s)){var l=a[s];s==="style"?ZT(i,l):s==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&YT(i,l)):s==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&Ya(i,l):typeof l=="number"&&Ya(i,""+l):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(Wa.hasOwnProperty(s)?l!=null&&s==="onScroll"&&mt("scroll",i):l!=null&&Yf(i,s,l,o))}switch(t){case"input":Oc(i),GT(i,n,!1);break;case"textarea":Oc(i),KT(i);break;case"option":n.value!=null&&i.setAttribute("value",""+Br(n.value));break;case"select":i.multiple=!!n.multiple,s=n.value,s!=null?Po(i,!!n.multiple,s,!1):n.defaultValue!=null&&Po(i,!!n.multiple,n.defaultValue,!0);break;default:typeof r.onClick=="function"&&(i.onclick=ru)}switch(t){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return ii(e),null;case 6:if(i&&e.stateNode!=null)lb(i,e,i.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(ae(166));if(t=Hs(El.current),Hs(On.current),du(e)){if(n=e.stateNode,t=e.memoizedProps,n[Dn]=e,(s=n.nodeValue!==t)&&(i=Ni,i!==null))switch(i.tag){case 3:nu(n.nodeValue,t,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&nu(n.nodeValue,t,(i.mode&1)!==0)}s&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Dn]=e,e.stateNode=n}return ii(e),null;case 13:if(vt(At),n=e.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if(St&&Bi!==null&&e.mode&1&&!(e.flags&128))dw(),Wo(),e.flags|=98560,s=!1;else if(s=du(e),n!==null&&n.dehydrated!==null){if(i===null){if(!s)throw Error(ae(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(ae(317));s[Dn]=e}else Wo(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;ii(e),s=!1}else pn!==null&&(zg(pn),pn=null),s=!0;if(!s)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(n=n!==null,n!==(i!==null&&i.memoizedState!==null)&&n&&(e.child.flags|=8192,e.mode&1&&(i===null||At.current&1?Ut===0&&(Ut=3):Wg())),e.updateQueue!==null&&(e.flags|=4),ii(e),null);case 4:return Yo(),Lg(i,e),i===null&&gl(e.stateNode.containerInfo),ii(e),null;case 10:return sg(e.type._context),ii(e),null;case 17:return wi(e.type)&&ou(),ii(e),null;case 19:if(vt(At),s=e.memoizedState,s===null)return ii(e),null;if(n=(e.flags&128)!==0,o=s.rendering,o===null)if(n)Rl(s,!1);else{if(Ut!==0||i!==null&&i.flags&128)for(i=e.child;i!==null;){if(o=vu(i),o!==null){for(e.flags|=128,Rl(s,!1),n=o.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),e.subtreeFlags=0,n=t,t=e.child;t!==null;)s=t,i=n,s.flags&=14680066,o=s.alternate,o===null?(s.childLanes=0,s.lanes=i,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=o.childLanes,s.lanes=o.lanes,s.child=o.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=o.memoizedProps,s.memoizedState=o.memoizedState,s.updateQueue=o.updateQueue,s.type=o.type,i=o.dependencies,s.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),t=t.sibling;return ft(At,At.current&1|2),e.child}i=i.sibling}s.tail!==null&&Lt()>Jo&&(e.flags|=128,n=!0,Rl(s,!1),e.lanes=4194304)}else{if(!n)if(i=vu(o),i!==null){if(e.flags|=128,n=!0,t=i.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),Rl(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!St)return ii(e),null}else 2*Lt()-s.renderingStartTime>Jo&&t!==1073741824&&(e.flags|=128,n=!0,Rl(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(t=s.last,t!==null?t.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Lt(),e.sibling=null,t=At.current,ft(At,n?t&1|2:t&1),e):(ii(e),null);case 22:case 23:return Gg(),n=e.memoizedState!==null,i!==null&&i.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Ui&1073741824&&(ii(e),e.subtreeFlags&6&&(e.flags|=8192)):ii(e),null;case 24:return null;case 25:return null}throw Error(ae(156,e.tag))}function B2(i,e){switch(Jp(e),e.tag){case 1:return wi(e.type)&&ou(),i=e.flags,i&65536?(e.flags=i&-65537|128,e):null;case 3:return Yo(),vt(Ei),vt(ei),hg(),i=e.flags,i&65536&&!(i&128)?(e.flags=i&-65537|128,e):null;case 5:return ug(e),null;case 13:if(vt(At),i=e.memoizedState,i!==null&&i.dehydrated!==null){if(e.alternate===null)throw Error(ae(340));Wo()}return i=e.flags,i&65536?(e.flags=i&-65537|128,e):null;case 19:return vt(At),null;case 4:return Yo(),null;case 10:return sg(e.type._context),null;case 22:case 23:return Gg(),null;case 24:return null;default:return null}}var Au=!1,ni=!1,U2=typeof WeakSet=="function"?WeakSet:Set,Se=null;function Zo(i,e){var t=i.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){It(i,e,n)}else t.current=null}function kg(i,e,t){try{t()}catch(n){It(i,e,n)}}var cb=!1;function $2(i,e){if(Gp=jc,i=HE(),Fp(i)){if("selectionStart"in i)var t={start:i.selectionStart,end:i.selectionEnd};else e:{t=(t=i.ownerDocument)&&t.defaultView||window;var n=t.getSelection&&t.getSelection();if(n&&n.rangeCount!==0){t=n.anchorNode;var r=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{t.nodeType,s.nodeType}catch{t=null;break e}var o=0,a=-1,l=-1,c=0,u=0,d=i,h=null;t:for(;;){for(var f;d!==t||r!==0&&d.nodeType!==3||(a=o+r),d!==s||n!==0&&d.nodeType!==3||(l=o+n),d.nodeType===3&&(o+=d.nodeValue.length),(f=d.firstChild)!==null;)h=d,d=f;for(;;){if(d===i)break t;if(h===t&&++c===r&&(a=o),h===s&&++u===n&&(l=o),(f=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(Wp={focusedElem:i,selectionRange:t},jc=!1,Se=e;Se!==null;)if(e=Se,i=e.child,(e.subtreeFlags&1028)!==0&&i!==null)i.return=e,Se=i;else for(;Se!==null;){e=Se;try{var p=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var g=p.memoizedProps,m=p.memoizedState,v=e.stateNode,y=v.getSnapshotBeforeUpdate(e.elementType===e.type?g:gn(e.type,g),m);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var S=e.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ae(163))}}catch(x){It(e,e.return,x)}if(i=e.sibling,i!==null){i.return=e.return,Se=i;break}Se=e.return}return p=cb,cb=!1,p}function Cl(i,e,t){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var r=n=n.next;do{if((r.tag&i)===i){var s=r.destroy;r.destroy=void 0,s!==void 0&&kg(e,t,s)}r=r.next}while(r!==n)}}function Ru(i,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&i)===i){var n=t.create;t.destroy=n()}t=t.next}while(t!==e)}}function Dg(i){var e=i.ref;if(e!==null){var t=i.stateNode;switch(i.tag){case 5:i=t;break;default:i=t}typeof e=="function"?e(i):e.current=i}}function ub(i){var e=i.alternate;e!==null&&(i.alternate=null,ub(e)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(e=i.stateNode,e!==null&&(delete e[Dn],delete e[vl],delete e[Yp],delete e[E2],delete e[w2])),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}function db(i){return i.tag===5||i.tag===3||i.tag===4}function hb(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||db(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function Og(i,e,t){var n=i.tag;if(n===5||n===6)i=i.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(i,e):t.insertBefore(i,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(i,t)):(e=t,e.appendChild(i)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=ru));else if(n!==4&&(i=i.child,i!==null))for(Og(i,e,t),i=i.sibling;i!==null;)Og(i,e,t),i=i.sibling}function Mg(i,e,t){var n=i.tag;if(n===5||n===6)i=i.stateNode,e?t.insertBefore(i,e):t.appendChild(i);else if(n!==4&&(i=i.child,i!==null))for(Mg(i,e,t),i=i.sibling;i!==null;)Mg(i,e,t),i=i.sibling}var Zt=null,mn=!1;function Zr(i,e,t){for(t=t.child;t!==null;)fb(i,e,t),t=t.sibling}function fb(i,e,t){if(kn&&typeof kn.onCommitFiberUnmount=="function")try{kn.onCommitFiberUnmount($c,t)}catch{}switch(t.tag){case 5:ni||Zo(t,e);case 6:var n=Zt,r=mn;Zt=null,Zr(i,e,t),Zt=n,mn=r,Zt!==null&&(mn?(i=Zt,t=t.stateNode,i.nodeType===8?i.parentNode.removeChild(t):i.removeChild(t)):Zt.removeChild(t.stateNode));break;case 18:Zt!==null&&(mn?(i=Zt,t=t.stateNode,i.nodeType===8?qp(i.parentNode,t):i.nodeType===1&&qp(i,t),ol(i)):qp(Zt,t.stateNode));break;case 4:n=Zt,r=mn,Zt=t.stateNode.containerInfo,mn=!0,Zr(i,e,t),Zt=n,mn=r;break;case 0:case 11:case 14:case 15:if(!ni&&(n=t.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){r=n=n.next;do{var s=r,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&kg(t,e,o),r=r.next}while(r!==n)}Zr(i,e,t);break;case 1:if(!ni&&(Zo(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){It(t,e,a)}Zr(i,e,t);break;case 21:Zr(i,e,t);break;case 22:t.mode&1?(ni=(n=ni)||t.memoizedState!==null,Zr(i,e,t),ni=n):Zr(i,e,t);break;default:Zr(i,e,t)}}function pb(i){var e=i.updateQueue;if(e!==null){i.updateQueue=null;var t=i.stateNode;t===null&&(t=i.stateNode=new U2),e.forEach(function(n){var r=Y2.bind(null,i,n);t.has(n)||(t.add(n),n.then(r,r))})}}function vn(i,e){var t=e.deletions;if(t!==null)for(var n=0;n<t.length;n++){var r=t[n];try{var s=i,o=e,a=o;e:for(;a!==null;){switch(a.tag){case 5:Zt=a.stateNode,mn=!1;break e;case 3:Zt=a.stateNode.containerInfo,mn=!0;break e;case 4:Zt=a.stateNode.containerInfo,mn=!0;break e}a=a.return}if(Zt===null)throw Error(ae(160));fb(s,o,r),Zt=null,mn=!1;var l=r.alternate;l!==null&&(l.return=null),r.return=null}catch(c){It(r,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)gb(e,i),e=e.sibling}function gb(i,e){var t=i.alternate,n=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(vn(e,i),Fn(i),n&4){try{Cl(3,i,i.return),Ru(3,i)}catch(g){It(i,i.return,g)}try{Cl(5,i,i.return)}catch(g){It(i,i.return,g)}}break;case 1:vn(e,i),Fn(i),n&512&&t!==null&&Zo(t,t.return);break;case 5:if(vn(e,i),Fn(i),n&512&&t!==null&&Zo(t,t.return),i.flags&32){var r=i.stateNode;try{Ya(r,"")}catch(g){It(i,i.return,g)}}if(n&4&&(r=i.stateNode,r!=null)){var s=i.memoizedProps,o=t!==null?t.memoizedProps:s,a=i.type,l=i.updateQueue;if(i.updateQueue=null,l!==null)try{a==="input"&&s.type==="radio"&&s.name!=null&&VT(r,s),hp(a,o);var c=hp(a,s);for(o=0;o<l.length;o+=2){var u=l[o],d=l[o+1];u==="style"?ZT(r,d):u==="dangerouslySetInnerHTML"?YT(r,d):u==="children"?Ya(r,d):Yf(r,u,d,c)}switch(a){case"input":ap(r,s);break;case"textarea":jT(r,s);break;case"select":var h=r._wrapperState.wasMultiple;r._wrapperState.wasMultiple=!!s.multiple;var f=s.value;f!=null?Po(r,!!s.multiple,f,!1):h!==!!s.multiple&&(s.defaultValue!=null?Po(r,!!s.multiple,s.defaultValue,!0):Po(r,!!s.multiple,s.multiple?[]:"",!1))}r[vl]=s}catch(g){It(i,i.return,g)}}break;case 6:if(vn(e,i),Fn(i),n&4){if(i.stateNode===null)throw Error(ae(162));r=i.stateNode,s=i.memoizedProps;try{r.nodeValue=s}catch(g){It(i,i.return,g)}}break;case 3:if(vn(e,i),Fn(i),n&4&&t!==null&&t.memoizedState.isDehydrated)try{ol(e.containerInfo)}catch(g){It(i,i.return,g)}break;case 4:vn(e,i),Fn(i);break;case 13:vn(e,i),Fn(i),r=i.child,r.flags&8192&&(s=r.memoizedState!==null,r.stateNode.isHidden=s,!s||r.alternate!==null&&r.alternate.memoizedState!==null||(Bg=Lt())),n&4&&pb(i);break;case 22:if(u=t!==null&&t.memoizedState!==null,i.mode&1?(ni=(c=ni)||u,vn(e,i),ni=c):vn(e,i),Fn(i),n&8192){if(c=i.memoizedState!==null,(i.stateNode.isHidden=c)&&!u&&i.mode&1)for(Se=i,u=i.child;u!==null;){for(d=Se=u;Se!==null;){switch(h=Se,f=h.child,h.tag){case 0:case 11:case 14:case 15:Cl(4,h,h.return);break;case 1:Zo(h,h.return);var p=h.stateNode;if(typeof p.componentWillUnmount=="function"){n=h,t=h.return;try{e=n,p.props=e.memoizedProps,p.state=e.memoizedState,p.componentWillUnmount()}catch(g){It(n,t,g)}}break;case 5:Zo(h,h.return);break;case 22:if(h.memoizedState!==null){yb(d);continue}}f!==null?(f.return=h,Se=f):yb(d)}u=u.sibling}e:for(u=null,d=i;;){if(d.tag===5){if(u===null){u=d;try{r=d.stateNode,c?(s=r.style,typeof s.setProperty=="function"?s.setProperty("display","none","important"):s.display="none"):(a=d.stateNode,l=d.memoizedProps.style,o=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=XT("display",o))}catch(g){It(i,i.return,g)}}}else if(d.tag===6){if(u===null)try{d.stateNode.nodeValue=c?"":d.memoizedProps}catch(g){It(i,i.return,g)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===i)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===i)break e;for(;d.sibling===null;){if(d.return===null||d.return===i)break e;u===d&&(u=null),d=d.return}u===d&&(u=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:vn(e,i),Fn(i),n&4&&pb(i);break;case 21:break;default:vn(e,i),Fn(i)}}function Fn(i){var e=i.flags;if(e&2){try{e:{for(var t=i.return;t!==null;){if(db(t)){var n=t;break e}t=t.return}throw Error(ae(160))}switch(n.tag){case 5:var r=n.stateNode;n.flags&32&&(Ya(r,""),n.flags&=-33);var s=hb(i);Mg(i,s,r);break;case 3:case 4:var o=n.stateNode.containerInfo,a=hb(i);Og(i,a,o);break;default:throw Error(ae(161))}}catch(l){It(i,i.return,l)}i.flags&=-3}e&4096&&(i.flags&=-4097)}function H2(i,e,t){Se=i,mb(i)}function mb(i,e,t){for(var n=(i.mode&1)!==0;Se!==null;){var r=Se,s=r.child;if(r.tag===22&&n){var o=r.memoizedState!==null||Au;if(!o){var a=r.alternate,l=a!==null&&a.memoizedState!==null||ni;a=Au;var c=ni;if(Au=o,(ni=l)&&!c)for(Se=r;Se!==null;)o=Se,l=o.child,o.tag===22&&o.memoizedState!==null?Sb(r):l!==null?(l.return=o,Se=l):Sb(r);for(;s!==null;)Se=s,mb(s),s=s.sibling;Se=r,Au=a,ni=c}vb(i)}else r.subtreeFlags&8772&&s!==null?(s.return=r,Se=s):vb(i)}}function vb(i){for(;Se!==null;){var e=Se;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:ni||Ru(5,e);break;case 1:var n=e.stateNode;if(e.flags&4&&!ni)if(t===null)n.componentDidMount();else{var r=e.elementType===e.type?t.memoizedProps:gn(e.type,t.memoizedProps);n.componentDidUpdate(r,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&yw(e,s,n);break;case 3:var o=e.updateQueue;if(o!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}yw(e,o,t)}break;case 5:var a=e.stateNode;if(t===null&&e.flags&4){t=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&t.focus();break;case"img":l.src&&(t.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var d=u.dehydrated;d!==null&&ol(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(ae(163))}ni||e.flags&512&&Dg(e)}catch(h){It(e,e.return,h)}}if(e===i){Se=null;break}if(t=e.sibling,t!==null){t.return=e.return,Se=t;break}Se=e.return}}function yb(i){for(;Se!==null;){var e=Se;if(e===i){Se=null;break}var t=e.sibling;if(t!==null){t.return=e.return,Se=t;break}Se=e.return}}function Sb(i){for(;Se!==null;){var e=Se;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{Ru(4,e)}catch(l){It(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var r=e.return;try{n.componentDidMount()}catch(l){It(e,r,l)}}var s=e.return;try{Dg(e)}catch(l){It(e,s,l)}break;case 5:var o=e.return;try{Dg(e)}catch(l){It(e,o,l)}}}catch(l){It(e,e.return,l)}if(e===i){Se=null;break}var a=e.sibling;if(a!==null){a.return=e.return,Se=a;break}Se=e.return}}var z2=Math.ceil,Cu=cr.ReactCurrentDispatcher,Fg=cr.ReactCurrentOwner,en=cr.ReactCurrentBatchConfig,Je=0,Gt=null,Mt=null,Qt=0,Ui=0,Qo=jr(0),Ut=0,Il=null,Vs=0,Iu=0,Ng=0,Pl=null,_i=null,Bg=0,Jo=1/0,vr=null,Pu=!1,Ug=null,Qr=null,Lu=!1,Jr=null,ku=0,Ll=0,$g=null,Du=-1,Ou=0;function di(){return Je&6?Lt():Du!==-1?Du:Du=Lt()}function es(i){return i.mode&1?Je&2&&Qt!==0?Qt&-Qt:_2.transition!==null?(Ou===0&&(Ou=hE()),Ou):(i=nt,i!==0||(i=window.event,i=i===void 0?16:TE(i.type)),i):1}function yn(i,e,t,n){if(50<Ll)throw Ll=0,$g=null,Error(ae(185));tl(i,t,n),(!(Je&2)||i!==Gt)&&(i===Gt&&(!(Je&2)&&(Iu|=t),Ut===4&&ts(i,Qt)),Ai(i,n),t===1&&Je===0&&!(e.mode&1)&&(Jo=Lt()+500,lu&&qr()))}function Ai(i,e){var t=i.callbackNode;_N(i,e);var n=Vc(i,i===Gt?Qt:0);if(n===0)t!==null&&cE(t),i.callbackNode=null,i.callbackPriority=0;else if(e=n&-n,i.callbackPriority!==e){if(t!=null&&cE(t),e===1)i.tag===0?b2(Tb.bind(null,i)):ow(Tb.bind(null,i)),x2(function(){!(Je&6)&&qr()}),t=null;else{switch(fE(n)){case 1:t=Sp;break;case 4:t=uE;break;case 16:t=Uc;break;case 536870912:t=dE;break;default:t=Uc}t=Ib(t,xb.bind(null,i))}i.callbackPriority=e,i.callbackNode=t}}function xb(i,e){if(Du=-1,Ou=0,Je&6)throw Error(ae(327));var t=i.callbackNode;if(ea()&&i.callbackNode!==t)return null;var n=Vc(i,i===Gt?Qt:0);if(n===0)return null;if(n&30||n&i.expiredLanes||e)e=Mu(i,n);else{e=n;var r=Je;Je|=2;var s=wb();(Gt!==i||Qt!==e)&&(vr=null,Jo=Lt()+500,Ws(i,e));do try{W2();break}catch(a){Eb(i,a)}while(!0);rg(),Cu.current=s,Je=r,Mt!==null?e=0:(Gt=null,Qt=0,e=Ut)}if(e!==0){if(e===2&&(r=xp(i),r!==0&&(n=r,e=Hg(i,r))),e===1)throw t=Il,Ws(i,0),ts(i,n),Ai(i,Lt()),t;if(e===6)ts(i,n);else{if(r=i.current.alternate,!(n&30)&&!V2(r)&&(e=Mu(i,n),e===2&&(s=xp(i),s!==0&&(n=s,e=Hg(i,s))),e===1))throw t=Il,Ws(i,0),ts(i,n),Ai(i,Lt()),t;switch(i.finishedWork=r,i.finishedLanes=n,e){case 0:case 1:throw Error(ae(345));case 2:js(i,_i,vr);break;case 3:if(ts(i,n),(n&130023424)===n&&(e=Bg+500-Lt(),10<e)){if(Vc(i,0)!==0)break;if(r=i.suspendedLanes,(r&n)!==n){di(),i.pingedLanes|=i.suspendedLanes&r;break}i.timeoutHandle=Kp(js.bind(null,i,_i,vr),e);break}js(i,_i,vr);break;case 4:if(ts(i,n),(n&4194240)===n)break;for(e=i.eventTimes,r=-1;0<n;){var o=31-hn(n);s=1<<o,o=e[o],o>r&&(r=o),n&=~s}if(n=r,n=Lt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*z2(n/1960))-n,10<n){i.timeoutHandle=Kp(js.bind(null,i,_i,vr),n);break}js(i,_i,vr);break;case 5:js(i,_i,vr);break;default:throw Error(ae(329))}}}return Ai(i,Lt()),i.callbackNode===t?xb.bind(null,i):null}function Hg(i,e){var t=Pl;return i.current.memoizedState.isDehydrated&&(Ws(i,e).flags|=256),i=Mu(i,e),i!==2&&(e=_i,_i=t,e!==null&&zg(e)),i}function zg(i){_i===null?_i=i:_i.push.apply(_i,i)}function V2(i){for(var e=i;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var n=0;n<t.length;n++){var r=t[n],s=r.getSnapshot;r=r.value;try{if(!fn(s(),r))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===i)break;for(;e.sibling===null;){if(e.return===null||e.return===i)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function ts(i,e){for(e&=~Ng,e&=~Iu,i.suspendedLanes|=e,i.pingedLanes&=~e,i=i.expirationTimes;0<e;){var t=31-hn(e),n=1<<t;i[t]=-1,e&=~n}}function Tb(i){if(Je&6)throw Error(ae(327));ea();var e=Vc(i,0);if(!(e&1))return Ai(i,Lt()),null;var t=Mu(i,e);if(i.tag!==0&&t===2){var n=xp(i);n!==0&&(e=n,t=Hg(i,n))}if(t===1)throw t=Il,Ws(i,0),ts(i,e),Ai(i,Lt()),t;if(t===6)throw Error(ae(345));return i.finishedWork=i.current.alternate,i.finishedLanes=e,js(i,_i,vr),Ai(i,Lt()),null}function Vg(i,e){var t=Je;Je|=1;try{return i(e)}finally{Je=t,Je===0&&(Jo=Lt()+500,lu&&qr())}}function Gs(i){Jr!==null&&Jr.tag===0&&!(Je&6)&&ea();var e=Je;Je|=1;var t=en.transition,n=nt;try{if(en.transition=null,nt=1,i)return i()}finally{nt=n,en.transition=t,Je=e,!(Je&6)&&qr()}}function Gg(){Ui=Qo.current,vt(Qo)}function Ws(i,e){i.finishedWork=null,i.finishedLanes=0;var t=i.timeoutHandle;if(t!==-1&&(i.timeoutHandle=-1,S2(t)),Mt!==null)for(t=Mt.return;t!==null;){var n=t;switch(Jp(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&ou();break;case 3:Yo(),vt(Ei),vt(ei),hg();break;case 5:ug(n);break;case 4:Yo();break;case 13:vt(At);break;case 19:vt(At);break;case 10:sg(n.type._context);break;case 22:case 23:Gg()}t=t.return}if(Gt=i,Mt=i=is(i.current,null),Qt=Ui=e,Ut=0,Il=null,Ng=Iu=Vs=0,_i=Pl=null,$s!==null){for(e=0;e<$s.length;e++)if(t=$s[e],n=t.interleaved,n!==null){t.interleaved=null;var r=n.next,s=t.pending;if(s!==null){var o=s.next;s.next=r,n.next=o}t.pending=n}$s=null}return i}function Eb(i,e){do{var t=Mt;try{if(rg(),yu.current=Eu,Su){for(var n=Rt.memoizedState;n!==null;){var r=n.queue;r!==null&&(r.pending=null),n=n.next}Su=!1}if(zs=0,Vt=Bt=Rt=null,wl=!1,bl=0,Fg.current=null,t===null||t.return===null){Ut=1,Il=e,Mt=null;break}e:{var s=i,o=t.return,a=t,l=e;if(e=Qt,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var c=l,u=a,d=u.tag;if(!(u.mode&1)&&(d===0||d===11||d===15)){var h=u.alternate;h?(u.updateQueue=h.updateQueue,u.memoizedState=h.memoizedState,u.lanes=h.lanes):(u.updateQueue=null,u.memoizedState=null)}var f=Kw(o);if(f!==null){f.flags&=-257,qw(f,o,a,s,e),f.mode&1&&jw(s,c,e),e=f,l=c;var p=e.updateQueue;if(p===null){var g=new Set;g.add(l),e.updateQueue=g}else p.add(l);break e}else{if(!(e&1)){jw(s,c,e),Wg();break e}l=Error(ae(426))}}else if(St&&a.mode&1){var m=Kw(o);if(m!==null){!(m.flags&65536)&&(m.flags|=256),qw(m,o,a,s,e),ig(Xo(l,a));break e}}s=l=Xo(l,a),Ut!==4&&(Ut=2),Pl===null?Pl=[s]:Pl.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var v=Gw(s,l,e);vw(s,v);break e;case 1:a=l;var y=s.type,S=s.stateNode;if(!(s.flags&128)&&(typeof y.getDerivedStateFromError=="function"||S!==null&&typeof S.componentDidCatch=="function"&&(Qr===null||!Qr.has(S)))){s.flags|=65536,e&=-e,s.lanes|=e;var x=Ww(s,a,e);vw(s,x);break e}}s=s.return}while(s!==null)}_b(t)}catch(E){e=E,Mt===t&&t!==null&&(Mt=t=t.return);continue}break}while(!0)}function wb(){var i=Cu.current;return Cu.current=Eu,i===null?Eu:i}function Wg(){(Ut===0||Ut===3||Ut===2)&&(Ut=4),Gt===null||!(Vs&268435455)&&!(Iu&268435455)||ts(Gt,Qt)}function Mu(i,e){var t=Je;Je|=2;var n=wb();(Gt!==i||Qt!==e)&&(vr=null,Ws(i,e));do try{G2();break}catch(r){Eb(i,r)}while(!0);if(rg(),Je=t,Cu.current=n,Mt!==null)throw Error(ae(261));return Gt=null,Qt=0,Ut}function G2(){for(;Mt!==null;)bb(Mt)}function W2(){for(;Mt!==null&&!mN();)bb(Mt)}function bb(i){var e=Cb(i.alternate,i,Ui);i.memoizedProps=i.pendingProps,e===null?_b(i):Mt=e,Fg.current=null}function _b(i){var e=i;do{var t=e.alternate;if(i=e.return,e.flags&32768){if(t=B2(t,e),t!==null){t.flags&=32767,Mt=t;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Ut=6,Mt=null;return}}else if(t=N2(t,e,Ui),t!==null){Mt=t;return}if(e=e.sibling,e!==null){Mt=e;return}Mt=e=i}while(e!==null);Ut===0&&(Ut=5)}function js(i,e,t){var n=nt,r=en.transition;try{en.transition=null,nt=1,j2(i,e,t,n)}finally{en.transition=r,nt=n}return null}function j2(i,e,t,n){do ea();while(Jr!==null);if(Je&6)throw Error(ae(327));t=i.finishedWork;var r=i.finishedLanes;if(t===null)return null;if(i.finishedWork=null,i.finishedLanes=0,t===i.current)throw Error(ae(177));i.callbackNode=null,i.callbackPriority=0;var s=t.lanes|t.childLanes;if(AN(i,s),i===Gt&&(Mt=Gt=null,Qt=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||Lu||(Lu=!0,Ib(Uc,function(){return ea(),null})),s=(t.flags&15990)!==0,t.subtreeFlags&15990||s){s=en.transition,en.transition=null;var o=nt;nt=1;var a=Je;Je|=4,Fg.current=null,$2(i,t),gb(t,i),h2(Wp),jc=!!Gp,Wp=Gp=null,i.current=t,H2(t),vN(),Je=a,nt=o,en.transition=s}else i.current=t;if(Lu&&(Lu=!1,Jr=i,ku=r),s=i.pendingLanes,s===0&&(Qr=null),xN(t.stateNode),Ai(i,Lt()),e!==null)for(n=i.onRecoverableError,t=0;t<e.length;t++)r=e[t],n(r.value,{componentStack:r.stack,digest:r.digest});if(Pu)throw Pu=!1,i=Ug,Ug=null,i;return ku&1&&i.tag!==0&&ea(),s=i.pendingLanes,s&1?i===$g?Ll++:(Ll=0,$g=i):Ll=0,qr(),null}function ea(){if(Jr!==null){var i=fE(ku),e=en.transition,t=nt;try{if(en.transition=null,nt=16>i?16:i,Jr===null)var n=!1;else{if(i=Jr,Jr=null,ku=0,Je&6)throw Error(ae(331));var r=Je;for(Je|=4,Se=i.current;Se!==null;){var s=Se,o=s.child;if(Se.flags&16){var a=s.deletions;if(a!==null){for(var l=0;l<a.length;l++){var c=a[l];for(Se=c;Se!==null;){var u=Se;switch(u.tag){case 0:case 11:case 15:Cl(8,u,s)}var d=u.child;if(d!==null)d.return=u,Se=d;else for(;Se!==null;){u=Se;var h=u.sibling,f=u.return;if(ub(u),u===c){Se=null;break}if(h!==null){h.return=f,Se=h;break}Se=f}}}var p=s.alternate;if(p!==null){var g=p.child;if(g!==null){p.child=null;do{var m=g.sibling;g.sibling=null,g=m}while(g!==null)}}Se=s}}if(s.subtreeFlags&2064&&o!==null)o.return=s,Se=o;else e:for(;Se!==null;){if(s=Se,s.flags&2048)switch(s.tag){case 0:case 11:case 15:Cl(9,s,s.return)}var v=s.sibling;if(v!==null){v.return=s.return,Se=v;break e}Se=s.return}}var y=i.current;for(Se=y;Se!==null;){o=Se;var S=o.child;if(o.subtreeFlags&2064&&S!==null)S.return=o,Se=S;else e:for(o=y;Se!==null;){if(a=Se,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:Ru(9,a)}}catch(E){It(a,a.return,E)}if(a===o){Se=null;break e}var x=a.sibling;if(x!==null){x.return=a.return,Se=x;break e}Se=a.return}}if(Je=r,qr(),kn&&typeof kn.onPostCommitFiberRoot=="function")try{kn.onPostCommitFiberRoot($c,i)}catch{}n=!0}return n}finally{nt=t,en.transition=e}}return!1}function Ab(i,e,t){e=Xo(t,e),e=Gw(i,e,1),i=Xr(i,e,1),e=di(),i!==null&&(tl(i,1,e),Ai(i,e))}function It(i,e,t){if(i.tag===3)Ab(i,i,t);else for(;e!==null;){if(e.tag===3){Ab(e,i,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Qr===null||!Qr.has(n))){i=Xo(t,i),i=Ww(e,i,1),e=Xr(e,i,1),i=di(),e!==null&&(tl(e,1,i),Ai(e,i));break}}e=e.return}}function K2(i,e,t){var n=i.pingCache;n!==null&&n.delete(e),e=di(),i.pingedLanes|=i.suspendedLanes&t,Gt===i&&(Qt&t)===t&&(Ut===4||Ut===3&&(Qt&130023424)===Qt&&500>Lt()-Bg?Ws(i,0):Ng|=t),Ai(i,e)}function Rb(i,e){e===0&&(i.mode&1?(e=zc,zc<<=1,!(zc&130023424)&&(zc=4194304)):e=1);var t=di();i=pr(i,e),i!==null&&(tl(i,e,t),Ai(i,t))}function q2(i){var e=i.memoizedState,t=0;e!==null&&(t=e.retryLane),Rb(i,t)}function Y2(i,e){var t=0;switch(i.tag){case 13:var n=i.stateNode,r=i.memoizedState;r!==null&&(t=r.retryLane);break;case 19:n=i.stateNode;break;default:throw Error(ae(314))}n!==null&&n.delete(e),Rb(i,t)}var Cb;Cb=function(i,e,t){if(i!==null)if(i.memoizedProps!==e.pendingProps||Ei.current)bi=!0;else{if(!(i.lanes&t)&&!(e.flags&128))return bi=!1,F2(i,e,t);bi=!!(i.flags&131072)}else bi=!1,St&&e.flags&1048576&&aw(e,uu,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;_u(i,e),i=e.pendingProps;var r=zo(e,ei.current);qo(e,t),r=gg(null,e,n,i,r,t);var s=mg();return e.flags|=1,typeof r=="object"&&r!==null&&typeof r.render=="function"&&r.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,wi(n)?(s=!0,au(e)):s=!1,e.memoizedState=r.state!==null&&r.state!==void 0?r.state:null,lg(e),r.updater=wu,e.stateNode=r,r._reactInternals=e,Eg(e,n,i,t),e=Ag(null,e,n,!0,s,t)):(e.tag=0,St&&s&&Qp(e),ui(null,e,r,t),e=e.child),e;case 16:n=e.elementType;e:{switch(_u(i,e),i=e.pendingProps,r=n._init,n=r(n._payload),e.type=n,r=e.tag=Z2(n),i=gn(n,i),r){case 0:e=_g(null,e,n,i,t);break e;case 1:e=eb(null,e,n,i,t);break e;case 11:e=Yw(null,e,n,i,t);break e;case 14:e=Xw(null,e,n,gn(n.type,i),t);break e}throw Error(ae(306,n,""))}return e;case 0:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:gn(n,r),_g(i,e,n,r,t);case 1:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:gn(n,r),eb(i,e,n,r,t);case 3:e:{if(tb(e),i===null)throw Error(ae(387));n=e.pendingProps,s=e.memoizedState,r=s.element,mw(i,e),mu(e,n,null,t);var o=e.memoizedState;if(n=o.element,s.isDehydrated)if(s={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){r=Xo(Error(ae(423)),e),e=ib(i,e,n,t,r);break e}else if(n!==r){r=Xo(Error(ae(424)),e),e=ib(i,e,n,t,r);break e}else for(Bi=Wr(e.stateNode.containerInfo.firstChild),Ni=e,St=!0,pn=null,t=pw(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Wo(),n===r){e=mr(i,e,t);break e}ui(i,e,n,t)}e=e.child}return e;case 5:return Sw(e),i===null&&tg(e),n=e.type,r=e.pendingProps,s=i!==null?i.memoizedProps:null,o=r.children,jp(n,r)?o=null:s!==null&&jp(n,s)&&(e.flags|=32),Jw(i,e),ui(i,e,o,t),e.child;case 6:return i===null&&tg(e),null;case 13:return nb(i,e,t);case 4:return cg(e,e.stateNode.containerInfo),n=e.pendingProps,i===null?e.child=jo(e,null,n,t):ui(i,e,n,t),e.child;case 11:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:gn(n,r),Yw(i,e,n,r,t);case 7:return ui(i,e,e.pendingProps,t),e.child;case 8:return ui(i,e,e.pendingProps.children,t),e.child;case 12:return ui(i,e,e.pendingProps.children,t),e.child;case 10:e:{if(n=e.type._context,r=e.pendingProps,s=e.memoizedProps,o=r.value,ft(fu,n._currentValue),n._currentValue=o,s!==null)if(fn(s.value,o)){if(s.children===r.children&&!Ei.current){e=mr(i,e,t);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===n){if(s.tag===1){l=gr(-1,t&-t),l.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}s.lanes|=t,l=s.alternate,l!==null&&(l.lanes|=t),og(s.return,t,e),a.lanes|=t;break}l=l.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(ae(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),og(o,t,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}ui(i,e,r.children,t),e=e.child}return e;case 9:return r=e.type,n=e.pendingProps.children,qo(e,t),r=Qi(r),n=n(r),e.flags|=1,ui(i,e,n,t),e.child;case 14:return n=e.type,r=gn(n,e.pendingProps),r=gn(n.type,r),Xw(i,e,n,r,t);case 15:return Zw(i,e,e.type,e.pendingProps,t);case 17:return n=e.type,r=e.pendingProps,r=e.elementType===n?r:gn(n,r),_u(i,e),e.tag=1,wi(n)?(i=!0,au(e)):i=!1,qo(e,t),zw(e,n,r),Eg(e,n,r,t),Ag(null,e,n,!0,i,t);case 19:return sb(i,e,t);case 22:return Qw(i,e,t)}throw Error(ae(156,e.tag))};function Ib(i,e){return lE(i,e)}function X2(i,e,t,n){this.tag=i,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function tn(i,e,t,n){return new X2(i,e,t,n)}function jg(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Z2(i){if(typeof i=="function")return jg(i)?1:0;if(i!=null){if(i=i.$$typeof,i===Qf)return 11;if(i===tp)return 14}return 2}function is(i,e){var t=i.alternate;return t===null?(t=tn(i.tag,e,i.key,i.mode),t.elementType=i.elementType,t.type=i.type,t.stateNode=i.stateNode,t.alternate=i,i.alternate=t):(t.pendingProps=e,t.type=i.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=i.flags&14680064,t.childLanes=i.childLanes,t.lanes=i.lanes,t.child=i.child,t.memoizedProps=i.memoizedProps,t.memoizedState=i.memoizedState,t.updateQueue=i.updateQueue,e=i.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=i.sibling,t.index=i.index,t.ref=i.ref,t}function Fu(i,e,t,n,r,s){var o=2;if(n=i,typeof i=="function")jg(i)&&(o=1);else if(typeof i=="string")o=5;else e:switch(i){case Io:return Ks(t.children,r,s,e);case Xf:o=8,r|=8;break;case Zf:return i=tn(12,t,e,r|2),i.elementType=Zf,i.lanes=s,i;case Jf:return i=tn(13,t,e,r),i.elementType=Jf,i.lanes=s,i;case ep:return i=tn(19,t,e,r),i.elementType=ep,i.lanes=s,i;case BT:return Nu(t,r,s,e);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case FT:o=10;break e;case NT:o=9;break e;case Qf:o=11;break e;case tp:o=14;break e;case Nr:o=16,n=null;break e}throw Error(ae(130,i==null?i:typeof i,""))}return e=tn(o,t,e,r),e.elementType=i,e.type=n,e.lanes=s,e}function Ks(i,e,t,n){return i=tn(7,i,n,e),i.lanes=t,i}function Nu(i,e,t,n){return i=tn(22,i,n,e),i.elementType=BT,i.lanes=t,i.stateNode={isHidden:!1},i}function Kg(i,e,t){return i=tn(6,i,null,e),i.lanes=t,i}function qg(i,e,t){return e=tn(4,i.children!==null?i.children:[],i.key,e),e.lanes=t,e.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},e}function Q2(i,e,t,n,r){this.tag=e,this.containerInfo=i,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Tp(0),this.expirationTimes=Tp(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Tp(0),this.identifierPrefix=n,this.onRecoverableError=r,this.mutableSourceEagerHydrationData=null}function Yg(i,e,t,n,r,s,o,a,l){return i=new Q2(i,e,t,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=tn(3,null,null,e),i.current=s,s.stateNode=i,s.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},lg(s),i}function J2(i,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Co,key:n==null?null:""+n,children:i,containerInfo:e,implementation:t}}function Pb(i){if(!i)return Kr;i=i._reactInternals;e:{if(Ms(i)!==i||i.tag!==1)throw Error(ae(170));var e=i;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(wi(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(ae(171))}if(i.tag===1){var t=i.type;if(wi(t))return rw(i,t,e)}return e}function Lb(i,e,t,n,r,s,o,a,l){return i=Yg(t,n,!0,i,r,s,o,a,l),i.context=Pb(null),t=i.current,n=di(),r=es(t),s=gr(n,r),s.callback=e??null,Xr(t,s,r),i.current.lanes=r,tl(i,r,n),Ai(i,n),i}function Bu(i,e,t,n){var r=e.current,s=di(),o=es(r);return t=Pb(t),e.context===null?e.context=t:e.pendingContext=t,e=gr(s,o),e.payload={element:i},n=n===void 0?null:n,n!==null&&(e.callback=n),i=Xr(r,e,o),i!==null&&(yn(i,r,o,s),gu(i,r,o)),o}function Uu(i){if(i=i.current,!i.child)return null;switch(i.child.tag){case 5:return i.child.stateNode;default:return i.child.stateNode}}function kb(i,e){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var t=i.retryLane;i.retryLane=t!==0&&t<e?t:e}}function Xg(i,e){kb(i,e),(i=i.alternate)&&kb(i,e)}function eB(){return null}var Db=typeof reportError=="function"?reportError:function(i){console.error(i)};function Zg(i){this._internalRoot=i}$u.prototype.render=Zg.prototype.render=function(i){var e=this._internalRoot;if(e===null)throw Error(ae(409));Bu(i,e,null,null)},$u.prototype.unmount=Zg.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var e=i.containerInfo;Gs(function(){Bu(null,i,null,null)}),e[ur]=null}};function $u(i){this._internalRoot=i}$u.prototype.unstable_scheduleHydration=function(i){if(i){var e=mE();i={blockedOn:null,target:i,priority:e};for(var t=0;t<zr.length&&e!==0&&e<zr[t].priority;t++);zr.splice(t,0,i),t===0&&SE(i)}};function Qg(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function Hu(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function Ob(){}function tB(i,e,t,n,r){if(r){if(typeof n=="function"){var s=n;n=function(){var c=Uu(o);s.call(c)}}var o=Lb(e,n,i,0,null,!1,!1,"",Ob);return i._reactRootContainer=o,i[ur]=o.current,gl(i.nodeType===8?i.parentNode:i),Gs(),o}for(;r=i.lastChild;)i.removeChild(r);if(typeof n=="function"){var a=n;n=function(){var c=Uu(l);a.call(c)}}var l=Yg(i,0,!1,null,null,!1,!1,"",Ob);return i._reactRootContainer=l,i[ur]=l.current,gl(i.nodeType===8?i.parentNode:i),Gs(function(){Bu(e,l,t,n)}),l}function zu(i,e,t,n,r){var s=t._reactRootContainer;if(s){var o=s;if(typeof r=="function"){var a=r;r=function(){var l=Uu(o);a.call(l)}}Bu(e,o,i,r)}else o=tB(t,e,i,r,n);return Uu(o)}pE=function(i){switch(i.tag){case 3:var e=i.stateNode;if(e.current.memoizedState.isDehydrated){var t=el(e.pendingLanes);t!==0&&(Ep(e,t|1),Ai(e,Lt()),!(Je&6)&&(Jo=Lt()+500,qr()))}break;case 13:Gs(function(){var n=pr(i,1);if(n!==null){var r=di();yn(n,i,1,r)}}),Xg(i,1)}},wp=function(i){if(i.tag===13){var e=pr(i,134217728);if(e!==null){var t=di();yn(e,i,134217728,t)}Xg(i,134217728)}},gE=function(i){if(i.tag===13){var e=es(i),t=pr(i,e);if(t!==null){var n=di();yn(t,i,e,n)}Xg(i,e)}},mE=function(){return nt},vE=function(i,e){var t=nt;try{return nt=i,e()}finally{nt=t}},gp=function(i,e,t){switch(e){case"input":if(ap(i,t),e=t.name,t.type==="radio"&&e!=null){for(t=i;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var n=t[e];if(n!==i&&n.form===i.form){var r=su(n);if(!r)throw Error(ae(90));HT(n),ap(n,r)}}}break;case"textarea":jT(i,t);break;case"select":e=t.value,e!=null&&Po(i,!!t.multiple,e,!1)}},tE=Vg,iE=Gs;var iB={usingClientEntryPoint:!1,Events:[yl,$o,su,JT,eE,Vg]},kl={findFiberByHostInstance:Fs,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},nB={bundleType:kl.bundleType,version:kl.version,rendererPackageName:kl.rendererPackageName,rendererConfig:kl.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:cr.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=oE(i),i===null?null:i.stateNode},findFiberByHostInstance:kl.findFiberByHostInstance||eB,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Vu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Vu.isDisabled&&Vu.supportsFiber)try{$c=Vu.inject(nB),kn=Vu}catch{}}Oi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=iB,Oi.createPortal=function(i,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Qg(e))throw Error(ae(200));return J2(i,e,null,t)},Oi.createRoot=function(i,e){if(!Qg(i))throw Error(ae(299));var t=!1,n="",r=Db;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(r=e.onRecoverableError)),e=Yg(i,1,!1,null,null,t,!1,n,r),i[ur]=e.current,gl(i.nodeType===8?i.parentNode:i),new Zg(e)},Oi.findDOMNode=function(i){if(i==null)return null;if(i.nodeType===1)return i;var e=i._reactInternals;if(e===void 0)throw typeof i.render=="function"?Error(ae(188)):(i=Object.keys(i).join(","),Error(ae(268,i)));return i=oE(e),i=i===null?null:i.stateNode,i},Oi.flushSync=function(i){return Gs(i)},Oi.hydrate=function(i,e,t){if(!Hu(e))throw Error(ae(200));return zu(null,i,e,!0,t)},Oi.hydrateRoot=function(i,e,t){if(!Qg(i))throw Error(ae(405));var n=t!=null&&t.hydratedSources||null,r=!1,s="",o=Db;if(t!=null&&(t.unstable_strictMode===!0&&(r=!0),t.identifierPrefix!==void 0&&(s=t.identifierPrefix),t.onRecoverableError!==void 0&&(o=t.onRecoverableError)),e=Lb(e,null,i,1,t??null,r,!1,s,o),i[ur]=e.current,gl(i),n)for(i=0;i<n.length;i++)t=n[i],r=t._getVersion,r=r(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,r]:e.mutableSourceEagerHydrationData.push(t,r);return new $u(e)},Oi.render=function(i,e,t){if(!Hu(e))throw Error(ae(200));return zu(null,i,e,!1,t)},Oi.unmountComponentAtNode=function(i){if(!Hu(i))throw Error(ae(40));return i._reactRootContainer?(Gs(function(){zu(null,null,i,!1,function(){i._reactRootContainer=null,i[ur]=null})}),!0):!1},Oi.unstable_batchedUpdates=Vg,Oi.unstable_renderSubtreeIntoContainer=function(i,e,t,n){if(!Hu(t))throw Error(ae(200));if(i==null||i._reactInternals===void 0)throw Error(ae(38));return zu(i,e,t,!1,n)},Oi.version="18.3.1-next-f1338f8080-20240426";function Mb(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Mb)}catch(i){console.error(i)}}Mb(),PT.exports=Oi;var Dl=PT.exports;const rB=Dy(Dl);function Ol(i){const e=sB(i),t=me((n,r)=>{const{children:s,...o}=n,a=xi.toArray(s),l=a.find(aB);if(l){const c=l.props.children,u=a.map(d=>d===l?xi.count(c)>1?xi.only(null):ki(c)?c.props.children:null:d);return T(e,{...o,ref:r,children:ki(c)?tr(c,void 0,u):null})}return T(e,{...o,ref:r,children:s})});return t.displayName=`${i}.Slot`,t}function sB(i){const e=me((t,n)=>{const{children:r,...s}=t;if(ki(r)){const o=cB(r),a=lB(s,r.props);return r.type!==Ee&&(a.ref=n?IT(n,o):o),tr(r,a)}return xi.count(r)>1?xi.only(null):null});return e.displayName=`${i}.SlotClone`,e}var oB=Symbol("radix.slottable");function aB(i){return ki(i)&&typeof i.type=="function"&&"__radixId"in i.type&&i.type.__radixId===oB}function lB(i,e){const t={...e};for(const n in e){const r=i[n],s=e[n];/^on[A-Z]/.test(n)?r&&s?t[n]=(...a)=>{const l=s(...a);return r(...a),l}:r&&(t[n]=r):n==="style"?t[n]={...r,...s}:n==="className"&&(t[n]=[r,s].filter(Boolean).join(" "))}return{...i,...t}}function cB(i){var n,r;let e=(n=Object.getOwnPropertyDescriptor(i.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?i.ref:(e=(r=Object.getOwnPropertyDescriptor(i,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?i.props.ref:i.props.ref||i.ref)}var uB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],je=uB.reduce((i,e)=>{const t=Ol(`Primitive.${e}`),n=me((r,s)=>{const{asChild:o,...a}=r,l=o?t:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),T(l,{...a,ref:s})});return n.displayName=`Primitive.${e}`,{...i,[e]:n}},{});function dB(i,e){i&&Dl.flushSync(()=>i.dispatchEvent(e))}function hB(i,e){return ho((t,n)=>e[t][n]??t,i)}var Ml=i=>{const{present:e,children:t}=i,n=fB(e),r=typeof t=="function"?t({present:n.isPresent}):xi.only(t),s=ut(n.ref,pB(r));return typeof t=="function"||n.isPresent?tr(r,{ref:s}):null};Ml.displayName="Presence";function fB(i){const[e,t]=se(),n=ge(null),r=ge(i),s=ge("none"),o=i?"mounted":"unmounted",[a,l]=hB(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ne(()=>{const c=Gu(n.current);s.current=a==="mounted"?c:"none"},[a]),Yt(()=>{const c=n.current,u=r.current;if(u!==i){const h=s.current,f=Gu(c);i?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&h!==f?"ANIMATION_OUT":"UNMOUNT"),r.current=i}},[i,l]),Yt(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=f=>{const g=Gu(n.current).includes(CSS.escape(f.animationName));if(f.target===e&&g&&(l("ANIMATION_END"),!r.current)){const m=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=m)})}},h=f=>{f.target===e&&(s.current=Gu(n.current))};return e.addEventListener("animationstart",h),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",h),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:Ce(c=>{n.current=c?getComputedStyle(c):null,t(c)},[])}}function Gu(i){return(i==null?void 0:i.animationName)||"none"}function pB(i){var n,r;let e=(n=Object.getOwnPropertyDescriptor(i.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?i.ref:(e=(r=Object.getOwnPropertyDescriptor(i,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?i.props.ref:i.props.ref||i.ref)}var gB=vc[" useId ".trim().toString()]||(()=>{}),mB=0;function qs(i){const[e,t]=se(gB());return Yt(()=>{t(n=>n??String(mB++))},[i]),i||(e?`radix-${e}`:"")}var Wu="Collapsible",[vB]=Ln(Wu),[yB,Jg]=vB(Wu),Fb=me((i,e)=>{const{__scopeCollapsible:t,open:n,defaultOpen:r,disabled:s,onOpenChange:o,...a}=i,[l,c]=Fr({prop:n,defaultProp:r??!1,onChange:o,caller:Wu});return T(yB,{scope:t,disabled:s,contentId:qs(),open:l,onOpenToggle:Ce(()=>c(u=>!u),[c]),children:T(je.div,{"data-state":tm(l),"data-disabled":s?"":void 0,...a,ref:e})})});Fb.displayName=Wu;var Nb="CollapsibleTrigger",SB=me((i,e)=>{const{__scopeCollapsible:t,...n}=i,r=Jg(Nb,t);return T(je.button,{type:"button","aria-controls":r.contentId,"aria-expanded":r.open||!1,"data-state":tm(r.open),"data-disabled":r.disabled?"":void 0,disabled:r.disabled,...n,ref:e,onClick:Ge(i.onClick,r.onOpenToggle)})});SB.displayName=Nb;var em="CollapsibleContent",xB=me((i,e)=>{const{forceMount:t,...n}=i,r=Jg(em,i.__scopeCollapsible);return T(Ml,{present:t||r.open,children:({present:s})=>T(TB,{...n,ref:e,present:s})})});xB.displayName=em;var TB=me((i,e)=>{const{__scopeCollapsible:t,present:n,children:r,...s}=i,o=Jg(em,t),[a,l]=se(n),c=ge(null),u=ut(e,c),d=ge(0),h=d.current,f=ge(0),p=f.current,g=o.open||a,m=ge(g),v=ge(void 0);return ne(()=>{const y=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(y)},[]),Yt(()=>{const y=c.current;if(y){v.current=v.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const S=y.getBoundingClientRect();d.current=S.height,f.current=S.width,m.current||(y.style.transitionDuration=v.current.transitionDuration,y.style.animationName=v.current.animationName),l(n)}},[o.open,n]),T(je.div,{"data-state":tm(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!g,...s,ref:u,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":p?`${p}px`:void 0,...i.style},children:g&&r})});function tm(i){return i?"open":"closed"}var EB=Fb;const wB=async(i,e)=>{const t=i.get({id:e,type:"Canvas"});if(!(t!=null&&t.annotations)||!t.annotations[0])return[];const r=i.get(t.annotations).filter(o=>o.items?o:!1),s=[];for(const o of r)if(o.items.length>0){const a=o.label||{none:["Annotations"]};s.push({...o,label:a})}else{let a={};try{a=await i.load(o.id)}catch(l){console.log(l)}if(a.items&&a.items.length>0){const l=a.label||{none:["Annotations"]};s.push({...a,label:l})}}return s},Bb=async(i,e,t)=>{try{if(t==null||t.q==null)return{};const n=t.q.trim(),r=new URL(e);return r.searchParams.set("q",n),await i.load(r.toString())}catch(n){return console.warn("Error in getContentSearchResources:",n),{}}},Ub=(i,e,t,n)=>{var o,a;const r={canvas:void 0,accompanyingCanvas:void 0,annotationPage:void 0,annotations:[]},s=l=>{if(l){if(!l.body||!l.motivation){console.error("Invalid annotation after Hyperion parsing: missing either 'body' or 'motivation'",l);return}let c=l.body;Array.isArray(c)&&(c=c[0]);const u=i.get(c.id);if(!u)return;switch(t){case"painting":return l.target===e.id&&l.motivation&&l.motivation[0]==="painting"&&n.includes(u.type)&&(l.body=u),!!l;case"supplementing":return;default:throw new Error("Invalid annotation motivation.")}}};if(r.canvas=i.get(e),r.canvas&&(r.annotationPage=i.get(r.canvas.items[0]),r.accompanyingCanvas=(o=r.canvas)!=null&&o.accompanyingCanvas?i.get((a=r.canvas)==null?void 0:a.accompanyingCanvas):void 0),r.annotationPage){const l=i.get(r.annotationPage.items).map(u=>({body:i.get(u.body[0].id),motivation:u.motivation,type:"Annotation"})),c=[];l.forEach(u=>{u.body.type==="Choice"?u.body.items.forEach(d=>c.push({...u,id:d.id,body:i.get(d.id)})):c.push(u)}),r.annotations=c.filter(s)}return r},im=(i,e="en")=>{if(!i)return"";if(!i[e]){const t=Object.getOwnPropertyNames(i);if(t.length>0)return i[t[0]]}return i[e]},ns=(i,e)=>{const t=Ub(i,{id:e,type:"Canvas"},"painting",["Image","Sound","Video"]);if(t.annotations.length!==0&&t.annotations&&t.annotations)return t.annotations.map(n=>n==null?void 0:n.body)},bB=oe("div",{position:"relative",zIndex:"0"}),$b=oe("div",{display:"flex",flexDirection:"row",flexGrow:"1",overflow:"hidden"}),Hb=oe("div",{display:"flex",flexDirection:"column",flexGrow:"1",flexShrink:"1",width:"100%",height:"100%","&[data-aside-active='true']":{width:"61.8%","@sm":{width:"0",opacity:"0"}},"&[data-aside-toggle='false']":{"@sm":{width:"100% !important",opacity:"1 !important"}}}),_B=oe("aside",{display:"flex",flexGrow:"1",flexShrink:"0",width:"0",maxHeight:"100%","&[data-aside-active='true']":{width:"38.2%","@sm":{width:"100%"}},"&[data-aside-toggle='false']":{"@sm":{width:"0 !important"}}}),AB=oe("div",{display:"flex",flexDirection:"column",fontSmooth:"auto",webkitFontSmoothing:"antialiased",'&[data-absolute-position="true"]':{position:"absolute",width:"100%",height:"100%",zIndex:"0"},"> div":{display:"flex",flexDirection:"column",flexGrow:"1",justifyContent:"flex-start",height:"100%",maxHeight:"100%","@sm":{[`& ${$b}`]:{flexGrow:"1"},[`& ${Hb}`]:{flexGrow:"0"}}},"@sm":{padding:"0"},"&[data-information-panel-open='true']":{"@sm":{}}});function zb(i){const e=i+"CollectionProvider",[t,n]=Ln(e),[r,s]=t(e,{collectionRef:{current:null},itemMap:new Map}),o=g=>{const{scope:m,children:v}=g,y=et.useRef(null),S=et.useRef(new Map).current;return T(r,{scope:m,itemMap:S,collectionRef:y,children:v})};o.displayName=e;const a=i+"CollectionSlot",l=Ol(a),c=et.forwardRef((g,m)=>{const{scope:v,children:y}=g,S=s(a,v),x=ut(m,S.collectionRef);return T(l,{ref:x,children:y})});c.displayName=a;const u=i+"CollectionItemSlot",d="data-radix-collection-item",h=Ol(u),f=et.forwardRef((g,m)=>{const{scope:v,children:y,...S}=g,x=et.useRef(null),E=ut(m,x),C=s(u,v);return et.useEffect(()=>(C.itemMap.set(x,{ref:x,...S}),()=>void C.itemMap.delete(x))),T(h,{[d]:"",ref:E,children:y})});f.displayName=u;function p(g){const m=s(i+"CollectionConsumer",g);return et.useCallback(()=>{const y=m.collectionRef.current;if(!y)return[];const S=Array.from(y.querySelectorAll(`[${d}]`));return Array.from(m.itemMap.values()).sort((C,b)=>S.indexOf(C.ref.current)-S.indexOf(b.ref.current))},[m.collectionRef,m.itemMap])}return[{Provider:o,Slot:c,ItemSlot:f},p,n]}function rs(i){const e=ge(i);return ne(()=>{e.current=i}),Ct(()=>(...t)=>{var n;return(n=e.current)==null?void 0:n.call(e,...t)},[])}var RB=ln(void 0);function ju(i){const e=Cn(RB);return i||e||"ltr"}var nm="rovingFocusGroup.onEntryFocus",CB={bubbles:!1,cancelable:!0},Fl="RovingFocusGroup",[rm,Vb,IB]=zb(Fl),[PB,Ku]=Ln(Fl,[IB]),[LB,kB]=PB(Fl),Gb=me((i,e)=>T(rm.Provider,{scope:i.__scopeRovingFocusGroup,children:T(rm.Slot,{scope:i.__scopeRovingFocusGroup,children:T(DB,{...i,ref:e})})}));Gb.displayName=Fl;var DB=me((i,e)=>{const{__scopeRovingFocusGroup:t,orientation:n,loop:r=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=i,h=ge(null),f=ut(e,h),p=ju(s),[g,m]=Fr({prop:o,defaultProp:a??null,onChange:l,caller:Fl}),[v,y]=se(!1),S=rs(c),x=Vb(t),E=ge(!1),[C,b]=se(0);return ne(()=>{const I=h.current;if(I)return I.addEventListener(nm,S),()=>I.removeEventListener(nm,S)},[S]),T(LB,{scope:t,orientation:n,dir:p,loop:r,currentTabStopId:g,onItemFocus:Ce(I=>m(I),[m]),onItemShiftTab:Ce(()=>y(!0),[]),onFocusableItemAdd:Ce(()=>b(I=>I+1),[]),onFocusableItemRemove:Ce(()=>b(I=>I-1),[]),children:T(je.div,{tabIndex:v||C===0?-1:0,"data-orientation":n,...d,ref:f,style:{outline:"none",...i.style},onMouseDown:Ge(i.onMouseDown,()=>{E.current=!0}),onFocus:Ge(i.onFocus,I=>{const D=!E.current;if(I.target===I.currentTarget&&D&&!v){const P=new CustomEvent(nm,CB);if(I.currentTarget.dispatchEvent(P),!P.defaultPrevented){const k=x().filter(H=>H.focusable),N=k.find(H=>H.active),B=k.find(H=>H.id===g),q=[N,B,...k].filter(Boolean).map(H=>H.ref.current);Kb(q,u)}}E.current=!1}),onBlur:Ge(i.onBlur,()=>y(!1))})})}),Wb="RovingFocusGroupItem",jb=me((i,e)=>{const{__scopeRovingFocusGroup:t,focusable:n=!0,active:r=!1,tabStopId:s,children:o,...a}=i,l=qs(),c=s||l,u=kB(Wb,t),d=u.currentTabStopId===c,h=Vb(t),{onFocusableItemAdd:f,onFocusableItemRemove:p,currentTabStopId:g}=u;return ne(()=>{if(n)return f(),()=>p()},[n,f,p]),T(rm.ItemSlot,{scope:t,id:c,focusable:n,active:r,children:T(je.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:Ge(i.onMouseDown,m=>{n?u.onItemFocus(c):m.preventDefault()}),onFocus:Ge(i.onFocus,()=>u.onItemFocus(c)),onKeyDown:Ge(i.onKeyDown,m=>{if(m.key==="Tab"&&m.shiftKey){u.onItemShiftTab();return}if(m.target!==m.currentTarget)return;const v=FB(m,u.orientation,u.dir);if(v!==void 0){if(m.metaKey||m.ctrlKey||m.altKey||m.shiftKey)return;m.preventDefault();let S=h().filter(x=>x.focusable).map(x=>x.ref.current);if(v==="last")S.reverse();else if(v==="prev"||v==="next"){v==="prev"&&S.reverse();const x=S.indexOf(m.currentTarget);S=u.loop?NB(S,x+1):S.slice(x+1)}setTimeout(()=>Kb(S))}}),children:typeof o=="function"?o({isCurrentTabStop:d,hasTabStop:g!=null}):o})})});jb.displayName=Wb;var OB={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function MB(i,e){return e!=="rtl"?i:i==="ArrowLeft"?"ArrowRight":i==="ArrowRight"?"ArrowLeft":i}function FB(i,e,t){const n=MB(i.key,t);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return OB[n]}function Kb(i,e=!1){const t=document.activeElement;for(const n of i)if(n===t||(n.focus({preventScroll:e}),document.activeElement!==t))return}function NB(i,e){return i.map((t,n)=>i[(e+n)%i.length])}var qb=Gb,Yb=jb,qu="Tabs",[BB]=Ln(qu,[Ku]),Xb=Ku(),[UB,sm]=BB(qu),Zb=me((i,e)=>{const{__scopeTabs:t,value:n,onValueChange:r,defaultValue:s,orientation:o="horizontal",dir:a,activationMode:l="automatic",...c}=i,u=ju(a),[d,h]=Fr({prop:n,onChange:r,defaultProp:s??"",caller:qu});return T(UB,{scope:t,baseId:qs(),value:d,onValueChange:h,orientation:o,dir:u,activationMode:l,children:T(je.div,{dir:u,"data-orientation":o,...c,ref:e})})});Zb.displayName=qu;var Qb="TabsList",Jb=me((i,e)=>{const{__scopeTabs:t,loop:n=!0,...r}=i,s=sm(Qb,t),o=Xb(t);return T(qb,{asChild:!0,...o,orientation:s.orientation,dir:s.dir,loop:n,children:T(je.div,{role:"tablist","aria-orientation":s.orientation,...r,ref:e})})});Jb.displayName=Qb;var e1="TabsTrigger",t1=me((i,e)=>{const{__scopeTabs:t,value:n,disabled:r=!1,...s}=i,o=sm(e1,t),a=Xb(t),l=r1(o.baseId,n),c=s1(o.baseId,n),u=n===o.value;return T(Yb,{asChild:!0,...a,focusable:!r,active:u,children:T(je.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":c,"data-state":u?"active":"inactive","data-disabled":r?"":void 0,disabled:r,id:l,...s,ref:e,onMouseDown:Ge(i.onMouseDown,d=>{!r&&d.button===0&&d.ctrlKey===!1?o.onValueChange(n):d.preventDefault()}),onKeyDown:Ge(i.onKeyDown,d=>{[" ","Enter"].includes(d.key)&&o.onValueChange(n)}),onFocus:Ge(i.onFocus,()=>{const d=o.activationMode!=="manual";!u&&!r&&d&&o.onValueChange(n)})})})});t1.displayName=e1;var i1="TabsContent",n1=me((i,e)=>{const{__scopeTabs:t,value:n,forceMount:r,children:s,...o}=i,a=sm(i1,t),l=r1(a.baseId,n),c=s1(a.baseId,n),u=n===a.value,d=ge(u);return ne(()=>{const h=requestAnimationFrame(()=>d.current=!1);return()=>cancelAnimationFrame(h)},[]),T(Ml,{present:r||u,children:({present:h})=>T(je.div,{"data-state":u?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":l,hidden:!h,id:c,tabIndex:0,...o,ref:e,style:{...i.style,animationDuration:d.current?"0s":void 0},children:h&&s})})});n1.displayName=i1;function r1(i,e){return`${i}-trigger-${e}`}function s1(i,e){return`${i}-content-${e}`}var $B=Zb,HB=Jb,zB=t1,VB=n1;const GB=oe($B,{display:"flex",flexDirection:"column",width:"100%",height:"100%",flexGrow:"1",flexShrink:"0",position:"relative",zIndex:"1",maskImage:"linear-gradient(180deg, rgba(0, 0, 0, 1) calc(100% - 2rem), transparent 100%)","@sm":{marginTop:"0.5rem",boxShadow:"none"}}),WB=oe(HB,{display:"flex",flexGrow:"0",margin:"0 1.618rem",borderBottom:"5px solid #6663","@sm":{margin:"0 1rem"}}),Nl=oe(zB,{display:"flex",position:"relative",padding:"0.5rem 1.618rem",background:"none",backgroundColor:"transparent",fontFamily:"inherit",border:"none",opacity:"0.7",fontSize:"1rem",lineHeight:"1rem",whiteSpace:"nowrap",cursor:"pointer",fontWeight:400,transition:"$all","&[data-value='manifest-back']":{display:"none;","@sm":{display:"block"}},"&::after":{width:"0",height:"4px",content:"",position:"absolute",bottom:"-4px",left:"0",transition:"$all"},"&[data-state='active']":{opacity:"1",fontWeight:700,"&::after":{width:"100%",backgroundColor:"$accent"}}}),Yu=oe(VB,{display:"flex",flexDirection:"column",flexGrow:"1",flexShrink:"0",position:"absolute",top:"0",left:"0","&[data-state='active']":{width:"100%",height:"calc(100% - 2rem)",padding:"1.618rem 0"}}),jB=oe(({handleScroll:i,children:e,className:t})=>T("div",{className:t,onScroll:i,children:e}),{position:"relative",height:"100%",width:"100%",overflowY:"scroll"}),o1={position:"relative",display:"flex",margin:"0 1.618rem",padding:"0.5rem 0",fontFamily:"inherit",fontSize:"0.8333rem",lineHeight:"1.47rem",color:"inherit",background:"none",borderRadius:"3px",border:"none"},Xu=oe("button",{textAlign:"left","&:hover":{color:"$accent"}}),om=oe("div",{display:"flex",flexDirection:"column",width:"100%",header:{margin:"0 1.618rem 0.5rem ",fontWeight:700,fontSize:"0.8333rem",em:{fontStyle:"normal",fontWeight:400,opacity:.7}},paddingBottom:"1rem",marginBottom:"1rem",borderBottom:"1px solid #0001"}),Zu=oe("div",{gap:"1rem",fontSize:"1rem",lineHeight:"1.47em",margin:"0",hr:{margin:"0.618rem 0 2rem",borderColor:"transparent",height:"2px",position:"relative",zIndex:0,display:"flex",justifyContent:"flex-end",background:"rgba(102, 102, 102, 0.133)"},p:{padding:"0.5rem 0"},ul:{padding:"0.5rem 1rem"},li:{listStyleType:"disc",li:{listStyleType:"circle"}},"&[data-content-search=true]":{em:{fontWeight:700,display:"inline"}}}),KB=oe("div",{...o1,display:"flex",flexDirection:"row",gap:"1rem","&[data-format='text/vtt']":{marginTop:"-1rem","> span":{display:"none"}},"> span":{display:"flex",width:"2rem",height:"2rem",backgroundColor:"#0001",flexShrink:"0",borderRadius:"3px",marginTop:"0.25rem"},[`&[dir=rtl] ${Zu}`]:{textAlign:"right !important"}}),qB=({value:i,handleClick:e})=>T(Xu,{onClick:e,children:T(Zu,{dangerouslySetInnerHTML:{__html:i}})}),YB=({caption:i,handleClick:e,imageUri:t})=>T(Xu,{onClick:e,children:[T("img",{src:t,alt:`A visual annotation for ${i}`}),T("span",{children:i})]});/*! @license DOMPurify 3.1.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.6/LICENSE */const{entries:a1,setPrototypeOf:l1,isFrozen:XB,getPrototypeOf:ZB,getOwnPropertyDescriptor:QB}=Object;let{freeze:hi,seal:nn,create:c1}=Object,{apply:am,construct:lm}=typeof Reflect<"u"&&Reflect;hi||(hi=function(e){return e}),nn||(nn=function(e){return e}),am||(am=function(e,t,n){return e.apply(t,n)}),lm||(lm=function(e,t){return new e(...t)});const Qu=$i(Array.prototype.forEach),u1=$i(Array.prototype.pop),Bl=$i(Array.prototype.push),Ju=$i(String.prototype.toLowerCase),cm=$i(String.prototype.toString),d1=$i(String.prototype.match),Ul=$i(String.prototype.replace),JB=$i(String.prototype.indexOf),eU=$i(String.prototype.trim),Sn=$i(Object.prototype.hasOwnProperty),fi=$i(RegExp.prototype.test),$l=tU(TypeError);function $i(i){return function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return am(i,e,n)}}function tU(i){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return lm(i,t)}}function Ye(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ju;l1&&l1(i,null);let n=e.length;for(;n--;){let r=e[n];if(typeof r=="string"){const s=t(r);s!==r&&(XB(e)||(e[n]=s),r=s)}i[r]=!0}return i}function iU(i){for(let e=0;e<i.length;e++)Sn(i,e)||(i[e]=null);return i}function Ys(i){const e=c1(null);for(const[t,n]of a1(i))Sn(i,t)&&(Array.isArray(n)?e[t]=iU(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=Ys(n):e[t]=n);return e}function Hl(i,e){for(;i!==null;){const n=QB(i,e);if(n){if(n.get)return $i(n.get);if(typeof n.value=="function")return $i(n.value)}i=ZB(i)}function t(){return null}return t}const h1=hi(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),um=hi(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),dm=hi(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),nU=hi(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),hm=hi(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),rU=hi(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),f1=hi(["#text"]),p1=hi(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),fm=hi(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),g1=hi(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ed=hi(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),sU=nn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),oU=nn(/<%[\w\W]*|[\w\W]*%>/gm),aU=nn(/\${[\w\W]*}/gm),lU=nn(/^data-[\-\w.\u00B7-\uFFFF]/),cU=nn(/^aria-[\-\w]+$/),m1=nn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),uU=nn(/^(?:\w+script|data):/i),dU=nn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),v1=nn(/^html$/i),hU=nn(/^[a-z][.\w]*(-[.\w]+)+$/i);var y1=Object.freeze({__proto__:null,MUSTACHE_EXPR:sU,ERB_EXPR:oU,TMPLIT_EXPR:aU,DATA_ATTR:lU,ARIA_ATTR:cU,IS_ALLOWED_URI:m1,IS_SCRIPT_OR_DATA:uU,ATTR_WHITESPACE:dU,DOCTYPE_NAME:v1,CUSTOM_ELEMENT:hU});const zl={element:1,text:3,progressingInstruction:7,comment:8,document:9},fU=function(){return typeof window>"u"?null:window},pU=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const s="dompurify"+(n?"#"+n:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}};function S1(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fU();const e=Ie=>S1(Ie);if(e.version="3.1.6",e.removed=[],!i||!i.document||i.document.nodeType!==zl.document)return e.isSupported=!1,e;let{document:t}=i;const n=t,r=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u=i.NamedNodeMap||i.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=i,p=l.prototype,g=Hl(p,"cloneNode"),m=Hl(p,"remove"),v=Hl(p,"nextSibling"),y=Hl(p,"childNodes"),S=Hl(p,"parentNode");if(typeof o=="function"){const Ie=t.createElement("template");Ie.content&&Ie.content.ownerDocument&&(t=Ie.content.ownerDocument)}let x,E="";const{implementation:C,createNodeIterator:b,createDocumentFragment:I,getElementsByTagName:D}=t,{importNode:P}=n;let k={};e.isSupported=typeof a1=="function"&&typeof S=="function"&&C&&C.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:N,ERB_EXPR:B,TMPLIT_EXPR:K,DATA_ATTR:q,ARIA_ATTR:H,IS_SCRIPT_OR_DATA:X,ATTR_WHITESPACE:F,CUSTOM_ELEMENT:U}=y1;let{IS_ALLOWED_URI:j}=y1,V=null;const Z=Ye({},[...h1,...um,...dm,...hm,...f1]);let Q=null;const le=Ye({},[...p1,...fm,...g1,...ed]);let re=Object.seal(c1(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ye=null,de=null,Pe=!0,qe=!0,Le=!1,Fe=!0,Ue=!1,Xe=!0,it=!1,zt=!1,De=!1,w=!1,O=!1,z=!1,ie=!0,te=!1;const xe="user-content-";let he=!0,$e=!1,ze={},ce=null;const fe=Ye({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let He=null;const R=Ye({},["audio","video","img","source","image","track"]);let A=null;const L=Ye({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),M="http://www.w3.org/1998/Math/MathML",Y="http://www.w3.org/2000/svg",ee="http://www.w3.org/1999/xhtml";let be=ee,Ze=!1,ke=null;const vi=Ye({},[M,Y,ee],cm);let Et=null;const ys=["application/xhtml+xml","text/html"],Ih="text/html";let kt=null,Cr=null;const h9=t.createElement("form"),YP=function($){return $ instanceof RegExp||$ instanceof Function},P0=function(){let $=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Cr&&Cr===$)){if((!$||typeof $!="object")&&($={}),$=Ys($),Et=ys.indexOf($.PARSER_MEDIA_TYPE)===-1?Ih:$.PARSER_MEDIA_TYPE,kt=Et==="application/xhtml+xml"?cm:Ju,V=Sn($,"ALLOWED_TAGS")?Ye({},$.ALLOWED_TAGS,kt):Z,Q=Sn($,"ALLOWED_ATTR")?Ye({},$.ALLOWED_ATTR,kt):le,ke=Sn($,"ALLOWED_NAMESPACES")?Ye({},$.ALLOWED_NAMESPACES,cm):vi,A=Sn($,"ADD_URI_SAFE_ATTR")?Ye(Ys(L),$.ADD_URI_SAFE_ATTR,kt):L,He=Sn($,"ADD_DATA_URI_TAGS")?Ye(Ys(R),$.ADD_DATA_URI_TAGS,kt):R,ce=Sn($,"FORBID_CONTENTS")?Ye({},$.FORBID_CONTENTS,kt):fe,ye=Sn($,"FORBID_TAGS")?Ye({},$.FORBID_TAGS,kt):{},de=Sn($,"FORBID_ATTR")?Ye({},$.FORBID_ATTR,kt):{},ze=Sn($,"USE_PROFILES")?$.USE_PROFILES:!1,Pe=$.ALLOW_ARIA_ATTR!==!1,qe=$.ALLOW_DATA_ATTR!==!1,Le=$.ALLOW_UNKNOWN_PROTOCOLS||!1,Fe=$.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ue=$.SAFE_FOR_TEMPLATES||!1,Xe=$.SAFE_FOR_XML!==!1,it=$.WHOLE_DOCUMENT||!1,w=$.RETURN_DOM||!1,O=$.RETURN_DOM_FRAGMENT||!1,z=$.RETURN_TRUSTED_TYPE||!1,De=$.FORCE_BODY||!1,ie=$.SANITIZE_DOM!==!1,te=$.SANITIZE_NAMED_PROPS||!1,he=$.KEEP_CONTENT!==!1,$e=$.IN_PLACE||!1,j=$.ALLOWED_URI_REGEXP||m1,be=$.NAMESPACE||ee,re=$.CUSTOM_ELEMENT_HANDLING||{},$.CUSTOM_ELEMENT_HANDLING&&YP($.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(re.tagNameCheck=$.CUSTOM_ELEMENT_HANDLING.tagNameCheck),$.CUSTOM_ELEMENT_HANDLING&&YP($.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(re.attributeNameCheck=$.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),$.CUSTOM_ELEMENT_HANDLING&&typeof $.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(re.allowCustomizedBuiltInElements=$.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ue&&(qe=!1),O&&(w=!0),ze&&(V=Ye({},f1),Q=[],ze.html===!0&&(Ye(V,h1),Ye(Q,p1)),ze.svg===!0&&(Ye(V,um),Ye(Q,fm),Ye(Q,ed)),ze.svgFilters===!0&&(Ye(V,dm),Ye(Q,fm),Ye(Q,ed)),ze.mathMl===!0&&(Ye(V,hm),Ye(Q,g1),Ye(Q,ed))),$.ADD_TAGS&&(V===Z&&(V=Ys(V)),Ye(V,$.ADD_TAGS,kt)),$.ADD_ATTR&&(Q===le&&(Q=Ys(Q)),Ye(Q,$.ADD_ATTR,kt)),$.ADD_URI_SAFE_ATTR&&Ye(A,$.ADD_URI_SAFE_ATTR,kt),$.FORBID_CONTENTS&&(ce===fe&&(ce=Ys(ce)),Ye(ce,$.FORBID_CONTENTS,kt)),he&&(V["#text"]=!0),it&&Ye(V,["html","head","body"]),V.table&&(Ye(V,["tbody"]),delete ye.tbody),$.TRUSTED_TYPES_POLICY){if(typeof $.TRUSTED_TYPES_POLICY.createHTML!="function")throw $l('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof $.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw $l('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=$.TRUSTED_TYPES_POLICY,E=x.createHTML("")}else x===void 0&&(x=pU(f,r)),x!==null&&typeof E=="string"&&(E=x.createHTML(""));hi&&hi($),Cr=$}},XP=Ye({},["mi","mo","mn","ms","mtext"]),ZP=Ye({},["foreignobject","annotation-xml"]),f9=Ye({},["title","style","font","a","script"]),QP=Ye({},[...um,...dm,...nU]),JP=Ye({},[...hm,...rU]),p9=function($){let ue=S($);(!ue||!ue.tagName)&&(ue={namespaceURI:be,tagName:"template"});const Re=Ju($.tagName),pt=Ju(ue.tagName);return ke[$.namespaceURI]?$.namespaceURI===Y?ue.namespaceURI===ee?Re==="svg":ue.namespaceURI===M?Re==="svg"&&(pt==="annotation-xml"||XP[pt]):!!QP[Re]:$.namespaceURI===M?ue.namespaceURI===ee?Re==="math":ue.namespaceURI===Y?Re==="math"&&ZP[pt]:!!JP[Re]:$.namespaceURI===ee?ue.namespaceURI===Y&&!ZP[pt]||ue.namespaceURI===M&&!XP[pt]?!1:!JP[Re]&&(f9[Re]||!QP[Re]):!!(Et==="application/xhtml+xml"&&ke[$.namespaceURI]):!1},Zn=function($){Bl(e.removed,{element:$});try{S($).removeChild($)}catch{m($)}},Ph=function($,ue){try{Bl(e.removed,{attribute:ue.getAttributeNode($),from:ue})}catch{Bl(e.removed,{attribute:null,from:ue})}if(ue.removeAttribute($),$==="is"&&!Q[$])if(w||O)try{Zn(ue)}catch{}else try{ue.setAttribute($,"")}catch{}},eL=function($){let ue=null,Re=null;if(De)$="<remove></remove>"+$;else{const Jt=d1($,/^[\r\n\t ]+/);Re=Jt&&Jt[0]}Et==="application/xhtml+xml"&&be===ee&&($='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+$+"</body></html>");const pt=x?x.createHTML($):$;if(be===ee)try{ue=new h().parseFromString(pt,Et)}catch{}if(!ue||!ue.documentElement){ue=C.createDocument(be,"template",null);try{ue.documentElement.innerHTML=Ze?E:pt}catch{}}const oi=ue.body||ue.documentElement;return $&&Re&&oi.insertBefore(t.createTextNode(Re),oi.childNodes[0]||null),be===ee?D.call(ue,it?"html":"body")[0]:it?ue.documentElement:oi},tL=function($){return b.call($.ownerDocument||$,$,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},iL=function($){return $ instanceof d&&(typeof $.nodeName!="string"||typeof $.textContent!="string"||typeof $.removeChild!="function"||!($.attributes instanceof u)||typeof $.removeAttribute!="function"||typeof $.setAttribute!="function"||typeof $.namespaceURI!="string"||typeof $.insertBefore!="function"||typeof $.hasChildNodes!="function")},nL=function($){return typeof a=="function"&&$ instanceof a},Ir=function($,ue,Re){k[$]&&Qu(k[$],pt=>{pt.call(e,ue,Re,Cr)})},rL=function($){let ue=null;if(Ir("beforeSanitizeElements",$,null),iL($))return Zn($),!0;const Re=kt($.nodeName);if(Ir("uponSanitizeElement",$,{tagName:Re,allowedTags:V}),$.hasChildNodes()&&!nL($.firstElementChild)&&fi(/<[/\w]/g,$.innerHTML)&&fi(/<[/\w]/g,$.textContent)||$.nodeType===zl.progressingInstruction||Xe&&$.nodeType===zl.comment&&fi(/<[/\w]/g,$.data))return Zn($),!0;if(!V[Re]||ye[Re]){if(!ye[Re]&&oL(Re)&&(re.tagNameCheck instanceof RegExp&&fi(re.tagNameCheck,Re)||re.tagNameCheck instanceof Function&&re.tagNameCheck(Re)))return!1;if(he&&!ce[Re]){const pt=S($)||$.parentNode,oi=y($)||$.childNodes;if(oi&&pt){const Jt=oi.length;for(let Li=Jt-1;Li>=0;--Li){const Qn=g(oi[Li],!0);Qn.__removalCount=($.__removalCount||0)+1,pt.insertBefore(Qn,v($))}}}return Zn($),!0}return $ instanceof l&&!p9($)||(Re==="noscript"||Re==="noembed"||Re==="noframes")&&fi(/<\/no(script|embed|frames)/i,$.innerHTML)?(Zn($),!0):(Ue&&$.nodeType===zl.text&&(ue=$.textContent,Qu([N,B,K],pt=>{ue=Ul(ue,pt," ")}),$.textContent!==ue&&(Bl(e.removed,{element:$.cloneNode()}),$.textContent=ue)),Ir("afterSanitizeElements",$,null),!1)},sL=function($,ue,Re){if(ie&&(ue==="id"||ue==="name")&&(Re in t||Re in h9))return!1;if(!(qe&&!de[ue]&&fi(q,ue))){if(!(Pe&&fi(H,ue))){if(!Q[ue]||de[ue]){if(!(oL($)&&(re.tagNameCheck instanceof RegExp&&fi(re.tagNameCheck,$)||re.tagNameCheck instanceof Function&&re.tagNameCheck($))&&(re.attributeNameCheck instanceof RegExp&&fi(re.attributeNameCheck,ue)||re.attributeNameCheck instanceof Function&&re.attributeNameCheck(ue))||ue==="is"&&re.allowCustomizedBuiltInElements&&(re.tagNameCheck instanceof RegExp&&fi(re.tagNameCheck,Re)||re.tagNameCheck instanceof Function&&re.tagNameCheck(Re))))return!1}else if(!A[ue]){if(!fi(j,Ul(Re,F,""))){if(!((ue==="src"||ue==="xlink:href"||ue==="href")&&$!=="script"&&JB(Re,"data:")===0&&He[$])){if(!(Le&&!fi(X,Ul(Re,F,"")))){if(Re)return!1}}}}}}return!0},oL=function($){return $!=="annotation-xml"&&d1($,U)},aL=function($){Ir("beforeSanitizeAttributes",$,null);const{attributes:ue}=$;if(!ue)return;const Re={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Q};let pt=ue.length;for(;pt--;){const oi=ue[pt],{name:Jt,namespaceURI:Li,value:Qn}=oi,hc=kt(Jt);let yi=Jt==="value"?Qn:eU(Qn);if(Re.attrName=hc,Re.attrValue=yi,Re.keepAttr=!0,Re.forceKeepAttr=void 0,Ir("uponSanitizeAttribute",$,Re),yi=Re.attrValue,Xe&&fi(/((--!?|])>)|<\/(style|title)/i,yi)){Ph(Jt,$);continue}if(Re.forceKeepAttr||(Ph(Jt,$),!Re.keepAttr))continue;if(!Fe&&fi(/\/>/i,yi)){Ph(Jt,$);continue}Ue&&Qu([N,B,K],cL=>{yi=Ul(yi,cL," ")});const lL=kt($.nodeName);if(sL(lL,hc,yi)){if(te&&(hc==="id"||hc==="name")&&(Ph(Jt,$),yi=xe+yi),x&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Li)switch(f.getAttributeType(lL,hc)){case"TrustedHTML":{yi=x.createHTML(yi);break}case"TrustedScriptURL":{yi=x.createScriptURL(yi);break}}try{Li?$.setAttributeNS(Li,Jt,yi):$.setAttribute(Jt,yi),iL($)?Zn($):u1(e.removed)}catch{}}}Ir("afterSanitizeAttributes",$,null)},g9=function Ie($){let ue=null;const Re=tL($);for(Ir("beforeSanitizeShadowDOM",$,null);ue=Re.nextNode();)Ir("uponSanitizeShadowNode",ue,null),!rL(ue)&&(ue.content instanceof s&&Ie(ue.content),aL(ue));Ir("afterSanitizeShadowDOM",$,null)};return e.sanitize=function(Ie){let $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ue=null,Re=null,pt=null,oi=null;if(Ze=!Ie,Ze&&(Ie="<!-->"),typeof Ie!="string"&&!nL(Ie))if(typeof Ie.toString=="function"){if(Ie=Ie.toString(),typeof Ie!="string")throw $l("dirty is not a string, aborting")}else throw $l("toString is not a function");if(!e.isSupported)return Ie;if(zt||P0($),e.removed=[],typeof Ie=="string"&&($e=!1),$e){if(Ie.nodeName){const Qn=kt(Ie.nodeName);if(!V[Qn]||ye[Qn])throw $l("root node is forbidden and cannot be sanitized in-place")}}else if(Ie instanceof a)ue=eL("<!---->"),Re=ue.ownerDocument.importNode(Ie,!0),Re.nodeType===zl.element&&Re.nodeName==="BODY"||Re.nodeName==="HTML"?ue=Re:ue.appendChild(Re);else{if(!w&&!Ue&&!it&&Ie.indexOf("<")===-1)return x&&z?x.createHTML(Ie):Ie;if(ue=eL(Ie),!ue)return w?null:z?E:""}ue&&De&&Zn(ue.firstChild);const Jt=tL($e?Ie:ue);for(;pt=Jt.nextNode();)rL(pt)||(pt.content instanceof s&&g9(pt.content),aL(pt));if($e)return Ie;if(w){if(O)for(oi=I.call(ue.ownerDocument);ue.firstChild;)oi.appendChild(ue.firstChild);else oi=ue;return(Q.shadowroot||Q.shadowrootmode)&&(oi=P.call(n,oi,!0)),oi}let Li=it?ue.outerHTML:ue.innerHTML;return it&&V["!doctype"]&&ue.ownerDocument&&ue.ownerDocument.doctype&&ue.ownerDocument.doctype.name&&fi(v1,ue.ownerDocument.doctype.name)&&(Li="<!DOCTYPE "+ue.ownerDocument.doctype.name+`>
|
|
45
|
+
`+Li),Ue&&Qu([N,B,K],Qn=>{Li=Ul(Li,Qn," ")}),x&&z?x.createHTML(Li):Li},e.setConfig=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};P0(Ie),zt=!0},e.clearConfig=function(){Cr=null,zt=!1},e.isValidAttribute=function(Ie,$,ue){Cr||P0({});const Re=kt(Ie),pt=kt($);return sL(Re,pt,ue)},e.addHook=function(Ie,$){typeof $=="function"&&(k[Ie]=k[Ie]||[],Bl(k[Ie],$))},e.removeHook=function(Ie){if(k[Ie])return u1(k[Ie])},e.removeHooks=function(Ie){k[Ie]&&(k[Ie]=[])},e.removeAllHooks=function(){k={}},e}var x1=S1();function gU(i){return{__html:mU(i)}}function Nn(i,e){const t=Object.keys(i).filter(r=>e.includes(r)?null:r),n=new Object;return t.forEach(r=>{n[r]=i[r]}),n}function mU(i){return typeof window>"u"?i:x1.sanitize(i,{ALLOWED_TAGS:["a","b","br","i","img","p","small","span","sub","sup"],ALLOWED_ATTR:["href","alt","src","height","width"],ALLOWED_URI_REGEXP:/^(?:https?|mailto):/i})}function vU(i){return typeof window>"u"?i:x1.sanitize(i,{ALLOWED_TAGS:["a","b","br","hr","i","img","li","ol","p","small","span","sub","sup","ul"],ALLOWED_ATTR:["href","alt","src","height","width","id"],ALLOWED_URI_REGEXP:/^(?:https?:|mailto:|#)/i})}let pm=null;function yU(){return pm||(pm=Promise.all([Promise.resolve().then(()=>T5),Promise.resolve().then(()=>R5)]).then(([{Marked:i},{default:e}])=>{const t=new i({gfm:!0,breaks:!1,async:!1});return t.use(e({footnoteDivider:!0,description:""})),n=>{try{const s=t.parse(n||"").replace(/<li id="([^"]+)">\n<p>/g,'<li><p id="$1">');return vU(s)}catch(r){return console.warn("Failed to convert markdown",r),n||""}}})),pm}const SU=i=>{const[e,t]=se("");ne(()=>{if(!i){t("");return}let r=!1;return yU().then(s=>{r||t(s(i))}),()=>{r=!0}},[i]);const n=Ct(()=>T("div",{dangerouslySetInnerHTML:{__html:e}}),[e]);return{html:e,jsx:n}},xU=({value:i,handleClick:e})=>{const t=SU(i);return T(Xu,{onClick:e,children:T(Zu,{dangerouslySetInnerHTML:{__html:t.html}})})},TU=i=>String(i||"").replace(/\n/g,"<br />"),T1=({value:i,handleClick:e,isContentSearch:t})=>{const n=TU(i);return T(Xu,{onClick:e,children:T(Zu,{dangerouslySetInnerHTML:{__html:n},"data-content-search":t})})};function xn(i,e){this.message=i,this.error=e}xn.prototype=Object.create(Error.prototype);const gm=/([0-9]+)?:?([0-9]{2}):([0-9]{2}\.[0-9]{2,3})/;function EU(i,e){e||(e={});const{meta:t=!1,strict:n=!0}=e;if(typeof i!="string")throw new xn("Input must be a string");i=i.trim(),i=i.replace(/\r\n/g,`
|
|
46
|
+
`),i=i.replace(/\r/g,`
|
|
47
|
+
`);const r=i.split(`
|
|
48
|
+
|
|
49
|
+
`),s=r.shift();if(!s.startsWith("WEBVTT"))throw new xn('Must start with "WEBVTT"');const o=s.split(`
|
|
50
|
+
`),a=o[0].replace("WEBVTT","");if(a.length>0&&a[0]!==" "&&a[0]!==" ")throw new xn("Header comment must start with space or tab");if(r.length===0&&o.length===1)return{valid:!0,strict:n,cues:[],errors:[]};if(!t&&o.length>1&&o[1]!=="")throw new xn("Missing blank line after signature");const{cues:l,errors:c}=bU(r,n);if(n&&c.length>0)throw c[0];const u=t?wU(o):null,d={valid:c.length===0,strict:n,cues:l,errors:c};return t&&(d.meta=u),d}function wU(i){const e={};return i.slice(1).forEach(t=>{const n=t.indexOf(":"),r=t.slice(0,n).trim(),s=t.slice(n+1).trim();e[r]=s}),Object.keys(e).length>0?e:null}function bU(i,e){const t=[];return{cues:i.map((r,s)=>{try{return _U(r,s,e)}catch(o){return t.push(o),null}}).filter(Boolean),errors:t}}function _U(i,e,t){let n="",r=0,s=.01,o="",a="";const l=i.split(`
|
|
51
|
+
`).filter(Boolean);if(l.length>0&&l[0].trim().startsWith("NOTE"))return null;if(l.length===1&&!l[0].includes("-->"))throw new xn(`Cue identifier cannot be standalone (cue #${e})`);if(l.length>1&&!(l[0].includes("-->")||l[1].includes("-->"))){const u=`Cue identifier needs to be followed by timestamp (cue #${e})`;throw new xn(u)}l.length>1&&l[1].includes("-->")&&(n=l.shift());const c=typeof l[0]=="string"&&l[0].split(" --> ");if(c.length!==2||!E1(c[0])||!E1(c[1]))throw new xn(`Invalid cue timestamp (cue #${e})`);if(r=w1(c[0]),s=w1(c[1]),t){if(r>s)throw new xn(`Start timestamp greater than end (cue #${e})`);if(s<=r)throw new xn(`End must be greater than start (cue #${e})`)}if(!t&&s<r)throw new xn(`End must be greater or equal to start when not strict (cue #${e})`);return a=c[1].replace(gm,"").trim(),l.shift(),o=l.join(`
|
|
52
|
+
`),o?{identifier:n,start:r,end:s,text:o,styles:a}:!1}function E1(i){return gm.test(i)}function w1(i){const e=i.match(gm);let t=parseFloat(e[1]||0)*60*60;return t+=parseFloat(e[2])*60,t+=parseFloat(e[3]),t}var b1={parse:EU};function pi(i,e){this.message=i,this.error=e}pi.prototype=Object.create(Error.prototype);function AU(i){if(!i)throw new pi("Input must be non-null");if(typeof i!="object")throw new pi("Input must be an object");if(Array.isArray(i))throw new pi("Input cannot be array");if(!i.valid)throw new pi("Input must be valid");let e=`WEBVTT
|
|
53
|
+
`;if(i.meta){if(typeof i.meta!="object"||Array.isArray(i.meta))throw new pi("Metadata must be an object");Object.entries(i.meta).forEach(n=>{if(typeof n[1]!="string")throw new pi(`Metadata value for "${n[0]}" must be string`);e+=`${n[0]}: ${n[1]}
|
|
54
|
+
`})}let t=null;return i.cues.forEach((n,r)=>{if(t&&t>n.start)throw new pi(`Cue number ${r} is not in chronological order`);t=n.start,e+=`
|
|
55
|
+
`,e+=RU(n),e+=`
|
|
56
|
+
`}),e}function RU(i){if(typeof i!="object")throw new pi("Cue malformed: not of type object");if(typeof i.identifier!="string"&&typeof i.identifier!="number"&&i.identifier!==null)throw new pi(`Cue malformed: identifier value is not a string.
|
|
57
|
+
${JSON.stringify(i)}`);if(isNaN(i.start))throw new pi(`Cue malformed: null start value.
|
|
58
|
+
${JSON.stringify(i)}`);if(isNaN(i.end))throw new pi(`Cue malformed: null end value.
|
|
59
|
+
${JSON.stringify(i)}`);if(i.start>=i.end)throw new pi(`Cue malformed: start timestamp greater than end
|
|
60
|
+
${JSON.stringify(i)}`);if(typeof i.text!="string")throw new pi(`Cue malformed: null text value.
|
|
61
|
+
${JSON.stringify(i)}`);if(typeof i.styles!="string")throw new pi(`Cue malformed: null styles value.
|
|
62
|
+
${JSON.stringify(i)}`);let e="";i.identifier.length>0&&(e+=`${i.identifier}
|
|
63
|
+
`);const t=_1(i.start),n=_1(i.end);return e+=`${t} --> ${n}`,e+=i.styles?` ${i.styles}`:"",e+=`
|
|
64
|
+
${i.text}`,e}function _1(i){const e=td(CU(i),2),t=td(IU(i),2),n=td(PU(i),2),r=td(LU(i),3);return`${e}:${t}:${n}.${r}`}function td(i,e){let t=`${i}`;for(;t.length<e;)t=`0${t}`;return t}function CU(i){return Math.floor(i/60/60)}function IU(i){return Math.floor(i/60)%60}function PU(i){return Math.floor(i%60)}function LU(i){return Math.floor((i%1).toFixed(4)*1e3)}var kU={compile:AU};const DU=b1.parse;function OU(i,e){e=e||10;const t=DU(i),n=[];let r=[],s=null,o=0,a=0;return t.cues.forEach((l,c)=>{const u=c===0,d=c===t.cues.length-1,h=l.start,f=l.end,p=d?1/0:t.cues[c+1].start,g=u?f:f-h,m=u?0:h-t.cues[c-1].end;o=o+g+m,`${c}`,n.length+1,s&&(r.push(s),o+=s.end-a,s=null),r.push(l);let v=p-f<e&&m<e&&o>e;if(MU(a,e,p,m)){const y=FU(d,f,e,o,a);n.push({duration:y,cues:r}),a+=y,o=0,r=[]}else v=!1;v&&(s=l)}),n}function MU(i,e,t,n){const r=A1(n,e);return(n<=e||r+i<t)&&t-i>=e}function FU(i,e,t,n,r){let s=t;return n>t&&(s=A1(n-t,t)),i?s=parseFloat((e-r).toFixed(2)):s=Math.round(s),s}function A1(i,e){return i+=e-i%e,i}function jY(i){}var R1={segment:OU};const C1=R1.segment;function NU(i,e,t){typeof t>"u"&&(t="900000");const n=C1(i,e),r=[];return n.forEach((s,o)=>{const a=`WEBVTT
|
|
65
|
+
X-TIMESTAMP-MAP=MPEGTS:${t},LOCAL:00:00:00.000
|
|
66
|
+
|
|
67
|
+
${HU(s.cues)}
|
|
68
|
+
`,l=I1(o);r.push({filename:l,content:a})}),r}function BU(i,e){const t=C1(i,e),n=UU(t);return`#EXTM3U
|
|
69
|
+
#EXT-X-TARGETDURATION:${Math.round($U(t))}
|
|
70
|
+
#EXT-X-VERSION:3
|
|
71
|
+
#EXT-X-MEDIA-SEQUENCE:0
|
|
72
|
+
#EXT-X-PLAYLIST-TYPE:VOD
|
|
73
|
+
${n}
|
|
74
|
+
#EXT-X-ENDLIST
|
|
75
|
+
`}function id(i,e){return`${"0".repeat(Math.max(0,e-i.toString().length))}${i}`}function I1(i){return`${i}.vtt`}function UU(i){const e=[];return i.forEach((t,n)=>{e.push(`#EXTINF:${t.duration.toFixed(5)},
|
|
76
|
+
${I1(n)}`)}),e.join(`
|
|
77
|
+
`)}function $U(i){let e=0;return i.forEach(t=>{t.duration>e&&(e=t.duration)}),e}function HU(i){const e=[];return i.forEach(t=>{e.push(zU(t))}),e.join(`
|
|
78
|
+
|
|
79
|
+
`)}function zU(i){const e=[];i.identifier&&e.push(i.identifier);const t=P1(i.start),n=P1(i.end),r=i.styles?`${i.styles}`:"";return e.push(`${t} --> ${n} ${r}`),e.push(i.text),e.join(`
|
|
80
|
+
`)}function P1(i){const e=(i%1).toFixed(3);i=Math.round(i-e);const t=Math.floor(i/3600),n=Math.floor((i-t*3600)/60),r=i-t*3600-n*60;return`${`${id(t,2)}:`}${id(n,2)}:${id(r,2)}.${id(e*1e3,3)}`}var VU={hlsSegment:NU,hlsSegmentPlaylist:BU};const GU=b1.parse,WU=kU.compile,jU=R1.segment;var KU={parse:GU,compile:WU,segment:jU,hls:VU};const qU=()=>{function i(l){return l.map(c=>{const u=c.identifier||To();return{...c,identifier:u}})}function e(l){var h;const c=[],u=[],d=i(l);for(const f of d){for(;u.length>0&&u[u.length-1].end<=f.start;)u.pop();u.length>0?(u[u.length-1].children||(u[u.length-1].children=[]),(h=u[u.length-1].children)==null||h.push(f),u.push(f)):(c.push(f),u.push(f))}return c}function t(l,c=[]){return c.some(u=>l.start>=u.start&&l.end<=u.end)}function n(l=[]){return l.sort((c,u)=>c.start-u.start)}function r(l){const c=l.replace(/<(c|v|i|b|u|lang|ruby)(?:\.([^\s>]+))?(?:\s([^>]+))?>/g,(u,d,h,f)=>{const p=document.createElement(d);return h&&(p.className=h.replace(/\./g," ")),(f==null?void 0:f.length)>0&&(p.title=f),p.outerHTML.replace(new RegExp(`</${d}>$`),"")});return console.log("normalizeVttTags",c),c}function s(l){var c;for(const u of l.children)s(u);if(l.localName==="c"||l.localName==="v"){const u=document.createElement("span");for(const d of l.attributes)u.setAttribute(d.name,d.value);u.innerHTML=l.innerHTML,(c=l.parentNode)==null||c.replaceChild(u,l)}}function o(l){const c=r(l),u=document.createElement("div");return u.innerHTML=c,s(u),u.innerHTML}function a(l){return new Promise((c,u)=>{const d=KU.parse(l);d.errors&&d.errors.length&&u(d.errors),c(d.cues.map(h=>({identifier:h.identifier||To(),start:h.start,end:h.end,align:h.align,html:o(h.text),text:h.text||""})))})}return{addIdentifiersToParsedCues:i,createNestedCues:e,isChild:t,orderCuesByTime:n,parseVttData:a}};function mm(i){const[e,t]=se(void 0);return Yt(()=>{if(i){t({width:i.offsetWidth,height:i.offsetHeight});const n=new ResizeObserver(r=>{if(!Array.isArray(r)||!r.length)return;const s=r[0];let o,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;o=c.inlineSize,a=c.blockSize}else o=i.offsetWidth,a=i.offsetHeight;t({width:o,height:a})});return n.observe(i,{box:"border-box"}),()=>n.unobserve(i)}else t(void 0)},[i]),e}function vm(i){const e=ge({value:i,previous:i});return Ct(()=>(e.current.value!==i&&(e.current.previous=e.current.value,e.current.value=i),e.current.previous),[i])}var ym="Radio",[YU,L1]=Ln(ym),[XU,ZU]=YU(ym),k1=me((i,e)=>{const{__scopeRadio:t,name:n,checked:r=!1,required:s,disabled:o,value:a="on",onCheck:l,form:c,...u}=i,[d,h]=se(null),f=ut(e,m=>h(m)),p=ge(!1),g=d?c||!!d.closest("form"):!0;return T(XU,{scope:t,checked:r,disabled:o,children:[T(je.button,{type:"button",role:"radio","aria-checked":r,"data-state":F1(r),"data-disabled":o?"":void 0,disabled:o,value:a,...u,ref:f,onClick:Ge(i.onClick,m=>{r||l==null||l(),g&&(p.current=m.isPropagationStopped(),p.current||m.stopPropagation())})}),g&&T(M1,{control:d,bubbles:!p.current,name:n,value:a,checked:r,required:s,disabled:o,form:c,style:{transform:"translateX(-100%)"}})]})});k1.displayName=ym;var D1="RadioIndicator",O1=me((i,e)=>{const{__scopeRadio:t,forceMount:n,...r}=i,s=ZU(D1,t);return T(Ml,{present:n||s.checked,children:T(je.span,{"data-state":F1(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:e})})});O1.displayName=D1;var QU="RadioBubbleInput",M1=me(({__scopeRadio:i,control:e,checked:t,bubbles:n=!0,...r},s)=>{const o=ge(null),a=ut(o,s),l=vm(t),c=mm(e);return ne(()=>{const u=o.current;if(!u)return;const d=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(d,"checked").set;if(l!==t&&f){const p=new Event("click",{bubbles:n});f.call(u,t),u.dispatchEvent(p)}},[l,t,n]),T(je.input,{type:"radio","aria-hidden":!0,defaultChecked:t,...r,tabIndex:-1,ref:a,style:{...r.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});M1.displayName=QU;function F1(i){return i?"checked":"unchecked"}var JU=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],nd="RadioGroup",[e3]=Ln(nd,[Ku,L1]),N1=Ku(),B1=L1(),[t3,i3]=e3(nd),U1=me((i,e)=>{const{__scopeRadioGroup:t,name:n,defaultValue:r,value:s,required:o=!1,disabled:a=!1,orientation:l,dir:c,loop:u=!0,onValueChange:d,...h}=i,f=N1(t),p=ju(c),[g,m]=Fr({prop:s,defaultProp:r??null,onChange:d,caller:nd});return T(t3,{scope:t,name:n,required:o,disabled:a,value:g,onValueChange:m,children:T(qb,{asChild:!0,...f,orientation:l,dir:p,loop:u,children:T(je.div,{role:"radiogroup","aria-required":o,"aria-orientation":l,"data-disabled":a?"":void 0,dir:p,...h,ref:e})})})});U1.displayName=nd;var $1="RadioGroupItem",H1=me((i,e)=>{const{__scopeRadioGroup:t,disabled:n,...r}=i,s=i3($1,t),o=s.disabled||n,a=N1(t),l=B1(t),c=ge(null),u=ut(e,c),d=s.value===r.value,h=ge(!1);return ne(()=>{const f=g=>{JU.includes(g.key)&&(h.current=!0)},p=()=>h.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",p),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",p)}},[]),T(Yb,{asChild:!0,...a,focusable:!o,active:d,children:T(k1,{disabled:o,required:s.required,checked:d,...l,...r,name:s.name,ref:u,onCheck:()=>s.onValueChange(r.value),onKeyDown:Ge(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:Ge(r.onFocus,()=>{var f;h.current&&((f=c.current)==null||f.click())})})})});H1.displayName=$1;var n3="RadioGroupIndicator",r3=me((i,e)=>{const{__scopeRadioGroup:t,...n}=i,r=B1(t);return T(O1,{...r,...n,ref:e})});r3.displayName=n3;var z1=U1,V1=H1;const s3=oe(z1,{display:"flex",flexDirection:"column",width:"100%"}),G1=oe(V1,{...o1,justifyContent:"space-between",textAlign:"left",flexGrow:1,margin:0,marginLeft:"-1rem",padding:"0.618rem 1rem",width:"calc(100% + 2rem)",fontSize:"1rem",strong:{marginLeft:"1rem"},"&:hover":{color:"$accent"},"&[aria-checked='true']":{background:"#6662"}}),o3=750,a3=i=>{for(;i&&i!==document.body;){const e=window.getComputedStyle(i).overflowY;if(e!=="visible"&&e!=="hidden"&&i.scrollHeight>i.clientHeight)return i;i=i.parentNode}return null},l3=({html:i,text:e,start:t,end:n})=>{var g,m;const r=Ti(),{activePlayer:s,configOptions:o,isAutoScrollEnabled:a,isUserScrolling:l}=gt(),c=(m=(g=o==null?void 0:o.informationPanel)==null?void 0:g.vtt)==null?void 0:m.autoScroll,[u,d]=se(!1),h=ge(null),f=s;return ne(()=>(f==null||f.addEventListener("timeupdate",()=>{const{currentTime:v}=f;d(t<=v&&v<n)}),()=>document.removeEventListener("timeupdate",()=>{})),[n,t,f]),ne(()=>{var y;const v=S=>{r({type:"updateAutoScrolling",isAutoScrolling:!0}),S(),setTimeout(()=>r({type:"updateAutoScrolling",isAutoScrolling:!1}),o3)};if(a&&u&&h.current&&!l){const S=h.current;if(S&&S instanceof HTMLElement){const x=a3(S);if(x&&x instanceof HTMLElement){let E;switch((y=c==null?void 0:c.settings)==null?void 0:y.block){case"center":const C=x.getBoundingClientRect();E=S.offsetTop+S.offsetHeight-Math.floor((C.bottom-C.top)/2);break;case"end":E=S.offsetTop+S.offsetHeight-(x.clientHeight-S.clientHeight)+2;break;default:E=S.offsetTop-2;break}v(()=>{var C;return x.scrollTo({top:E,left:0,behavior:(C=c==null?void 0:c.settings)==null?void 0:C.behavior})})}}}},[c,u,l,a,r]),T(G1,{ref:h,"aria-checked":u,"data-testid":"information-panel-cue",onClick:()=>{f&&(f.pause(),f.currentTime=t,f.play())},value:e,children:[T("div",{className:"webvtt-cue",dangerouslySetInnerHTML:{__html:i}}),T("strong",{children:Fx(t)})]})},c3=oe("ul",{listStyle:"none",paddingLeft:"1rem",position:"relative","&&:first-child":{paddingLeft:"0"},"& li ul":{[`& ${G1}`]:{backgroundColor:"unset","&::before":{content:"none"},"&::after":{content:"none"}}},"&:first-child":{margin:"0 0 1.618rem"}}),W1=({items:i})=>T(c3,{children:i.map(e=>{const{html:t,text:n,start:r,end:s,children:o,identifier:a}=e;return T("li",{children:[T(l3,{html:t,text:n,start:r,end:s}),o&&T(W1,{items:o})]},a)})}),u3=({inlineCues:i,label:e,vttUri:t})=>{const[n,r]=et.useState(i||[]),{createNestedCues:s,orderCuesByTime:o,parseVttData:a}=qU(),[l,c]=et.useState();return ne(()=>{!i&&t&&fetch(t,{redirect:"follow",headers:{Accept:"text/vtt, text/plain, */*"}}).then(u=>{if(!u.ok)throw new Error(`HTTP error! status: ${u.status}`);return u.text()}).then(u=>{a(u).then(d=>{const h=o(d),f=s(h);r(f)})}).catch(u=>{console.error(t,u.toString()),c(u)})},[t,i]),T(s3,{"data-testid":"annotation-item-vtt","aria-label":`${im(e)}`,children:[l&&T("div",{"data-testid":"error-message",children:["Network Error: ",l.toString()]}),T(W1,{items:n})]})},Sm=({annotation:i,targetResource:e,isContentSearch:t,isContentState:n})=>{var B,K,q,H,X,F,U;const{target:r}=i,s=(B=r==null?void 0:r.selector)==null?void 0:B.type,o=((q=(K=r==null?void 0:r.selector)==null?void 0:K.value)==null?void 0:q.split("=")[1])||"full",[a,l]=o!=="full"?o==null?void 0:o.split(",").slice(2):[100,100],u=`${e}/${o}/!${((j,V)=>{const Q=Math.max(j,V),le=Math.round(j/Q*100),re=Math.round(V/Q*100);return[le,re].join(",")})(a,l)}/0/default.jpg`,d=gt(),h=Ti(),{openSeadragonViewer:f,vault:p,visibleCanvases:g}=d,m=i!=null&&i.body?(H=i==null?void 0:i.body)==null?void 0:H.map(j=>p.get(j.id)):[],{format:v=s==="PointSelector"?"text/vtt":"text/plain",language:y="none",value:S="",chars:x=""}=m[0]?m[0]:{},E=s==="PointSelector"?"text/vtt":v,C=((X=m[0])==null?void 0:X.label)||{none:["t"]},b=S||x||"None",I=y?BL(y).toLocaleLowerCase():"LTR",D=s==="PointSelector"&&((F=r==null?void 0:r.selector)!=null&&F.t)?[{start:(U=r==null?void 0:r.selector)==null?void 0:U.t,end:0,html:b,text:b,styles:"",children:[]}]:void 0;function P(){var V;const j=f==null?void 0:f.getOverlayById(i.id);if(j&&(f!=null&&f.viewport)){j!=null&&j.element&&((V=j.element)==null||V.focus());const Z=j==null?void 0:j.getBounds(f.viewport);Z.x-=.2,Z.y-=.2,Z.width+=.5,Z.height+=.5,f.viewport.fitBounds(Z,!1)}}ne(()=>{if(!f||!n)return;const j=setInterval(()=>{(f==null?void 0:f.getOverlayById(i.id))&&(P(),f.container.className="clover-iiif-content-state",clearInterval(j))},1e3);return()=>clearInterval(j)},[f,n]);function k(j){var le;j.preventDefault(),j.stopPropagation();const V=((le=i==null?void 0:i.target)==null?void 0:le.source)||(i==null?void 0:i.target),Z=V==null?void 0:V.id;g.map(re=>re.id).includes(Z)?P():h({type:"updateActiveCanvas",canvasId:Z})}function N(){var j,V,Z;switch(E){case"text/plain":return T(T1,{value:b,handleClick:k,isContentSearch:t});case"text/html":return T(qB,{value:b,handleClick:k});case"text/markdown":return T(xU,{value:b,handleClick:k});case"text/vtt":return T(u3,{inlineCues:D,label:C,vttUri:((j=m[0])==null?void 0:j.id)||void 0});case((V=v==null?void 0:v.match(/^image\//))==null?void 0:V.input):const Q=((Z=m.find(le=>{var re;return!((re=le.id)!=null&&re.includes("vault://"))}))==null?void 0:Z.id)||"";return T(YB,{caption:S,handleClick:k,imageUri:Q});default:return T(T1,{value:b,handleClick:k})}}if(v)return T(KB,{dir:I,"data-format":v,"data-content":b,className:"clover-iiif-annotation-item",children:[T("span",{style:{backgroundImage:`url(${u})`,backgroundSize:"cover",backgroundPosition:"center"}}),N()]})},d3=oe("span",{}),yr=i=>{const{as:e,label:t}=i,r=Nn(i,["as","label"]);return T(d3,{as:e,...r,children:Di(t,r.lang)})},j1=(i,e)=>{var t;return!!(i&&((t=i.split("?")[0].split(".").pop())==null?void 0:t.toLowerCase())==="m3u8"||e&&h3.includes(e))},h3=["application/vnd.apple.mpegurl","vnd.apple.mpegurl","audio/mpegurl","audio/x-mpegurl","application/x-mpegurl","video/x-mpegurl","video/mpegurl","application/mpegurl"],f3=(i,e="200,",t="full")=>{Array.isArray(i)&&(i=i[0]);const{id:n,service:r}=i;let s;if(!r)return n;if(Array.isArray(i.service)&&i.service.length>0&&(s=r[0]),s){if(s["@id"])return`${s["@id"]}/${t}/${e}/0/default.jpg`;if(s.id)return`${s.id}/${t}/${e}/0/default.jpg`}},K1=oe("img",{objectFit:"cover"}),p3=i=>{const e=ge(null),{contentResource:t,altAsLabel:n,region:r="full"}=i;let s;n&&(s=Di(n));const a=Nn(i,["contentResource","altAsLabel"]),{type:l,id:c,width:u=200,height:d=200,duration:h}=t,f=j1(c,t.format);ne(()=>{if(!c||!e.current||l==="Image"||!f)return;const m=e.current;if(m.canPlayType("application/vnd.apple.mpegurl")){m.src=c;return}let v=!1,y;return(async()=>{const{default:S}=await Promise.resolve().then(()=>jP);if(!(v||!e.current)){if(!S.isSupported()){e.current.src=c;return}y=new S,y.attachMedia(e.current),y.on(S.Events.MEDIA_ATTACHED,function(){y==null||y.loadSource(c)}),y.on(S.Events.ERROR,function(x,E){if(E.fatal)switch(E.type){case S.ErrorTypes.NETWORK_ERROR:console.error(`fatal ${x} network error encountered, try to recover`),y==null||y.startLoad();break;case S.ErrorTypes.MEDIA_ERROR:console.error(`fatal ${x} media error encountered, try to recover`),y==null||y.recoverMediaError();break;default:y==null||y.destroy();break}})}})(),()=>{v=!0,y&&(y.detachMedia(),y.destroy())}},[c,l,f]);const p=Ce(()=>{if(!e.current)return;let m=0,v=30;if(h&&(v=h),!c.split("#t=")&&h&&(m=h*.1),c.split("#t=").pop()){const S=c.split("#t=").pop();S&&(m=parseInt(S.split(",")[0]))}const y=e.current;y.autoplay=!0,y.currentTime=m,setTimeout(()=>p(),v*1e3)},[h,c]);ne(()=>p(),[p]);const g=f3(t,`${u},${d}`,r);switch(l){case"Image":return T(K1,{as:"img",alt:s,css:{width:u,height:d},src:g,...a},c);case"Video":return T(K1,{as:"video",css:{width:u,height:d},disablePictureInPicture:!0,loop:!0,muted:!0,onPause:p,ref:e,...f?{}:{src:c}},c);default:return console.warn(`Resource type: ${l} is not valid or not yet supported in Primitives.`),T(Ee,{})}},g3=oe("a",{}),m3=i=>{const{children:e,homepage:t}=i,r=Nn(i,["children","homepage"]);return T(Ee,{children:t&&t.map(s=>{const o=Di(s.label,r.lang);return T(g3,{"aria-label":e?o:void 0,href:s.id,...r,children:e||o},s.id)})})},v3={delimiter:", "},xm=ln(void 0),q1=()=>{const i=Cn(xm);if(i===void 0)throw new Error("usePrimitivesContext must be used with a PrimitivesProvider");return i},Tm=({children:i,initialState:e=v3})=>{const t=y3(e,"delimiter");return T(xm.Provider,{value:{delimiter:t},children:i})},y3=(i,e)=>Object.hasOwn(i,e)?i[e].toString():void 0,S3=oe("span",{}),Y1=i=>{const{as:e,markup:t}=i,{delimiter:n}=q1();if(!t)return T(Ee,{});const s=Nn(i,["as","markup"]),o=gU(Di(t,s.lang,n));return T(S3,{as:e,...s,dangerouslySetInnerHTML:o})},X1=i=>et.useContext(xm)?T(Y1,{...i}):T(Tm,{children:T(Y1,{...i})}),x3=({as:i="dd",lang:e,value:t})=>T(X1,{markup:t,as:i,lang:e}),T3=oe("span",{}),E3=({as:i="dd",customValueContent:e,lang:t,value:n})=>{var o;const{delimiter:r}=q1(),s=(o=wT(n,t))==null?void 0:o.map(a=>tr(e,{value:a}));return T(T3,{as:i,lang:t,children:s==null?void 0:s.map((a,l)=>[l>0&&`${r}`,T(Ee,{children:a},l)])})},Z1=i=>{var a;const{item:e,lang:t,customValueContent:n}=i,{label:r,value:s}=e,o=(a=Di(r))==null?void 0:a.replace(" ","-").toLowerCase();return T("div",{role:"group","data-label":o,children:[T(yr,{as:"dt",label:r,lang:t}),n?T(E3,{as:"dd",customValueContent:n,value:s,lang:t}):T(x3,{as:"dd",value:s,lang:t})]})};function w3(i,e){const t=e.filter(n=>{const{matchingLabel:r}=n,s=Object.keys(n.matchingLabel)[0],o=Di(r,s);if(Di(i,s)===o)return!0}).map(n=>n.Content);if(Array.isArray(t))return t[0]}const b3=oe("dl",{}),_3=i=>{const{as:e,customValueContent:t,metadata:n}=i;if(!Array.isArray(n))return T(Ee,{});const r=Ux(i,"customValueDelimiter"),o=Nn(i,["as","customValueContent","customValueDelimiter","metadata"]);return T(Tm,{...typeof r=="string"?{initialState:{delimiter:r}}:void 0,children:n.length>0&&T(b3,{as:e,...o,children:n.map((a,l)=>{const c=t?w3(a.label,t):void 0;return T(Z1,{customValueContent:c,item:a,lang:o==null?void 0:o.lang},l)})})})};oe("li",{}),oe("ul",{});const A3=oe("li",{}),R3=oe("ul",{}),C3=i=>{const{as:e,rendering:t}=i,r=Nn(i,["as","rendering"]);return T(R3,{as:e,children:t&&t.map(s=>{const o=Di(s.label,r.lang);return T(A3,{children:T("a",{href:s.id,...r,target:"_blank",children:o||s.id})},s.id)})})},I3=oe("dl",{}),P3=i=>{const{as:e,requiredStatement:t}=i;if(!t)return T(Ee,{});const n=Ux(i,"customValueDelimiter"),s=Nn(i,["as","customValueDelimiter","requiredStatement"]);return T(Tm,{...typeof n=="string"?{initialState:{delimiter:n}}:void 0,children:T(I3,{as:e,...s,children:T(Z1,{item:t,lang:s.lang})})})},L3=oe("li",{}),k3=oe("ul",{}),D3=i=>{const{as:e,seeAlso:t}=i,r=Nn(i,["as","seeAlso"]);return T(k3,{as:e,children:t&&t.map(s=>{const o=Di(s.label,r.lang);return T(L3,{children:T("a",{href:s.id,...r,children:o||s.id})},s.id)})})},O3=i=>{const{as:e,summary:t}=i,r=Nn(i,["as","customValueDelimiter","summary"]);return T(X1,{as:e,markup:t,...r})},Q1=i=>{const{thumbnail:e,region:t}=i,r=Nn(i,["thumbnail"]);return T(Ee,{children:e&&e.map(s=>T(p3,{contentResource:s,region:t,...r},s.id))})},M3=({annotationPage:i})=>{var l,c,u,d,h,f;const e=gt(),{vault:t}=e;if(!i||!i.items||((l=i.items)==null?void 0:l.length)===0)return T(Ee,{});const n=i.items.map(p=>t.get(p.id));if(!n)return T(Ee,{});const r=n.reduce((p,g)=>(p.canvas=g.target.source.id,p.annotations=[],p.annotations.push(g==null?void 0:g.id),p),{}),s=t.get(r.canvas),o=ns(t,s.id),a=(c=o==null?void 0:o[0])!=null&&c.service?((d=(u=o==null?void 0:o[0])==null?void 0:u.service[0])==null?void 0:d.id)||((f=(h=o==null?void 0:o[0])==null?void 0:h.service[0])==null?void 0:f["@id"]):void 0;return T(om,{"data-testid":"annotation-page",children:[s&&T("header",{children:T(yr,{label:s.label})}),T("div",{"data-testid":"annotation-page-items",children:n==null?void 0:n.map(p=>T(Sm,{annotation:p,targetResource:a},p.id))})]})};function Sr(){return Sr=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(i[n]=t[n])}return i},Sr.apply(null,arguments)}function Vl(i,e,{checkForDefaultPrevented:t=!0}={}){return function(r){if(i==null||i(r),t===!1||!r.defaultPrevented)return e==null?void 0:e(r)}}function F3(i,e){typeof i=="function"?i(e):i!=null&&(i.current=e)}function J1(...i){return e=>i.forEach(t=>F3(t,e))}function e_(...i){return Ce(J1(...i),i)}function N3(i,e=[]){let t=[];function n(s,o){const a=ln(o),l=t.length;t=[...t,o];function c(d){const{scope:h,children:f,...p}=d,g=(h==null?void 0:h[i][l])||a,m=Ct(()=>p,Object.values(p));return Ve(g.Provider,{value:m},f)}function u(d,h){const f=(h==null?void 0:h[i][l])||a,p=Cn(f);if(p)return p;if(o!==void 0)return o;throw new Error(`\`${d}\` must be used within \`${s}\``)}return c.displayName=s+"Provider",[c,u]}const r=()=>{const s=t.map(o=>ln(o));return function(a){const l=(a==null?void 0:a[i])||s;return Ct(()=>({[`__scope${i}`]:{...a,[i]:l}}),[a,l])}};return r.scopeName=i,[n,B3(r,...e)]}function B3(...i){const e=i[0];if(i.length===1)return e;const t=()=>{const n=i.map(r=>({useScope:r(),scopeName:r.scopeName}));return function(s){const o=n.reduce((a,{useScope:l,scopeName:c})=>{const d=l(s)[`__scope${c}`];return{...a,...d}},{});return Ct(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return t.scopeName=e.scopeName,t}const U3=globalThis!=null&&globalThis.document?Ki:()=>{},$3=vc.useId||(()=>{});let H3=0;function z3(i){const[e,t]=se($3());return U3(()=>{t(n=>n??String(H3++))},[i]),e?`radix-${e}`:""}const t_=me((i,e)=>{const{children:t,...n}=i,r=xi.toArray(t),s=r.find(G3);if(s){const o=s.props.children,a=r.map(l=>l===s?xi.count(o)>1?xi.only(null):ki(o)?o.props.children:null:l);return Ve(Em,Sr({},n,{ref:e}),ki(o)?tr(o,void 0,a):null)}return Ve(Em,Sr({},n,{ref:e}),t)});t_.displayName="Slot";const Em=me((i,e)=>{const{children:t,...n}=i;return ki(t)?tr(t,{...W3(n,t.props),ref:e?J1(e,t.ref):t.ref}):xi.count(t)>1?xi.only(null):null});Em.displayName="SlotClone";const V3=({children:i})=>Ve(Ee,null,i);function G3(i){return ki(i)&&i.type===V3}function W3(i,e){const t={...e};for(const n in e){const r=i[n],s=e[n];/^on[A-Z]/.test(n)?r&&s?t[n]=(...a)=>{s(...a),r(...a)}:r&&(t[n]=r):n==="style"?t[n]={...r,...s}:n==="className"&&(t[n]=[r,s].filter(Boolean).join(" "))}return{...i,...t}}const rd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce((i,e)=>{const t=me((n,r)=>{const{asChild:s,...o}=n,a=s?t_:e;return ne(()=>{window[Symbol.for("radix-ui")]=!0},[]),Ve(a,Sr({},o,{ref:r}))});return t.displayName=`Primitive.${e}`,{...i,[e]:t}},{}),[wm]=N3("Form"),i_="Form",[j3,n_]=wm(i_),[K3,q3]=wm(i_),Y3=me((i,e)=>{const{__scopeForm:t,onClearServerErrors:n=()=>{},...r}=i,s=ge(null),o=e_(e,s),[a,l]=se({}),c=Ce(P=>a[P],[a]),u=Ce((P,k)=>l(N=>{var B;return{...N,[P]:{...(B=N[P])!==null&&B!==void 0?B:{},...k}}}),[]),d=Ce(P=>{l(k=>({...k,[P]:void 0})),y(k=>({...k,[P]:{}}))},[]),[h,f]=se({}),p=Ce(P=>{var k;return(k=h[P])!==null&&k!==void 0?k:[]},[h]),g=Ce((P,k)=>{f(N=>{var B;return{...N,[P]:[...(B=N[P])!==null&&B!==void 0?B:[],k]}})},[]),m=Ce((P,k)=>{f(N=>{var B;return{...N,[P]:((B=N[P])!==null&&B!==void 0?B:[]).filter(K=>K.id!==k)}})},[]),[v,y]=se({}),S=Ce(P=>{var k;return(k=v[P])!==null&&k!==void 0?k:{}},[v]),x=Ce((P,k)=>{y(N=>{var B;return{...N,[P]:{...(B=N[P])!==null&&B!==void 0?B:{},...k}}})},[]),[E,C]=se({}),b=Ce((P,k)=>{C(N=>{const B=new Set(N[P]).add(k);return{...N,[P]:B}})},[]),I=Ce((P,k)=>{C(N=>{const B=new Set(N[P]);return B.delete(k),{...N,[P]:B}})},[]),D=Ce(P=>{var k;return Array.from((k=E[P])!==null&&k!==void 0?k:[]).join(" ")||void 0},[E]);return Ve(j3,{scope:t,getFieldValidity:c,onFieldValidityChange:u,getFieldCustomMatcherEntries:p,onFieldCustomMatcherEntryAdd:g,onFieldCustomMatcherEntryRemove:m,getFieldCustomErrors:S,onFieldCustomErrorsChange:x,onFieldValiditionClear:d},Ve(K3,{scope:t,onFieldMessageIdAdd:b,onFieldMessageIdRemove:I,getFieldDescription:D},Ve(rd.form,Sr({},r,{ref:o,onInvalid:Vl(i.onInvalid,P=>{const k=o_(P.currentTarget);k===P.target&&k.focus(),P.preventDefault()}),onSubmit:Vl(i.onSubmit,n,{checkForDefaultPrevented:!1}),onReset:Vl(i.onReset,n)}))))}),r_="FormField",[X3,Z3]=wm(r_),Q3=me((i,e)=>{const{__scopeForm:t,name:n,serverInvalid:r=!1,...s}=i,a=n_(r_,t).getFieldValidity(n),l=z3();return Ve(X3,{scope:t,id:l,name:n,serverInvalid:r},Ve(rd.div,Sr({"data-valid":a_(a,r),"data-invalid":l_(a,r)},s,{ref:e})))}),bm="FormControl",J3=me((i,e)=>{const{__scopeForm:t,...n}=i,r=n_(bm,t),s=Z3(bm,t),o=q3(bm,t),a=ge(null),l=e_(e,a),c=n.name||s.name,u=n.id||s.id,d=r.getFieldCustomMatcherEntries(c),{onFieldValidityChange:h,onFieldCustomErrorsChange:f,onFieldValiditionClear:p}=r,g=Ce(async y=>{if(a$(y.validity)){const N=_m(y.validity);h(c,N);return}const S=y.form?new FormData(y.form):new FormData,x=[y.value,S],E=[],C=[];d.forEach(N=>{r$(N,x)?C.push(N):s$(N)&&E.push(N)});const b=E.map(({id:N,match:B})=>[N,B(...x)]),I=Object.fromEntries(b),D=Object.values(I).some(Boolean),P=D;y.setCustomValidity(P?s_:"");const k=_m(y.validity);if(h(c,k),f(c,I),!D&&C.length>0){const N=C.map(({id:F,match:U})=>U(...x).then(j=>[F,j])),B=await Promise.all(N),K=Object.fromEntries(B),H=Object.values(K).some(Boolean);y.setCustomValidity(H?s_:"");const X=_m(y.validity);h(c,X),f(c,K)}},[d,c,f,h]);ne(()=>{const y=a.current;if(y){const S=()=>g(y);return y.addEventListener("change",S),()=>y.removeEventListener("change",S)}},[g]);const m=Ce(()=>{const y=a.current;y&&(y.setCustomValidity(""),p(c))},[c,p]);ne(()=>{var y;const S=(y=a.current)===null||y===void 0?void 0:y.form;if(S)return S.addEventListener("reset",m),()=>S.removeEventListener("reset",m)},[m]),ne(()=>{const y=a.current,S=y==null?void 0:y.closest("form");if(S&&s.serverInvalid){const x=o_(S);x===y&&x.focus()}},[s.serverInvalid]);const v=r.getFieldValidity(c);return Ve(rd.input,Sr({"data-valid":a_(v,s.serverInvalid),"data-invalid":l_(v,s.serverInvalid),"aria-invalid":s.serverInvalid?!0:void 0,"aria-describedby":o.getFieldDescription(c),title:""},n,{ref:l,id:u,name:c,onInvalid:Vl(i.onInvalid,y=>{const S=y.currentTarget;g(S)}),onChange:Vl(i.onChange,y=>{m()})}))}),s_="This value is not valid",e$=me((i,e)=>{const{__scopeForm:t,...n}=i;return Ve(rd.button,Sr({type:"submit"},n,{ref:e}))});function _m(i){const e={};for(const t in i)e[t]=i[t];return e}function t$(i){return i instanceof HTMLElement}function i$(i){return"validity"in i}function n$(i){return i$(i)&&(i.validity.valid===!1||i.getAttribute("aria-invalid")==="true")}function o_(i){const e=i.elements,[t]=Array.from(e).filter(t$).filter(n$);return t}function r$(i,e){return i.match.constructor.name==="AsyncFunction"||o$(i.match,e)}function s$(i){return i.match.constructor.name==="Function"}function o$(i,e){return i(...e)instanceof Promise}function a$(i){let e=!1;for(const t in i){const n=t;if(n!=="valid"&&n!=="customError"&&i[n]){e=!0;break}}return e}function a_(i,e){if((i==null?void 0:i.valid)===!0&&!e)return!0}function l_(i,e){if((i==null?void 0:i.valid)===!1||e)return!0}const l$=Y3,c$=Q3,u$=J3,d$=e$,h$=oe("div",{form:{display:"flex",alignItems:"center",width:"100%",height:"100%",gap:"1rem",padding:"0 1.618rem 1.618rem",".content-search-input":{flexGrow:"1",input:{width:"100%",border:"none",backgroundColor:"$secondaryMuted",color:"$primary",marginRight:"1rem",height:"2rem",padding:"0 1rem",borderRadius:"1rem",fontFamily:"inherit",fontSize:"1rem",lineHeight:"1rem",boxShadow:"inset 1px 1px 2px #0001","&::placeholder":{color:"#0006"}}}}}),f$=oe("button",{display:"flex",background:"none",border:"none",width:"2rem",height:"2rem",padding:"0",margin:"0",fontWeight:"700",borderRadius:"2rem",backgroundColor:"$accent",color:"$secondary",cursor:"pointer",boxSizing:"content-box",transition:"$all",svg:{height:"60%",width:"60%",padding:"20%",fill:"$secondary",stroke:"$secondary",opacity:"1",filter:"drop-shadow(5px 5px 5px #000D)",boxSizing:"inherit",transition:"$all"},"&:disabled":{backgroundColor:"transparent",boxShadow:"none",svg:{opacity:"0.25"}}}),p$=({searchServiceUrl:i,setContentSearchResource:e,setLoading:t,contentSearchCallback:n,initialSearchQuery:r})=>{const{t:s}=dn(),[o,a]=se(r),l=gt(),{vault:c}=l;async function u(f){if(f.preventDefault(),!!i){if(!o||o.trim()===""){e({});return}t(!0),Bb(c,i,{q:o}).then(p=>{e(p),t(!1)})}}const d=f=>{f.preventDefault();const p=f.target.value;a(p),n==null||n(p)},h=s("contentSearchPlaceholder");return T(h$,{children:T(l$,{onSubmit:u,className:"content-search-form",children:[T(c$,{className:"content-search-input",name:"searchTerms",children:T(u$,{placeholder:h,defaultValue:r,onChange:d})}),T(d$,{asChild:!0,children:T(f$,{type:"submit",children:T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:s("informationPanelTabsSearch")}),T("path",{d:"M456.69 421.39L362.6 327.3a173.81 173.81 0 0034.84-104.58C397.44 126.38 319.06 48 222.72 48S48 126.38 48 222.72s78.38 174.72 174.72 174.72A173.81 173.81 0 00327.3 362.6l94.09 94.09a25 25 0 0035.3-35.3zM97.92 222.72a124.8 124.8 0 11124.8 124.8 124.95 124.95 0 01-124.8-124.8z"})]})})})]})})},g$=({searchServiceUrl:i,setContentSearchResource:e,activeCanvas:t,annotationPage:n,contentSearchCallback:r,initialSearchQuery:s})=>{const o=gt(),{vault:a}=o,{t:l}=dn(),[c,u]=se(!1),[d,h]=se({});ne(()=>{var m;if(!(n!=null&&n.items))return;const g=((m=n==null?void 0:n.items)==null?void 0:m.map(v=>a.get(v.id))).reduce((v,y)=>{const S=y.target.source.id;return v[S]||(v[S]=[]),v[S].push(y.id),v},{});h(g)},[n]);let f;return T(Ee,{children:[T(p$,{searchServiceUrl:i,setContentSearchResource:e,activeCanvas:t,setLoading:u,contentSearchCallback:r,initialSearchQuery:s}),c?T("span",{children:l("contentSearchLoading")}):d&&Object.keys(d).length>0&&Object.keys(d).map(p=>(f=a.get(p),T(om,{"data-testid":"annotation-page",children:[f&&T("header",{children:T(yr,{label:f.label})}),d[p].map(g=>{var S,x,E,C,b;const m=a.get(g),v=ns(a,f.id),y=(S=v==null?void 0:v[0])!=null&&S.service?((E=(x=v==null?void 0:v[0])==null?void 0:x.service[0])==null?void 0:E.id)||((b=(C=v==null?void 0:v[0])==null?void 0:C.service[0])==null?void 0:b["@id"]):void 0;return T(Sm,{annotation:m,targetResource:y,isContentSearch:!0},m.id)})]},p)))]})},m$=oe("div",{width:"100%",padding:" 0 1.618rem 2rem",display:"flex",flexDirection:"column",overflow:"auto",position:"absolute",fontWeight:"400",fontSize:"1rem",zIndex:"0",img:{maxWidth:"100px",maxHeight:"100px",objectFit:"contain",color:"transparent",margin:"0 0 1rem",borderRadius:"3px",backgroundColor:"$secondaryMuted"},video:{display:"none"},"a, a:visited":{color:"$accent"},p:{fontSize:"1rem",lineHeight:"1.47em",margin:"0"},dl:{margin:"0",dt:{fontWeight:"700",margin:"1rem 0 0.25rem"},dd:{margin:"0"}},".manifest-property-title":{fontWeight:"700",margin:"1rem 0 0.25rem"},"ul, ol":{padding:"0",margin:"0",li:{fontSize:"1rem",lineHeight:"1.45em",listStyle:"none",margin:"0.25rem 0 0.25rem"}}}),v$=oe("div",{position:"relative",width:"100%",height:"100%",zIndex:"0"}),y$=({homepage:i})=>(i==null?void 0:i.length)===0?T(Ee,{}):T(Ee,{children:[T("span",{className:"manifest-property-title",children:"Homepage"}),T(m3,{homepage:i})]}),S$=({id:i,htmlLabel:e,parent:t="manifest"})=>T(Ee,{children:[T("span",{className:"manifest-property-title",children:e}),T("a",{href:i,target:"_blank",id:`iiif-${t}-id`,children:i})]}),x$=({metadata:i,parent:e="manifest"})=>i?T(Ee,{children:T(_3,{metadata:i,id:`iiif-${e}-metadata`})}):T(Ee,{}),T$=({rendering:i})=>(i==null?void 0:i.length)===0?T(Ee,{}):T(Ee,{children:[T("span",{className:"manifest-property-title",children:"Alternate formats"}),T(C3,{rendering:i})]}),E$=({requiredStatement:i,parent:e="manifest"})=>i?T(Ee,{children:T(P3,{requiredStatement:i,id:`iiif-${e}-required-statement`})}):T(Ee,{}),w$=({rights:i})=>i?T(Ee,{children:[T("span",{className:"manifest-property-title",children:"Rights"}),T("a",{href:i,target:"_blank",children:i})]}):T(Ee,{}),b$=({seeAlso:i})=>(i==null?void 0:i.length)===0?T(Ee,{}):T(Ee,{children:[T("span",{className:"manifest-property-title",children:"See Also"}),T(D3,{seeAlso:i})]}),_$=({summary:i,parent:e="manifest"})=>i?T(Ee,{children:T(O3,{summary:i,as:"p",id:`iiif-${e}-summary`})}):T(Ee,{}),A$=({label:i,thumbnail:e,objectFit:t="cover"})=>(e==null?void 0:e.length)===0?T(Ee,{}):T(Ee,{children:T(Q1,{altAsLabel:i||{none:["resource"]},thumbnail:e,style:{backgroundColor:"#6663",objectFit:t}})}),R$=()=>{const i=gt(),{activeManifest:e,vault:t}=i,[n,r]=se(),[s,o]=se([]),[a,l]=se([]),[c,u]=se([]),[d,h]=se([]);return ne(()=>{var p,g,m,v;const f=t.get(e);f&&(r(f),((p=f.homepage)==null?void 0:p.length)>0&&o(t.get(f.homepage)),((g=f.seeAlso)==null?void 0:g.length)>0&&l(t.get(f.seeAlso)),((m=f.rendering)==null?void 0:m.length)>0&&u(t.get(f.rendering)),((v=f.thumbnail)==null?void 0:v.length)>0&&h(t.get(f.thumbnail)))},[e,t]),n?T(v$,{children:T(m$,{children:[T(A$,{thumbnail:d,label:n.label,objectFit:"contain"}),T(_$,{summary:n.summary}),T(x$,{metadata:n.metadata}),T(E$,{requiredStatement:n.requiredStatement}),T(w$,{rights:n.rights}),T(y$,{homepage:s}),T(b$,{seeAlso:a}),T(T$,{rendering:c}),T(S$,{id:n.id,htmlLabel:"IIIF Manifest"})]})}):T(Ee,{})};function C$(i){const e=[];return i.forEach(t=>{var n;(n=t.informationPanel)!=null&&n.component&&e.push(t)}),{pluginsWithInfoPanel:e}}const I$=({contentStateAnnotation:i})=>{var a,l,c,u,d,h;const e=gt(),{vault:t}=e;if(!i)return T(Ee,{});const n=((a=i==null?void 0:i.target)==null?void 0:a.source)||(i==null?void 0:i.target),r=t.get(n==null?void 0:n.id),s=ns(t,r.id),o=(l=s==null?void 0:s[0])!=null&&l.service?((u=(c=s==null?void 0:s[0])==null?void 0:c.service[0])==null?void 0:u.id)||((h=(d=s==null?void 0:s[0])==null?void 0:d.service[0])==null?void 0:h["@id"]):void 0;return T(om,{"data-testid":"annotation-page",children:[r&&T("header",{children:[T(yr,{label:r.label})," ",T("em",{children:"(Shared)"})]}),T("div",{"data-testid":"annotation-page-items",children:T(Sm,{annotation:i,targetResource:o,isContentState:!0},i.id)})]})},P$=1500,L$=({activeCanvas:i,annotationResources:e,searchServiceUrl:t,setContentSearchResource:n,contentSearchResource:r,contentSearchCallback:s,initialSearchQuery:o})=>{var X,F;const{t:a}=dn(),l=Ti(),c=gt(),{contentStateAnnotation:u,informationPanelResource:d,isAutoScrolling:h,isUserScrolling:f,vault:p,configOptions:g,plugins:m}=c,{informationPanel:v}=g,y=v==null?void 0:v.renderAbout,S=v==null?void 0:v.renderAnnotation,x=p.get({id:i,type:"Canvas"}),E=v==null?void 0:v.renderContentSearch,C=v==null?void 0:v.renderToggle,b=(X=g==null?void 0:g.annotations)==null?void 0:X.motivations,I=((F=u==null?void 0:u.target)==null?void 0:F.source)||(u==null?void 0:u.target),D=!!u&&I.id===i,P=Ct(()=>e?b?e.map(U=>{var V;if(!((V=U==null?void 0:U.items)!=null&&V.length))return null;const j=U.items.filter(Z=>{const Q=p.get(Z.id);return $L(Q,b)});return j.length?{...U,items:j}:null}).filter(Boolean):e:[],[e,b,p]),k=!!(P!=null&&P.length)||D,{pluginsWithInfoPanel:N}=C$(m);function B(U,j){var Z,Q;const V=(Z=U==null?void 0:U.informationPanel)==null?void 0:Z.component;return V===void 0?T(Ee,{}):T(Yu,{value:U.id,children:T(If,{FallbackComponent:Of,children:T(V,{...(Q=U==null?void 0:U.informationPanel)==null?void 0:Q.componentProps,canvas:x,useViewerDispatch:Ti,useViewerState:gt})})},j)}const K=()=>{l({type:"updateInformationOpen",isInformationOpen:!1})};ne(()=>{["manifest-about","manifest-annotations","manifest-content-search"].includes(String(v==null?void 0:v.defaultTab))?l({type:"updateInformationPanelResource",informationPanelResource:v==null?void 0:v.defaultTab}):l(D?{type:"updateInformationPanelResource",informationPanelResource:"manifest-annotations"}:{type:"updateInformationPanelResource",informationPanelResource:"manifest-about"})},[]),ne(()=>{k||l({type:"updateInformationPanelResource",informationPanelResource:"manifest-about"})},[k]);function q(){if(!h){clearTimeout(f);const U=setTimeout(()=>{l({type:"updateUserScrolling",isUserScrolling:void 0})},P$);l({type:"updateUserScrolling",isUserScrolling:U})}}return T(GB,{"data-testid":"information-panel",defaultValue:d,onValueChange:U=>{l({type:"updateInformationPanelResource",informationPanelResource:U})},orientation:"horizontal",value:d,className:"clover-viewer-information-panel",children:[T(WB,{"aria-label":a("informationPanelTabs"),"data-testid":"information-panel-list",children:[C&&T(Nl,{value:"manifest-back","data-value":"manifest-back",onClick:K,as:"button",children:a("informationPanelTabsClose")}),y&&T(Nl,{value:"manifest-about",children:a("informationPanelTabsAbout")}),E&&r&&T(Nl,{value:"manifest-content-search",children:a("informationPanelTabsSearch")}),S&&k&&T(Nl,{value:"manifest-annotations",children:(v==null?void 0:v.annotationTabLabel)||a("informationPanelTabsAnnotations")}),N&&N.map((U,j)=>{var V;return T(Nl,{value:U.id,children:T(yr,{label:(V=U.informationPanel)==null?void 0:V.label})},j)})]}),T(jB,{handleScroll:q,children:[y&&T(Yu,{value:"manifest-about",children:T(R$,{})}),E&&r&&T(Yu,{value:"manifest-content-search",children:T(g$,{searchServiceUrl:t,setContentSearchResource:n,activeCanvas:i,annotationPage:r,contentSearchCallback:s,initialSearchQuery:o})}),S&&k&&P&&T(Yu,{value:"manifest-annotations",children:[u&&D&&T(I$,{contentStateAnnotation:u}),P.map(U=>T(M3,{annotationPage:U},U.id))]}),N&&N.map((U,j)=>B(U,j))]})]})},k$=()=>T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32",d:"M256 112v288M400 256H112"}),D$=()=>T(Ee,{children:[T("path",{d:"M232 416a23.88 23.88 0 01-14.2-4.68 8.27 8.27 0 01-.66-.51L125.76 336H56a24 24 0 01-24-24V200a24 24 0 0124-24h69.75l91.37-74.81a8.27 8.27 0 01.66-.51A24 24 0 01256 120v272a24 24 0 01-24 24zm-106.18-80zm-.27-159.86zM320 336a16 16 0 01-14.29-23.19c9.49-18.87 14.3-38 14.3-56.81 0-19.38-4.66-37.94-14.25-56.73a16 16 0 0128.5-14.54C346.19 208.12 352 231.44 352 256c0 23.86-6 47.81-17.7 71.19A16 16 0 01320 336z"}),T("path",{d:"M368 384a16 16 0 01-13.86-24C373.05 327.09 384 299.51 384 256c0-44.17-10.93-71.56-29.82-103.94a16 16 0 0127.64-16.12C402.92 172.11 416 204.81 416 256c0 50.43-13.06 83.29-34.13 120a16 16 0 01-13.87 8z"}),T("path",{d:"M416 432a16 16 0 01-13.39-24.74C429.85 365.47 448 323.76 448 256c0-66.5-18.18-108.62-45.49-151.39a16 16 0 1127-17.22C459.81 134.89 480 181.74 480 256c0 64.75-14.66 113.63-50.6 168.74A16 16 0 01416 432z"})]}),O$=()=>T("path",{d:"M289.94 256l95-95A24 24 0 00351 127l-95 95-95-95a24 24 0 00-34 34l95 95-95 95a24 24 0 1034 34l95-95 95 95a24 24 0 0034-34z"}),M$=()=>T(Ee,{children:[T("path",{d:"M336 176h40a40 40 0 0140 40v208a40 40 0 01-40 40H136a40 40 0 01-40-40V216a40 40 0 0140-40h40",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32"}),T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32",d:"M176 272l80 80 80-80M256 48v288"})]}),F$=()=>T("path",{d:"M416 64H96a64.07 64.07 0 00-64 64v256a64.07 64.07 0 0064 64h320a64.07 64.07 0 0064-64V128a64.07 64.07 0 00-64-64zm-80 64a48 48 0 11-48 48 48.05 48.05 0 0148-48zM96 416a32 32 0 01-32-32v-67.63l94.84-84.3a48.06 48.06 0 0165.8 1.9l64.95 64.81L172.37 416zm352-32a32 32 0 01-32 32H217.63l121.42-121.42a47.72 47.72 0 0161.64-.16L448 333.84z"}),N$=()=>T("path",{d:"M464 384.39a32 32 0 01-13-2.77 15.77 15.77 0 01-2.71-1.54l-82.71-58.22A32 32 0 01352 295.7v-79.4a32 32 0 0113.58-26.16l82.71-58.22a15.77 15.77 0 012.71-1.54 32 32 0 0145 29.24v192.76a32 32 0 01-32 32zM268 400H84a68.07 68.07 0 01-68-68V180a68.07 68.07 0 0168-68h184.48A67.6 67.6 0 01336 179.52V332a68.07 68.07 0 01-68 68z"}),c_=oe("svg",{display:"inline-flex",variants:{isLarge:{true:{height:"4rem",width:"4rem"}},isMedium:{true:{height:"2rem",width:"2rem"}},isSmall:{true:{height:"1rem",width:"1rem"}}}}),B$=({children:i})=>T("title",{children:i}),ri=i=>T(c_,{...i,"data-testid":"icon-svg",role:"img",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:i.children});ri.Title=B$,ri.Add=k$,ri.Audio=D$,ri.Close=O$,ri.Download=M$,ri.Image=F$,ri.Video=N$;function U$(i,e=globalThis==null?void 0:globalThis.document){const t=rs(i);ne(()=>{const n=r=>{r.key==="Escape"&&t(r)};return e.addEventListener("keydown",n,{capture:!0}),()=>e.removeEventListener("keydown",n,{capture:!0})},[t,e])}var $$="DismissableLayer",Am="dismissableLayer.update",H$="dismissableLayer.pointerDownOutside",z$="dismissableLayer.focusOutside",u_,d_=ln({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Rm=me((i,e)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:n,onPointerDownOutside:r,onFocusOutside:s,onInteractOutside:o,onDismiss:a,...l}=i,c=Cn(d_),[u,d]=se(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=se({}),p=ut(e,b=>d(b)),g=Array.from(c.layers),[m]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),v=g.indexOf(m),y=u?g.indexOf(u):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,x=y>=v,E=W$(b=>{const I=b.target,D=[...c.branches].some(P=>P.contains(I));!x||D||(r==null||r(b),o==null||o(b),b.defaultPrevented||a==null||a())},h),C=j$(b=>{const I=b.target;[...c.branches].some(P=>P.contains(I))||(s==null||s(b),o==null||o(b),b.defaultPrevented||a==null||a())},h);return U$(b=>{y===c.layers.size-1&&(n==null||n(b),!b.defaultPrevented&&a&&(b.preventDefault(),a()))},h),ne(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(u_=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),h_(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=u_)}},[u,h,t,c]),ne(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),h_())},[u,c]),ne(()=>{const b=()=>f({});return document.addEventListener(Am,b),()=>document.removeEventListener(Am,b)},[]),T(je.div,{...l,ref:p,style:{pointerEvents:S?x?"auto":"none":void 0,...i.style},onFocusCapture:Ge(i.onFocusCapture,C.onFocusCapture),onBlurCapture:Ge(i.onBlurCapture,C.onBlurCapture),onPointerDownCapture:Ge(i.onPointerDownCapture,E.onPointerDownCapture)})});Rm.displayName=$$;var V$="DismissableLayerBranch",G$=me((i,e)=>{const t=Cn(d_),n=ge(null),r=ut(e,n);return ne(()=>{const s=n.current;if(s)return t.branches.add(s),()=>{t.branches.delete(s)}},[t.branches]),T(je.div,{...i,ref:r})});G$.displayName=V$;function W$(i,e=globalThis==null?void 0:globalThis.document){const t=rs(i),n=ge(!1),r=ge(()=>{});return ne(()=>{const s=a=>{if(a.target&&!n.current){let l=function(){f_(H$,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",r.current),r.current=l,e.addEventListener("click",r.current,{once:!0})):l()}else e.removeEventListener("click",r.current);n.current=!1},o=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(o),e.removeEventListener("pointerdown",s),e.removeEventListener("click",r.current)}},[e,t]),{onPointerDownCapture:()=>n.current=!0}}function j$(i,e=globalThis==null?void 0:globalThis.document){const t=rs(i),n=ge(!1);return ne(()=>{const r=s=>{s.target&&!n.current&&f_(z$,t,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",r),()=>e.removeEventListener("focusin",r)},[e,t]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function h_(){const i=new CustomEvent(Am);document.dispatchEvent(i)}function f_(i,e,t,{discrete:n}){const r=t.originalEvent.target,s=new CustomEvent(i,{bubbles:!1,cancelable:!0,detail:t});e&&r.addEventListener(i,e,{once:!0}),n?dB(r,s):r.dispatchEvent(s)}var Cm=0;function p_(){ne(()=>{const i=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",i[0]??g_()),document.body.insertAdjacentElement("beforeend",i[1]??g_()),Cm++,()=>{Cm===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Cm--}},[])}function g_(){const i=document.createElement("span");return i.setAttribute("data-radix-focus-guard",""),i.tabIndex=0,i.style.outline="none",i.style.opacity="0",i.style.position="fixed",i.style.pointerEvents="none",i}var Im="focusScope.autoFocusOnMount",Pm="focusScope.autoFocusOnUnmount",m_={bubbles:!1,cancelable:!0},K$="FocusScope",Lm=me((i,e)=>{const{loop:t=!1,trapped:n=!1,onMountAutoFocus:r,onUnmountAutoFocus:s,...o}=i,[a,l]=se(null),c=rs(r),u=rs(s),d=ge(null),h=ut(e,g=>l(g)),f=ge({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;ne(()=>{if(n){let g=function(S){if(f.paused||!a)return;const x=S.target;a.contains(x)?d.current=x:ss(d.current,{select:!0})},m=function(S){if(f.paused||!a)return;const x=S.relatedTarget;x!==null&&(a.contains(x)||ss(d.current,{select:!0}))},v=function(S){if(document.activeElement===document.body)for(const E of S)E.removedNodes.length>0&&ss(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",m);const y=new MutationObserver(v);return a&&y.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",m),y.disconnect()}}},[n,a,f.paused]),ne(()=>{if(a){S_.add(f);const g=document.activeElement;if(!a.contains(g)){const v=new CustomEvent(Im,m_);a.addEventListener(Im,c),a.dispatchEvent(v),v.defaultPrevented||(q$(J$(v_(a)),{select:!0}),document.activeElement===g&&ss(a))}return()=>{a.removeEventListener(Im,c),setTimeout(()=>{const v=new CustomEvent(Pm,m_);a.addEventListener(Pm,u),a.dispatchEvent(v),v.defaultPrevented||ss(g??document.body,{select:!0}),a.removeEventListener(Pm,u),S_.remove(f)},0)}}},[a,c,u,f]);const p=Ce(g=>{if(!t&&!n||f.paused)return;const m=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,v=document.activeElement;if(m&&v){const y=g.currentTarget,[S,x]=Y$(y);S&&x?!g.shiftKey&&v===x?(g.preventDefault(),t&&ss(S,{select:!0})):g.shiftKey&&v===S&&(g.preventDefault(),t&&ss(x,{select:!0})):v===y&&g.preventDefault()}},[t,n,f.paused]);return T(je.div,{tabIndex:-1,...o,ref:h,onKeyDown:p})});Lm.displayName=K$;function q$(i,{select:e=!1}={}){const t=document.activeElement;for(const n of i)if(ss(n,{select:e}),document.activeElement!==t)return}function Y$(i){const e=v_(i),t=y_(e,i),n=y_(e.reverse(),i);return[t,n]}function v_(i){const e=[],t=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const r=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||r?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function y_(i,e){for(const t of i)if(!X$(t,{upTo:e}))return t}function X$(i,{upTo:e}){if(getComputedStyle(i).visibility==="hidden")return!0;for(;i;){if(e!==void 0&&i===e)return!1;if(getComputedStyle(i).display==="none")return!0;i=i.parentElement}return!1}function Z$(i){return i instanceof HTMLInputElement&&"select"in i}function ss(i,{select:e=!1}={}){if(i&&i.focus){const t=document.activeElement;i.focus({preventScroll:!0}),i!==t&&Z$(i)&&e&&i.select()}}var S_=Q$();function Q$(){let i=[];return{add(e){const t=i[0];e!==t&&(t==null||t.pause()),i=x_(i,e),i.unshift(e)},remove(e){var t;i=x_(i,e),(t=i[0])==null||t.resume()}}}function x_(i,e){const t=[...i],n=t.indexOf(e);return n!==-1&&t.splice(n,1),t}function J$(i){return i.filter(e=>e.tagName!=="A")}const e4=["top","right","bottom","left"],os=Math.min,Hi=Math.max,sd=Math.round,od=Math.floor,Bn=i=>({x:i,y:i}),t4={left:"right",right:"left",bottom:"top",top:"bottom"},i4={start:"end",end:"start"};function km(i,e,t){return Hi(i,os(e,t))}function xr(i,e){return typeof i=="function"?i(e):i}function Tr(i){return i.split("-")[0]}function ta(i){return i.split("-")[1]}function Dm(i){return i==="x"?"y":"x"}function Om(i){return i==="y"?"height":"width"}const n4=new Set(["top","bottom"]);function Un(i){return n4.has(Tr(i))?"y":"x"}function Mm(i){return Dm(Un(i))}function r4(i,e,t){t===void 0&&(t=!1);const n=ta(i),r=Mm(i),s=Om(r);let o=r==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(o=ad(o)),[o,ad(o)]}function s4(i){const e=ad(i);return[Fm(i),e,Fm(e)]}function Fm(i){return i.replace(/start|end/g,e=>i4[e])}const T_=["left","right"],E_=["right","left"],o4=["top","bottom"],a4=["bottom","top"];function l4(i,e,t){switch(i){case"top":case"bottom":return t?e?E_:T_:e?T_:E_;case"left":case"right":return e?o4:a4;default:return[]}}function c4(i,e,t,n){const r=ta(i);let s=l4(Tr(i),t==="start",n);return r&&(s=s.map(o=>o+"-"+r),e&&(s=s.concat(s.map(Fm)))),s}function ad(i){return i.replace(/left|right|bottom|top/g,e=>t4[e])}function u4(i){return{top:0,right:0,bottom:0,left:0,...i}}function w_(i){return typeof i!="number"?u4(i):{top:i,right:i,bottom:i,left:i}}function ld(i){const{x:e,y:t,width:n,height:r}=i;return{width:n,height:r,top:t,left:e,right:e+n,bottom:t+r,x:e,y:t}}function b_(i,e,t){let{reference:n,floating:r}=i;const s=Un(e),o=Mm(e),a=Om(o),l=Tr(e),c=s==="y",u=n.x+n.width/2-r.width/2,d=n.y+n.height/2-r.height/2,h=n[a]/2-r[a]/2;let f;switch(l){case"top":f={x:u,y:n.y-r.height};break;case"bottom":f={x:u,y:n.y+n.height};break;case"right":f={x:n.x+n.width,y:d};break;case"left":f={x:n.x-r.width,y:d};break;default:f={x:n.x,y:n.y}}switch(ta(e)){case"start":f[o]-=h*(t&&c?-1:1);break;case"end":f[o]+=h*(t&&c?-1:1);break}return f}const d4=async(i,e,t)=>{const{placement:n="bottom",strategy:r="absolute",middleware:s=[],platform:o}=t,a=s.filter(Boolean),l=await(o.isRTL==null?void 0:o.isRTL(e));let c=await o.getElementRects({reference:i,floating:e,strategy:r}),{x:u,y:d}=b_(c,n,l),h=n,f={},p=0;for(let g=0;g<a.length;g++){const{name:m,fn:v}=a[g],{x:y,y:S,data:x,reset:E}=await v({x:u,y:d,initialPlacement:n,placement:h,strategy:r,middlewareData:f,rects:c,platform:o,elements:{reference:i,floating:e}});u=y??u,d=S??d,f={...f,[m]:{...f[m],...x}},E&&p<=50&&(p++,typeof E=="object"&&(E.placement&&(h=E.placement),E.rects&&(c=E.rects===!0?await o.getElementRects({reference:i,floating:e,strategy:r}):E.rects),{x:u,y:d}=b_(c,h,l)),g=-1)}return{x:u,y:d,placement:h,strategy:r,middlewareData:f}};async function Gl(i,e){var t;e===void 0&&(e={});const{x:n,y:r,platform:s,rects:o,elements:a,strategy:l}=i,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:f=0}=xr(e,i),p=w_(f),m=a[h?d==="floating"?"reference":"floating":d],v=ld(await s.getClippingRect({element:(t=await(s.isElement==null?void 0:s.isElement(m)))==null||t?m:m.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),y=d==="floating"?{x:n,y:r,width:o.floating.width,height:o.floating.height}:o.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),x=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},E=ld(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:S,strategy:l}):y);return{top:(v.top-E.top+p.top)/x.y,bottom:(E.bottom-v.bottom+p.bottom)/x.y,left:(v.left-E.left+p.left)/x.x,right:(E.right-v.right+p.right)/x.x}}const h4=i=>({name:"arrow",options:i,async fn(e){const{x:t,y:n,placement:r,rects:s,platform:o,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=xr(i,e)||{};if(c==null)return{};const d=w_(u),h={x:t,y:n},f=Mm(r),p=Om(f),g=await o.getDimensions(c),m=f==="y",v=m?"top":"left",y=m?"bottom":"right",S=m?"clientHeight":"clientWidth",x=s.reference[p]+s.reference[f]-h[f]-s.floating[p],E=h[f]-s.reference[f],C=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c));let b=C?C[S]:0;(!b||!await(o.isElement==null?void 0:o.isElement(C)))&&(b=a.floating[S]||s.floating[p]);const I=x/2-E/2,D=b/2-g[p]/2-1,P=os(d[v],D),k=os(d[y],D),N=P,B=b-g[p]-k,K=b/2-g[p]/2+I,q=km(N,K,B),H=!l.arrow&&ta(r)!=null&&K!==q&&s.reference[p]/2-(K<N?P:k)-g[p]/2<0,X=H?K<N?K-N:K-B:0;return{[f]:h[f]+X,data:{[f]:q,centerOffset:K-q-X,...H&&{alignmentOffset:X}},reset:H}}}),f4=function(i){return i===void 0&&(i={}),{name:"flip",options:i,async fn(e){var t,n;const{placement:r,middlewareData:s,rects:o,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:p="none",flipAlignment:g=!0,...m}=xr(i,e);if((t=s.arrow)!=null&&t.alignmentOffset)return{};const v=Tr(r),y=Un(a),S=Tr(a)===a,x=await(l.isRTL==null?void 0:l.isRTL(c.floating)),E=h||(S||!g?[ad(a)]:s4(a)),C=p!=="none";!h&&C&&E.push(...c4(a,g,p,x));const b=[a,...E],I=await Gl(e,m),D=[];let P=((n=s.flip)==null?void 0:n.overflows)||[];if(u&&D.push(I[v]),d){const K=r4(r,o,x);D.push(I[K[0]],I[K[1]])}if(P=[...P,{placement:r,overflows:D}],!D.every(K=>K<=0)){var k,N;const K=(((k=s.flip)==null?void 0:k.index)||0)+1,q=b[K];if(q&&(!(d==="alignment"?y!==Un(q):!1)||P.every(F=>Un(F.placement)===y?F.overflows[0]>0:!0)))return{data:{index:K,overflows:P},reset:{placement:q}};let H=(N=P.filter(X=>X.overflows[0]<=0).sort((X,F)=>X.overflows[1]-F.overflows[1])[0])==null?void 0:N.placement;if(!H)switch(f){case"bestFit":{var B;const X=(B=P.filter(F=>{if(C){const U=Un(F.placement);return U===y||U==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(U=>U>0).reduce((U,j)=>U+j,0)]).sort((F,U)=>F[1]-U[1])[0])==null?void 0:B[0];X&&(H=X);break}case"initialPlacement":H=a;break}if(r!==H)return{reset:{placement:H}}}return{}}}};function __(i,e){return{top:i.top-e.height,right:i.right-e.width,bottom:i.bottom-e.height,left:i.left-e.width}}function A_(i){return e4.some(e=>i[e]>=0)}const p4=function(i){return i===void 0&&(i={}),{name:"hide",options:i,async fn(e){const{rects:t}=e,{strategy:n="referenceHidden",...r}=xr(i,e);switch(n){case"referenceHidden":{const s=await Gl(e,{...r,elementContext:"reference"}),o=__(s,t.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:A_(o)}}}case"escaped":{const s=await Gl(e,{...r,altBoundary:!0}),o=__(s,t.floating);return{data:{escapedOffsets:o,escaped:A_(o)}}}default:return{}}}}},R_=new Set(["left","top"]);async function g4(i,e){const{placement:t,platform:n,elements:r}=i,s=await(n.isRTL==null?void 0:n.isRTL(r.floating)),o=Tr(t),a=ta(t),l=Un(t)==="y",c=R_.has(o)?-1:1,u=s&&l?-1:1,d=xr(e,i);let{mainAxis:h,crossAxis:f,alignmentAxis:p}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof p=="number"&&(f=a==="end"?p*-1:p),l?{x:f*u,y:h*c}:{x:h*c,y:f*u}}const m4=function(i){return i===void 0&&(i=0),{name:"offset",options:i,async fn(e){var t,n;const{x:r,y:s,placement:o,middlewareData:a}=e,l=await g4(e,i);return o===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:r+l.x,y:s+l.y,data:{...l,placement:o}}}}},v4=function(i){return i===void 0&&(i={}),{name:"shift",options:i,async fn(e){const{x:t,y:n,placement:r}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:m=>{let{x:v,y}=m;return{x:v,y}}},...l}=xr(i,e),c={x:t,y:n},u=await Gl(e,l),d=Un(Tr(r)),h=Dm(d);let f=c[h],p=c[d];if(s){const m=h==="y"?"top":"left",v=h==="y"?"bottom":"right",y=f+u[m],S=f-u[v];f=km(y,f,S)}if(o){const m=d==="y"?"top":"left",v=d==="y"?"bottom":"right",y=p+u[m],S=p-u[v];p=km(y,p,S)}const g=a.fn({...e,[h]:f,[d]:p});return{...g,data:{x:g.x-t,y:g.y-n,enabled:{[h]:s,[d]:o}}}}}},y4=function(i){return i===void 0&&(i={}),{options:i,fn(e){const{x:t,y:n,placement:r,rects:s,middlewareData:o}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=xr(i,e),u={x:t,y:n},d=Un(r),h=Dm(d);let f=u[h],p=u[d];const g=xr(a,e),m=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const S=h==="y"?"height":"width",x=s.reference[h]-s.floating[S]+m.mainAxis,E=s.reference[h]+s.reference[S]-m.mainAxis;f<x?f=x:f>E&&(f=E)}if(c){var v,y;const S=h==="y"?"width":"height",x=R_.has(Tr(r)),E=s.reference[d]-s.floating[S]+(x&&((v=o.offset)==null?void 0:v[d])||0)+(x?0:m.crossAxis),C=s.reference[d]+s.reference[S]+(x?0:((y=o.offset)==null?void 0:y[d])||0)-(x?m.crossAxis:0);p<E?p=E:p>C&&(p=C)}return{[h]:f,[d]:p}}}},S4=function(i){return i===void 0&&(i={}),{name:"size",options:i,async fn(e){var t,n;const{placement:r,rects:s,platform:o,elements:a}=e,{apply:l=()=>{},...c}=xr(i,e),u=await Gl(e,c),d=Tr(r),h=ta(r),f=Un(r)==="y",{width:p,height:g}=s.floating;let m,v;d==="top"||d==="bottom"?(m=d,v=h===(await(o.isRTL==null?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=d,m=h==="end"?"top":"bottom");const y=g-u.top-u.bottom,S=p-u.left-u.right,x=os(g-u[m],y),E=os(p-u[v],S),C=!e.middlewareData.shift;let b=x,I=E;if((t=e.middlewareData.shift)!=null&&t.enabled.x&&(I=S),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(b=y),C&&!h){const P=Hi(u.left,0),k=Hi(u.right,0),N=Hi(u.top,0),B=Hi(u.bottom,0);f?I=p-2*(P!==0||k!==0?P+k:Hi(u.left,u.right)):b=g-2*(N!==0||B!==0?N+B:Hi(u.top,u.bottom))}await l({...e,availableWidth:I,availableHeight:b});const D=await o.getDimensions(a.floating);return p!==D.width||g!==D.height?{reset:{rects:!0}}:{}}}};function cd(){return typeof window<"u"}function ia(i){return C_(i)?(i.nodeName||"").toLowerCase():"#document"}function zi(i){var e;return(i==null||(e=i.ownerDocument)==null?void 0:e.defaultView)||window}function $n(i){var e;return(e=(C_(i)?i.ownerDocument:i.document)||window.document)==null?void 0:e.documentElement}function C_(i){return cd()?i instanceof Node||i instanceof zi(i).Node:!1}function Tn(i){return cd()?i instanceof Element||i instanceof zi(i).Element:!1}function Hn(i){return cd()?i instanceof HTMLElement||i instanceof zi(i).HTMLElement:!1}function I_(i){return!cd()||typeof ShadowRoot>"u"?!1:i instanceof ShadowRoot||i instanceof zi(i).ShadowRoot}const x4=new Set(["inline","contents"]);function Wl(i){const{overflow:e,overflowX:t,overflowY:n,display:r}=En(i);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&!x4.has(r)}const T4=new Set(["table","td","th"]);function E4(i){return T4.has(ia(i))}const w4=[":popover-open",":modal"];function ud(i){return w4.some(e=>{try{return i.matches(e)}catch{return!1}})}const b4=["transform","translate","scale","rotate","perspective"],_4=["transform","translate","scale","rotate","perspective","filter"],A4=["paint","layout","strict","content"];function Nm(i){const e=Bm(),t=Tn(i)?En(i):i;return b4.some(n=>t[n]?t[n]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!e&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!e&&(t.filter?t.filter!=="none":!1)||_4.some(n=>(t.willChange||"").includes(n))||A4.some(n=>(t.contain||"").includes(n))}function R4(i){let e=as(i);for(;Hn(e)&&!na(e);){if(Nm(e))return e;if(ud(e))return null;e=as(e)}return null}function Bm(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const C4=new Set(["html","body","#document"]);function na(i){return C4.has(ia(i))}function En(i){return zi(i).getComputedStyle(i)}function dd(i){return Tn(i)?{scrollLeft:i.scrollLeft,scrollTop:i.scrollTop}:{scrollLeft:i.scrollX,scrollTop:i.scrollY}}function as(i){if(ia(i)==="html")return i;const e=i.assignedSlot||i.parentNode||I_(i)&&i.host||$n(i);return I_(e)?e.host:e}function P_(i){const e=as(i);return na(e)?i.ownerDocument?i.ownerDocument.body:i.body:Hn(e)&&Wl(e)?e:P_(e)}function jl(i,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const r=P_(i),s=r===((n=i.ownerDocument)==null?void 0:n.body),o=zi(r);if(s){const a=Um(o);return e.concat(o,o.visualViewport||[],Wl(r)?r:[],a&&t?jl(a):[])}return e.concat(r,jl(r,[],t))}function Um(i){return i.parent&&Object.getPrototypeOf(i.parent)?i.frameElement:null}function L_(i){const e=En(i);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const r=Hn(i),s=r?i.offsetWidth:t,o=r?i.offsetHeight:n,a=sd(t)!==s||sd(n)!==o;return a&&(t=s,n=o),{width:t,height:n,$:a}}function $m(i){return Tn(i)?i:i.contextElement}function ra(i){const e=$m(i);if(!Hn(e))return Bn(1);const t=e.getBoundingClientRect(),{width:n,height:r,$:s}=L_(e);let o=(s?sd(t.width):t.width)/n,a=(s?sd(t.height):t.height)/r;return(!o||!Number.isFinite(o))&&(o=1),(!a||!Number.isFinite(a))&&(a=1),{x:o,y:a}}const I4=Bn(0);function k_(i){const e=zi(i);return!Bm()||!e.visualViewport?I4:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function P4(i,e,t){return e===void 0&&(e=!1),!t||e&&t!==zi(i)?!1:e}function Xs(i,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const r=i.getBoundingClientRect(),s=$m(i);let o=Bn(1);e&&(n?Tn(n)&&(o=ra(n)):o=ra(i));const a=P4(s,t,n)?k_(s):Bn(0);let l=(r.left+a.x)/o.x,c=(r.top+a.y)/o.y,u=r.width/o.x,d=r.height/o.y;if(s){const h=zi(s),f=n&&Tn(n)?zi(n):n;let p=h,g=Um(p);for(;g&&n&&f!==p;){const m=ra(g),v=g.getBoundingClientRect(),y=En(g),S=v.left+(g.clientLeft+parseFloat(y.paddingLeft))*m.x,x=v.top+(g.clientTop+parseFloat(y.paddingTop))*m.y;l*=m.x,c*=m.y,u*=m.x,d*=m.y,l+=S,c+=x,p=zi(g),g=Um(p)}}return ld({width:u,height:d,x:l,y:c})}function hd(i,e){const t=dd(i).scrollLeft;return e?e.left+t:Xs($n(i)).left+t}function D_(i,e){const t=i.getBoundingClientRect(),n=t.left+e.scrollLeft-hd(i,t),r=t.top+e.scrollTop;return{x:n,y:r}}function L4(i){let{elements:e,rect:t,offsetParent:n,strategy:r}=i;const s=r==="fixed",o=$n(n),a=e?ud(e.floating):!1;if(n===o||a&&s)return t;let l={scrollLeft:0,scrollTop:0},c=Bn(1);const u=Bn(0),d=Hn(n);if((d||!d&&!s)&&((ia(n)!=="body"||Wl(o))&&(l=dd(n)),Hn(n))){const f=Xs(n);c=ra(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}const h=o&&!d&&!s?D_(o,l):Bn(0);return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x+h.x,y:t.y*c.y-l.scrollTop*c.y+u.y+h.y}}function k4(i){return Array.from(i.getClientRects())}function D4(i){const e=$n(i),t=dd(i),n=i.ownerDocument.body,r=Hi(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),s=Hi(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+hd(i);const a=-t.scrollTop;return En(n).direction==="rtl"&&(o+=Hi(e.clientWidth,n.clientWidth)-r),{width:r,height:s,x:o,y:a}}const O_=25;function O4(i,e){const t=zi(i),n=$n(i),r=t.visualViewport;let s=n.clientWidth,o=n.clientHeight,a=0,l=0;if(r){s=r.width,o=r.height;const u=Bm();(!u||u&&e==="fixed")&&(a=r.offsetLeft,l=r.offsetTop)}const c=hd(n);if(c<=0){const u=n.ownerDocument,d=u.body,h=getComputedStyle(d),f=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,p=Math.abs(n.clientWidth-d.clientWidth-f);p<=O_&&(s-=p)}else c<=O_&&(s+=c);return{width:s,height:o,x:a,y:l}}const M4=new Set(["absolute","fixed"]);function F4(i,e){const t=Xs(i,!0,e==="fixed"),n=t.top+i.clientTop,r=t.left+i.clientLeft,s=Hn(i)?ra(i):Bn(1),o=i.clientWidth*s.x,a=i.clientHeight*s.y,l=r*s.x,c=n*s.y;return{width:o,height:a,x:l,y:c}}function M_(i,e,t){let n;if(e==="viewport")n=O4(i,t);else if(e==="document")n=D4($n(i));else if(Tn(e))n=F4(e,t);else{const r=k_(i);n={x:e.x-r.x,y:e.y-r.y,width:e.width,height:e.height}}return ld(n)}function F_(i,e){const t=as(i);return t===e||!Tn(t)||na(t)?!1:En(t).position==="fixed"||F_(t,e)}function N4(i,e){const t=e.get(i);if(t)return t;let n=jl(i,[],!1).filter(a=>Tn(a)&&ia(a)!=="body"),r=null;const s=En(i).position==="fixed";let o=s?as(i):i;for(;Tn(o)&&!na(o);){const a=En(o),l=Nm(o);!l&&a.position==="fixed"&&(r=null),(s?!l&&!r:!l&&a.position==="static"&&!!r&&M4.has(r.position)||Wl(o)&&!l&&F_(i,o))?n=n.filter(u=>u!==o):r=a,o=as(o)}return e.set(i,n),n}function B4(i){let{element:e,boundary:t,rootBoundary:n,strategy:r}=i;const o=[...t==="clippingAncestors"?ud(e)?[]:N4(e,this._c):[].concat(t),n],a=o[0],l=o.reduce((c,u)=>{const d=M_(e,u,r);return c.top=Hi(d.top,c.top),c.right=os(d.right,c.right),c.bottom=os(d.bottom,c.bottom),c.left=Hi(d.left,c.left),c},M_(e,a,r));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function U4(i){const{width:e,height:t}=L_(i);return{width:e,height:t}}function $4(i,e,t){const n=Hn(e),r=$n(e),s=t==="fixed",o=Xs(i,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=Bn(0);function c(){l.x=hd(r)}if(n||!n&&!s)if((ia(e)!=="body"||Wl(r))&&(a=dd(e)),n){const f=Xs(e,!0,s,e);l.x=f.x+e.clientLeft,l.y=f.y+e.clientTop}else r&&c();s&&!n&&r&&c();const u=r&&!n&&!s?D_(r,a):Bn(0),d=o.left+a.scrollLeft-l.x-u.x,h=o.top+a.scrollTop-l.y-u.y;return{x:d,y:h,width:o.width,height:o.height}}function Hm(i){return En(i).position==="static"}function N_(i,e){if(!Hn(i)||En(i).position==="fixed")return null;if(e)return e(i);let t=i.offsetParent;return $n(i)===t&&(t=t.ownerDocument.body),t}function B_(i,e){const t=zi(i);if(ud(i))return t;if(!Hn(i)){let r=as(i);for(;r&&!na(r);){if(Tn(r)&&!Hm(r))return r;r=as(r)}return t}let n=N_(i,e);for(;n&&E4(n)&&Hm(n);)n=N_(n,e);return n&&na(n)&&Hm(n)&&!Nm(n)?t:n||R4(i)||t}const H4=async function(i){const e=this.getOffsetParent||B_,t=this.getDimensions,n=await t(i.floating);return{reference:$4(i.reference,await e(i.floating),i.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function z4(i){return En(i).direction==="rtl"}const V4={convertOffsetParentRelativeRectToViewportRelativeRect:L4,getDocumentElement:$n,getClippingRect:B4,getOffsetParent:B_,getElementRects:H4,getClientRects:k4,getDimensions:U4,getScale:ra,isElement:Tn,isRTL:z4};function U_(i,e){return i.x===e.x&&i.y===e.y&&i.width===e.width&&i.height===e.height}function G4(i,e){let t=null,n;const r=$n(i);function s(){var a;clearTimeout(n),(a=t)==null||a.disconnect(),t=null}function o(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=i.getBoundingClientRect(),{left:u,top:d,width:h,height:f}=c;if(a||e(),!h||!f)return;const p=od(d),g=od(r.clientWidth-(u+h)),m=od(r.clientHeight-(d+f)),v=od(u),S={rootMargin:-p+"px "+-g+"px "+-m+"px "+-v+"px",threshold:Hi(0,os(1,l))||1};let x=!0;function E(C){const b=C[0].intersectionRatio;if(b!==l){if(!x)return o();b?o(!1,b):n=setTimeout(()=>{o(!1,1e-7)},1e3)}b===1&&!U_(c,i.getBoundingClientRect())&&o(),x=!1}try{t=new IntersectionObserver(E,{...S,root:r.ownerDocument})}catch{t=new IntersectionObserver(E,S)}t.observe(i)}return o(!0),s}function W4(i,e,t,n){n===void 0&&(n={});const{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=n,c=$m(i),u=r||s?[...c?jl(c):[],...jl(e)]:[];u.forEach(v=>{r&&v.addEventListener("scroll",t,{passive:!0}),s&&v.addEventListener("resize",t)});const d=c&&a?G4(c,t):null;let h=-1,f=null;o&&(f=new ResizeObserver(v=>{let[y]=v;y&&y.target===c&&f&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(e)})),t()}),c&&!l&&f.observe(c),f.observe(e));let p,g=l?Xs(i):null;l&&m();function m(){const v=Xs(i);g&&!U_(g,v)&&t(),g=v,p=requestAnimationFrame(m)}return t(),()=>{var v;u.forEach(y=>{r&&y.removeEventListener("scroll",t),s&&y.removeEventListener("resize",t)}),d==null||d(),(v=f)==null||v.disconnect(),f=null,l&&cancelAnimationFrame(p)}}const j4=m4,K4=v4,q4=f4,Y4=S4,X4=p4,$_=h4,Z4=y4,Q4=(i,e,t)=>{const n=new Map,r={platform:V4,...t},s={...r.platform,_c:n};return d4(i,e,{...r,platform:s})};var J4=typeof document<"u",eH=function(){},fd=J4?Ki:eH;function pd(i,e){if(i===e)return!0;if(typeof i!=typeof e)return!1;if(typeof i=="function"&&i.toString()===e.toString())return!0;let t,n,r;if(i&&e&&typeof i=="object"){if(Array.isArray(i)){if(t=i.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!pd(i[n],e[n]))return!1;return!0}if(r=Object.keys(i),t=r.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,r[n]))return!1;for(n=t;n--!==0;){const s=r[n];if(!(s==="_owner"&&i.$$typeof)&&!pd(i[s],e[s]))return!1}return!0}return i!==i&&e!==e}function H_(i){return typeof window>"u"?1:(i.ownerDocument.defaultView||window).devicePixelRatio||1}function z_(i,e){const t=H_(i);return Math.round(e*t)/t}function zm(i){const e=ge(i);return fd(()=>{e.current=i}),e}function tH(i){i===void 0&&(i={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:r,elements:{reference:s,floating:o}={},transform:a=!0,whileElementsMounted:l,open:c}=i,[u,d]=se({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=se(n);pd(h,n)||f(n);const[p,g]=se(null),[m,v]=se(null),y=Ce(F=>{F!==C.current&&(C.current=F,g(F))},[]),S=Ce(F=>{F!==b.current&&(b.current=F,v(F))},[]),x=s||p,E=o||m,C=ge(null),b=ge(null),I=ge(u),D=l!=null,P=zm(l),k=zm(r),N=zm(c),B=Ce(()=>{if(!C.current||!b.current)return;const F={placement:e,strategy:t,middleware:h};k.current&&(F.platform=k.current),Q4(C.current,b.current,F).then(U=>{const j={...U,isPositioned:N.current!==!1};K.current&&!pd(I.current,j)&&(I.current=j,Dl.flushSync(()=>{d(j)}))})},[h,e,t,k,N]);fd(()=>{c===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,d(F=>({...F,isPositioned:!1})))},[c]);const K=ge(!1);fd(()=>(K.current=!0,()=>{K.current=!1}),[]),fd(()=>{if(x&&(C.current=x),E&&(b.current=E),x&&E){if(P.current)return P.current(x,E,B);B()}},[x,E,B,P,D]);const q=Ct(()=>({reference:C,floating:b,setReference:y,setFloating:S}),[y,S]),H=Ct(()=>({reference:x,floating:E}),[x,E]),X=Ct(()=>{const F={position:t,left:0,top:0};if(!H.floating)return F;const U=z_(H.floating,u.x),j=z_(H.floating,u.y);return a?{...F,transform:"translate("+U+"px, "+j+"px)",...H_(H.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:U,top:j}},[t,a,H.floating,u.x,u.y]);return Ct(()=>({...u,update:B,refs:q,elements:H,floatingStyles:X}),[u,B,q,H,X])}const iH=i=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:i,fn(t){const{element:n,padding:r}=typeof i=="function"?i(t):i;return n&&e(n)?n.current!=null?$_({element:n.current,padding:r}).fn(t):{}:n?$_({element:n,padding:r}).fn(t):{}}}},nH=(i,e)=>({...j4(i),options:[i,e]}),rH=(i,e)=>({...K4(i),options:[i,e]}),sH=(i,e)=>({...Z4(i),options:[i,e]}),oH=(i,e)=>({...q4(i),options:[i,e]}),aH=(i,e)=>({...Y4(i),options:[i,e]}),lH=(i,e)=>({...X4(i),options:[i,e]}),cH=(i,e)=>({...iH(i),options:[i,e]});var uH="Arrow",V_=me((i,e)=>{const{children:t,width:n=10,height:r=5,...s}=i;return T(je.svg,{...s,ref:e,width:n,height:r,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:i.asChild?t:T("polygon",{points:"0,0 30,0 15,10"})})});V_.displayName=uH;var dH=V_,Vm="Popper",[G_,gd]=Ln(Vm),[hH,W_]=G_(Vm),j_=i=>{const{__scopePopper:e,children:t}=i,[n,r]=se(null);return T(hH,{scope:e,anchor:n,onAnchorChange:r,children:t})};j_.displayName=Vm;var K_="PopperAnchor",q_=me((i,e)=>{const{__scopePopper:t,virtualRef:n,...r}=i,s=W_(K_,t),o=ge(null),a=ut(e,o),l=ge(null);return ne(()=>{const c=l.current;l.current=(n==null?void 0:n.current)||o.current,c!==l.current&&s.onAnchorChange(l.current)}),n?null:T(je.div,{...r,ref:a})});q_.displayName=K_;var Gm="PopperContent",[fH,pH]=G_(Gm),Y_=me((i,e)=>{var de,Pe,qe,Le,Fe,Ue;const{__scopePopper:t,side:n="bottom",sideOffset:r=0,align:s="center",alignOffset:o=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:h=!1,updatePositionStrategy:f="optimized",onPlaced:p,...g}=i,m=W_(Gm,t),[v,y]=se(null),S=ut(e,Xe=>y(Xe)),[x,E]=se(null),C=mm(x),b=(C==null?void 0:C.width)??0,I=(C==null?void 0:C.height)??0,D=n+(s!=="center"?"-"+s:""),P=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},k=Array.isArray(c)?c:[c],N=k.length>0,B={padding:P,boundary:k.filter(mH),altBoundary:N},{refs:K,floatingStyles:q,placement:H,isPositioned:X,middlewareData:F}=tH({strategy:"fixed",placement:D,whileElementsMounted:(...Xe)=>W4(...Xe,{animationFrame:f==="always"}),elements:{reference:m.anchor},middleware:[nH({mainAxis:r+I,alignmentAxis:o}),l&&rH({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?sH():void 0,...B}),l&&oH({...B}),aH({...B,apply:({elements:Xe,rects:it,availableWidth:zt,availableHeight:De})=>{const{width:w,height:O}=it.reference,z=Xe.floating.style;z.setProperty("--radix-popper-available-width",`${zt}px`),z.setProperty("--radix-popper-available-height",`${De}px`),z.setProperty("--radix-popper-anchor-width",`${w}px`),z.setProperty("--radix-popper-anchor-height",`${O}px`)}}),x&&cH({element:x,padding:a}),vH({arrowWidth:b,arrowHeight:I}),h&&lH({strategy:"referenceHidden",...B})]}),[U,j]=Q_(H),V=rs(p);Yt(()=>{X&&(V==null||V())},[X,V]);const Z=(de=F.arrow)==null?void 0:de.x,Q=(Pe=F.arrow)==null?void 0:Pe.y,le=((qe=F.arrow)==null?void 0:qe.centerOffset)!==0,[re,ye]=se();return Yt(()=>{v&&ye(window.getComputedStyle(v).zIndex)},[v]),T("div",{ref:K.setFloating,"data-radix-popper-content-wrapper":"",style:{...q,transform:X?q.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[(Le=F.transformOrigin)==null?void 0:Le.x,(Fe=F.transformOrigin)==null?void 0:Fe.y].join(" "),...((Ue=F.hide)==null?void 0:Ue.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:i.dir,children:T(fH,{scope:t,placedSide:U,onArrowChange:E,arrowX:Z,arrowY:Q,shouldHideArrow:le,children:T(je.div,{"data-side":U,"data-align":j,...g,ref:S,style:{...g.style,animation:X?void 0:"none"}})})})});Y_.displayName=Gm;var X_="PopperArrow",gH={top:"bottom",right:"left",bottom:"top",left:"right"},Z_=me(function(e,t){const{__scopePopper:n,...r}=e,s=pH(X_,n),o=gH[s.placedSide];return T("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:T(dH,{...r,ref:t,style:{...r.style,display:"block"}})})});Z_.displayName=X_;function mH(i){return i!==null}var vH=i=>({name:"transformOrigin",options:i,fn(e){var m,v,y;const{placement:t,rects:n,middlewareData:r}=e,o=((m=r.arrow)==null?void 0:m.centerOffset)!==0,a=o?0:i.arrowWidth,l=o?0:i.arrowHeight,[c,u]=Q_(t),d={start:"0%",center:"50%",end:"100%"}[u],h=(((v=r.arrow)==null?void 0:v.x)??0)+a/2,f=(((y=r.arrow)==null?void 0:y.y)??0)+l/2;let p="",g="";return c==="bottom"?(p=o?d:`${h}px`,g=`${-l}px`):c==="top"?(p=o?d:`${h}px`,g=`${n.floating.height+l}px`):c==="right"?(p=`${-l}px`,g=o?d:`${f}px`):c==="left"&&(p=`${n.floating.width+l}px`,g=o?d:`${f}px`),{data:{x:p,y:g}}}});function Q_(i){const[e,t="center"]=i.split("-");return[e,t]}var J_=j_,Wm=q_,eA=Y_,tA=Z_,yH="Portal",iA=me((i,e)=>{var a;const{container:t,...n}=i,[r,s]=se(!1);Yt(()=>s(!0),[]);const o=t||r&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return o?rB.createPortal(T(je.div,{...n,ref:e}),o):null});iA.displayName=yH;var SH=function(i){if(typeof document>"u")return null;var e=Array.isArray(i)?i[0]:i;return e.ownerDocument.body},sa=new WeakMap,md=new WeakMap,vd={},jm=0,nA=function(i){return i&&(i.host||nA(i.parentNode))},xH=function(i,e){return e.map(function(t){if(i.contains(t))return t;var n=nA(t);return n&&i.contains(n)?n:(console.error("aria-hidden",t,"in not contained inside",i,". Doing nothing"),null)}).filter(function(t){return!!t})},TH=function(i,e,t,n){var r=xH(e,Array.isArray(i)?i:[i]);vd[t]||(vd[t]=new WeakMap);var s=vd[t],o=[],a=new Set,l=new Set(r),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};r.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(h){if(a.has(h))u(h);else try{var f=h.getAttribute(n),p=f!==null&&f!=="false",g=(sa.get(h)||0)+1,m=(s.get(h)||0)+1;sa.set(h,g),s.set(h,m),o.push(h),g===1&&p&&md.set(h,!0),m===1&&h.setAttribute(t,"true"),p||h.setAttribute(n,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return u(e),a.clear(),jm++,function(){o.forEach(function(d){var h=sa.get(d)-1,f=s.get(d)-1;sa.set(d,h),s.set(d,f),h||(md.has(d)||d.removeAttribute(n),md.delete(d)),f||d.removeAttribute(t)}),jm--,jm||(sa=new WeakMap,sa=new WeakMap,md=new WeakMap,vd={})}},rA=function(i,e,t){t===void 0&&(t="data-aria-hidden");var n=Array.from(Array.isArray(i)?i:[i]),r=SH(i);return r?(n.push.apply(n,Array.from(r.querySelectorAll("[aria-live], script"))),TH(n,r,t,"aria-hidden")):function(){return null}},zn=function(){return zn=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},zn.apply(this,arguments)};function sA(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function EH(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return i.concat(s||Array.prototype.slice.call(e))}typeof SuppressedError=="function"&&SuppressedError;var yd="right-scroll-bar-position",Sd="width-before-scroll-bar",wH="with-scroll-bars-hidden",bH="--removed-body-scroll-bar-size";function Km(i,e){return typeof i=="function"?i(e):i&&(i.current=e),i}function _H(i,e){var t=se(function(){return{value:i,callback:e,facade:{get current(){return t.value},set current(n){var r=t.value;r!==n&&(t.value=n,t.callback(n,r))}}}})[0];return t.callback=e,t.facade}var AH=typeof window<"u"?Ki:ne,oA=new WeakMap;function RH(i,e){var t=_H(null,function(n){return i.forEach(function(r){return Km(r,n)})});return AH(function(){var n=oA.get(t);if(n){var r=new Set(n),s=new Set(i),o=t.current;r.forEach(function(a){s.has(a)||Km(a,null)}),s.forEach(function(a){r.has(a)||Km(a,o)})}oA.set(t,i)},[i]),t}function CH(i){return i}function IH(i,e){e===void 0&&(e=CH);var t=[],n=!1,r={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return t.length?t[t.length-1]:i},useMedium:function(s){var o=e(s,n);return t.push(o),function(){t=t.filter(function(a){return a!==o})}},assignSyncMedium:function(s){for(n=!0;t.length;){var o=t;t=[],o.forEach(s)}t={push:function(a){return s(a)},filter:function(){return t}}},assignMedium:function(s){n=!0;var o=[];if(t.length){var a=t;t=[],a.forEach(s),o=t}var l=function(){var u=o;o=[],u.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),t={push:function(u){o.push(u),c()},filter:function(u){return o=o.filter(u),t}}}};return r}function PH(i){i===void 0&&(i={});var e=IH(null);return e.options=zn({async:!0,ssr:!1},i),e}var aA=function(i){var e=i.sideCar,t=sA(i,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=e.read();if(!n)throw new Error("Sidecar medium not found");return Ve(n,zn({},t))};aA.isSideCarExport=!0;function LH(i,e){return i.useMedium(e),aA}var lA=PH(),qm=function(){},xd=me(function(i,e){var t=ge(null),n=se({onScrollCapture:qm,onWheelCapture:qm,onTouchMoveCapture:qm}),r=n[0],s=n[1],o=i.forwardProps,a=i.children,l=i.className,c=i.removeScrollBar,u=i.enabled,d=i.shards,h=i.sideCar,f=i.noRelative,p=i.noIsolation,g=i.inert,m=i.allowPinchZoom,v=i.as,y=v===void 0?"div":v,S=i.gapMode,x=sA(i,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),E=h,C=RH([t,e]),b=zn(zn({},x),r);return Ve(Ee,null,u&&Ve(E,{sideCar:lA,removeScrollBar:c,shards:d,noRelative:f,noIsolation:p,inert:g,setCallbacks:s,allowPinchZoom:!!m,lockRef:t,gapMode:S}),o?tr(xi.only(a),zn(zn({},b),{ref:C})):Ve(y,zn({},b,{className:l,ref:C}),a))});xd.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},xd.classNames={fullWidth:Sd,zeroRight:yd};var kH=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function DH(){if(!document)return null;var i=document.createElement("style");i.type="text/css";var e=kH();return e&&i.setAttribute("nonce",e),i}function OH(i,e){i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}function MH(i){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(i)}var FH=function(){var i=0,e=null;return{add:function(t){i==0&&(e=DH())&&(OH(e,t),MH(e)),i++},remove:function(){i--,!i&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},NH=function(){var i=FH();return function(e,t){ne(function(){return i.add(e),function(){i.remove()}},[e&&t])}},cA=function(){var i=NH(),e=function(t){var n=t.styles,r=t.dynamic;return i(n,r),null};return e},BH={left:0,top:0,right:0,gap:0},Ym=function(i){return parseInt(i||"",10)||0},UH=function(i){var e=window.getComputedStyle(document.body),t=e[i==="padding"?"paddingLeft":"marginLeft"],n=e[i==="padding"?"paddingTop":"marginTop"],r=e[i==="padding"?"paddingRight":"marginRight"];return[Ym(t),Ym(n),Ym(r)]},$H=function(i){if(i===void 0&&(i="margin"),typeof window>"u")return BH;var e=UH(i),t=document.documentElement.clientWidth,n=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,n-t+e[2]-e[0])}},HH=cA(),oa="data-scroll-locked",zH=function(i,e,t,n){var r=i.left,s=i.top,o=i.right,a=i.gap;return t===void 0&&(t="margin"),`
|
|
81
|
+
.`.concat(wH,` {
|
|
82
|
+
overflow: hidden `).concat(n,`;
|
|
83
|
+
padding-right: `).concat(a,"px ").concat(n,`;
|
|
84
|
+
}
|
|
85
|
+
body[`).concat(oa,`] {
|
|
86
|
+
overflow: hidden `).concat(n,`;
|
|
87
|
+
overscroll-behavior: contain;
|
|
88
|
+
`).concat([e&&"position: relative ".concat(n,";"),t==="margin"&&`
|
|
89
|
+
padding-left: `.concat(r,`px;
|
|
90
|
+
padding-top: `).concat(s,`px;
|
|
91
|
+
padding-right: `).concat(o,`px;
|
|
92
|
+
margin-left:0;
|
|
93
|
+
margin-top:0;
|
|
94
|
+
margin-right: `).concat(a,"px ").concat(n,`;
|
|
95
|
+
`),t==="padding"&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
.`).concat(yd,` {
|
|
99
|
+
right: `).concat(a,"px ").concat(n,`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
.`).concat(Sd,` {
|
|
103
|
+
margin-right: `).concat(a,"px ").concat(n,`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
.`).concat(yd," .").concat(yd,` {
|
|
107
|
+
right: 0 `).concat(n,`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
.`).concat(Sd," .").concat(Sd,` {
|
|
111
|
+
margin-right: 0 `).concat(n,`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
body[`).concat(oa,`] {
|
|
115
|
+
`).concat(bH,": ").concat(a,`px;
|
|
116
|
+
}
|
|
117
|
+
`)},uA=function(){var i=parseInt(document.body.getAttribute(oa)||"0",10);return isFinite(i)?i:0},VH=function(){ne(function(){return document.body.setAttribute(oa,(uA()+1).toString()),function(){var i=uA()-1;i<=0?document.body.removeAttribute(oa):document.body.setAttribute(oa,i.toString())}},[])},GH=function(i){var e=i.noRelative,t=i.noImportant,n=i.gapMode,r=n===void 0?"margin":n;VH();var s=Ct(function(){return $H(r)},[r]);return Ve(HH,{styles:zH(s,!e,r,t?"":"!important")})},Xm=!1;if(typeof window<"u")try{var Td=Object.defineProperty({},"passive",{get:function(){return Xm=!0,!0}});window.addEventListener("test",Td,Td),window.removeEventListener("test",Td,Td)}catch{Xm=!1}var aa=Xm?{passive:!1}:!1,WH=function(i){return i.tagName==="TEXTAREA"},dA=function(i,e){if(!(i instanceof Element))return!1;var t=window.getComputedStyle(i);return t[e]!=="hidden"&&!(t.overflowY===t.overflowX&&!WH(i)&&t[e]==="visible")},jH=function(i){return dA(i,"overflowY")},KH=function(i){return dA(i,"overflowX")},hA=function(i,e){var t=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=fA(i,n);if(r){var s=pA(i,n),o=s[1],a=s[2];if(o>a)return!0}n=n.parentNode}while(n&&n!==t.body);return!1},qH=function(i){var e=i.scrollTop,t=i.scrollHeight,n=i.clientHeight;return[e,t,n]},YH=function(i){var e=i.scrollLeft,t=i.scrollWidth,n=i.clientWidth;return[e,t,n]},fA=function(i,e){return i==="v"?jH(e):KH(e)},pA=function(i,e){return i==="v"?qH(e):YH(e)},XH=function(i,e){return i==="h"&&e==="rtl"?-1:1},ZH=function(i,e,t,n,r){var s=XH(i,window.getComputedStyle(e).direction),o=s*n,a=t.target,l=e.contains(a),c=!1,u=o>0,d=0,h=0;do{if(!a)break;var f=pA(i,a),p=f[0],g=f[1],m=f[2],v=g-m-s*p;(p||v)&&fA(i,a)&&(d+=v,h+=p);var y=a.parentNode;a=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&Math.abs(d)<1||!u&&Math.abs(h)<1)&&(c=!0),c},Ed=function(i){return"changedTouches"in i?[i.changedTouches[0].clientX,i.changedTouches[0].clientY]:[0,0]},gA=function(i){return[i.deltaX,i.deltaY]},mA=function(i){return i&&"current"in i?i.current:i},QH=function(i,e){return i[0]===e[0]&&i[1]===e[1]},JH=function(i){return`
|
|
118
|
+
.block-interactivity-`.concat(i,` {pointer-events: none;}
|
|
119
|
+
.allow-interactivity-`).concat(i,` {pointer-events: all;}
|
|
120
|
+
`)},e6=0,la=[];function t6(i){var e=ge([]),t=ge([0,0]),n=ge(),r=se(e6++)[0],s=se(cA)[0],o=ge(i);ne(function(){o.current=i},[i]),ne(function(){if(i.inert){document.body.classList.add("block-interactivity-".concat(r));var g=EH([i.lockRef.current],(i.shards||[]).map(mA),!0).filter(Boolean);return g.forEach(function(m){return m.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),g.forEach(function(m){return m.classList.remove("allow-interactivity-".concat(r))})}}},[i.inert,i.lockRef.current,i.shards]);var a=Ce(function(g,m){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!o.current.allowPinchZoom;var v=Ed(g),y=t.current,S="deltaX"in g?g.deltaX:y[0]-v[0],x="deltaY"in g?g.deltaY:y[1]-v[1],E,C=g.target,b=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in g&&b==="h"&&C.type==="range")return!1;var I=hA(b,C);if(!I)return!0;if(I?E=b:(E=b==="v"?"h":"v",I=hA(b,C)),!I)return!1;if(!n.current&&"changedTouches"in g&&(S||x)&&(n.current=E),!E)return!0;var D=n.current||E;return ZH(D,m,g,D==="h"?S:x)},[]),l=Ce(function(g){var m=g;if(!(!la.length||la[la.length-1]!==s)){var v="deltaY"in m?gA(m):Ed(m),y=e.current.filter(function(E){return E.name===m.type&&(E.target===m.target||m.target===E.shadowParent)&&QH(E.delta,v)})[0];if(y&&y.should){m.cancelable&&m.preventDefault();return}if(!y){var S=(o.current.shards||[]).map(mA).filter(Boolean).filter(function(E){return E.contains(m.target)}),x=S.length>0?a(m,S[0]):!o.current.noIsolation;x&&m.cancelable&&m.preventDefault()}}},[]),c=Ce(function(g,m,v,y){var S={name:g,delta:m,target:v,should:y,shadowParent:i6(v)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),u=Ce(function(g){t.current=Ed(g),n.current=void 0},[]),d=Ce(function(g){c(g.type,gA(g),g.target,a(g,i.lockRef.current))},[]),h=Ce(function(g){c(g.type,Ed(g),g.target,a(g,i.lockRef.current))},[]);ne(function(){return la.push(s),i.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,aa),document.addEventListener("touchmove",l,aa),document.addEventListener("touchstart",u,aa),function(){la=la.filter(function(g){return g!==s}),document.removeEventListener("wheel",l,aa),document.removeEventListener("touchmove",l,aa),document.removeEventListener("touchstart",u,aa)}},[]);var f=i.removeScrollBar,p=i.inert;return Ve(Ee,null,p?Ve(s,{styles:JH(r)}):null,f?Ve(GH,{noRelative:i.noRelative,gapMode:i.gapMode}):null)}function i6(i){for(var e=null;i!==null;)i instanceof ShadowRoot&&(e=i.host,i=i.host),i=i.parentNode;return e}const n6=LH(lA,t6);var Zm=me(function(i,e){return Ve(xd,zn({},i,{ref:e,sideCar:n6}))});Zm.classNames=xd.classNames;var wd="Popover",[vA]=Ln(wd,[gd]),Kl=gd(),[r6,Zs]=vA(wd),yA=i=>{const{__scopePopover:e,children:t,open:n,defaultOpen:r,onOpenChange:s,modal:o=!1}=i,a=Kl(e),l=ge(null),[c,u]=se(!1),[d,h]=Fr({prop:n,defaultProp:r??!1,onChange:s,caller:wd});return T(J_,{...a,children:T(r6,{scope:e,contentId:qs(),triggerRef:l,open:d,onOpenChange:h,onOpenToggle:Ce(()=>h(f=>!f),[h]),hasCustomAnchor:c,onCustomAnchorAdd:Ce(()=>u(!0),[]),onCustomAnchorRemove:Ce(()=>u(!1),[]),modal:o,children:t})})};yA.displayName=wd;var SA="PopoverAnchor",s6=me((i,e)=>{const{__scopePopover:t,...n}=i,r=Zs(SA,t),s=Kl(t),{onCustomAnchorAdd:o,onCustomAnchorRemove:a}=r;return ne(()=>(o(),()=>a()),[o,a]),T(Wm,{...s,...n,ref:e})});s6.displayName=SA;var xA="PopoverTrigger",TA=me((i,e)=>{const{__scopePopover:t,...n}=i,r=Zs(xA,t),s=Kl(t),o=ut(e,r.triggerRef),a=T(je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":RA(r.open),...n,ref:o,onClick:Ge(i.onClick,r.onOpenToggle)});return r.hasCustomAnchor?a:T(Wm,{asChild:!0,...s,children:a})});TA.displayName=xA;var o6="PopoverPortal",[YY,a6]=vA(o6,{forceMount:void 0}),ca="PopoverContent",EA=me((i,e)=>{const t=a6(ca,i.__scopePopover),{forceMount:n=t.forceMount,...r}=i,s=Zs(ca,i.__scopePopover);return T(Ml,{present:n||s.open,children:s.modal?T(c6,{...r,ref:e}):T(u6,{...r,ref:e})})});EA.displayName=ca;var l6=Ol("PopoverContent.RemoveScroll"),c6=me((i,e)=>{const t=Zs(ca,i.__scopePopover),n=ge(null),r=ut(e,n),s=ge(!1);return ne(()=>{const o=n.current;if(o)return rA(o)},[]),T(Zm,{as:l6,allowPinchZoom:!0,children:T(wA,{...i,ref:r,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(i.onCloseAutoFocus,o=>{var a;o.preventDefault(),s.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ge(i.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;s.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Ge(i.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),u6=me((i,e)=>{const t=Zs(ca,i.__scopePopover),n=ge(!1),r=ge(!1);return T(wA,{...i,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,a;(o=i.onCloseAutoFocus)==null||o.call(i,s),s.defaultPrevented||(n.current||(a=t.triggerRef.current)==null||a.focus(),s.preventDefault()),n.current=!1,r.current=!1},onInteractOutside:s=>{var l,c;(l=i.onInteractOutside)==null||l.call(i,s),s.defaultPrevented||(n.current=!0,s.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const o=s.target;((c=t.triggerRef.current)==null?void 0:c.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&r.current&&s.preventDefault()}})}),wA=me((i,e)=>{const{__scopePopover:t,trapFocus:n,onOpenAutoFocus:r,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=i,h=Zs(ca,t),f=Kl(t);return p_(),T(Lm,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:r,onUnmountAutoFocus:s,children:T(Rm,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>h.onOpenChange(!1),children:T(eA,{"data-state":RA(h.open),role:"dialog",id:h.contentId,...f,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),bA="PopoverClose",_A=me((i,e)=>{const{__scopePopover:t,...n}=i,r=Zs(bA,t);return T(je.button,{type:"button",...n,ref:e,onClick:Ge(i.onClick,()=>r.onOpenChange(!1))})});_A.displayName=bA;var d6="PopoverArrow",AA=me((i,e)=>{const{__scopePopover:t,...n}=i,r=Kl(t);return T(tA,{...r,...n,ref:e})});AA.displayName=d6;function RA(i){return i?"open":"closed"}var h6=yA,f6=TA,p6=EA,g6=_A,m6=AA;const v6=Mx({"0%":{opacity:0,transform:"translateY(1rem)"},"100%":{opacity:1,transform:"translateY(0)"}}),y6=Mx({"0%":{opacity:0,transform:"translateY(1rem)"},"100%":{opacity:1,transform:"translateY(0)"}}),CA=oe(m6,{fill:"$secondaryAlt"}),S6=oe(g6,{position:"absolute",right:"0",top:"0",padding:"0.5rem",margin:"0",cursor:"pointer",border:"none",background:"none",fill:"inherit","&:hover":{opacity:"0.75"}}),x6=oe(p6,{border:"none",backgroundColor:"white",fill:"inhrerit",padding:"1rem 2rem 1rem 1rem",width:"auto",minWidth:"200px",maxWidth:"350px",borderRadius:"3px",boxShadow:"5px 5px 13px #0002",animationDuration:"0.3s",animationTimingFunction:"cubic-bezier(0.16, 1, 0.3, 1)",'&[data-side="top"]':{animationName:y6},'&[data-side="bottom"]':{animationName:v6},'&[data-align="end"]':{[`& ${CA}`]:{margin:"0 0.7rem"}}}),T6=oe(f6,{display:"inline-flex",padding:"0.5rem 0",margin:"0 0.5rem 0 0",cursor:"pointer",border:"none",background:"none","> button, > span":{margin:"0"}}),E6=oe(h6,{boxSizing:"content-box"}),w6=i=>T(T6,{...i,children:i.children}),b6=i=>T(x6,{...i,sideOffset:5,collisionPadding:21,children:[T(CA,{}),T(S6,{children:T(ri,{isSmall:!0,children:T(ri.Close,{})})}),i.children]}),Qs=({children:i})=>T(E6,{children:i});Qs.Trigger=w6,Qs.Content=b6;const bd=oe("div",{boxSizing:"border-box",display:"inline-flex",alignItems:"center",borderRadius:"2px",padding:"$1",marginBottom:"$2",marginRight:"$2",backgroundColor:"$lightGrey",color:"$richBlack50",textTransform:"uppercase",fontSize:"$2",objectFit:"contain",lineHeight:"1em !important","&:last-child":{marginRight:"0"},[`${c_}`]:{position:"absolute",left:"$1",height:"$3",width:"$3"},variants:{isIcon:{true:{position:"relative",paddingLeft:"$5"}}}}),_d=oe("span",{background:"transparent",opacity:"0",border:"3px solid transparent",position:"absolute",width:"100%",height:"100%",zIndex:"0",left:"0",top:"0",transition:"$all"}),IA=oe("span",{display:"flex"}),_6=oe("span",{display:"flex",width:"1.2111rem",height:"0.7222rem"}),A6=oe("span",{display:"inline-flex",marginLeft:"5px",marginBottom:"-1px"}),Ad=oe("div",{position:"relative",display:"flex",backgroundColor:"$secondaryAlt",width:"inherit",height:"100px",overflow:"hidden",borderRadius:"3px",".media-thumbnail-lazyload":{width:"100%",height:"100%",borderRadius:"3px"},img:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"top center",filter:"blur(0)",transform:"scale3d(1, 1, 1)",borderRadius:"3px",transition:"$all",color:"transparent"},[`& ${IA}`]:{position:"absolute",right:"0",bottom:"0",[`& ${bd}`]:{display:"none",margin:"0",paddingLeft:"0",fontSize:"0.7222rem",backgroundColor:"#000d",color:"$secondary",fill:"$secondary",borderBottomLeftRadius:"0",borderTopRightRadius:"0"}}}),Qm=oe(V1,{display:"flex",flexShrink:"0",padding:"0",cursor:"pointer",background:"none",border:"none",fontFamily:"inherit",lineHeight:"1.25em",fontSize:"1rem",textAlign:"left",figure:{margin:"0",width:"161.8px",figcaption:{marginTop:"0.5rem",fontWeight:"400",fontSize:"0.8333rem",display:"-webkit-box",overflow:"hidden",MozBoxOrient:"vertical",WebkitBoxOrient:"vertical",WebkitLineClamp:"5","@sm":{fontSize:"0.8333rem"}}}}),R6=oe(z1,{display:"flex",flexDirection:"row",flexGrow:"1",overflowX:"scroll",position:"relative",zIndex:"0",gap:"1rem",padding:"1.618rem 0"}),C6=oe("div",{display:"flex",flexDirection:"row","&[data-active='true']":{[`& ${Qm}`]:{figcaption:{fontWeight:"700"},[`& ${bd}`]:{backgroundColor:"$accent"},[`& ${_d}`]:{background:"#0003",opacity:"1",borderBottom:"3px solid $accent"},"&:first-of-type":{[`& ${_d}`]:{borderRight:"unset"}},"&:last-of-type":{[`& ${_d}`]:{borderLeft:"unset"}}}},[`& ${Qm}`]:{[`& ${Ad}`]:{borderRadius:"unset"},"&:first-of-type":{[`& ${Ad}`]:{borderTopLeftRadius:"3px",borderBottomLeftRadius:"3px"}},"&:last-of-type":{[`& ${Ad}`]:{borderTopRightRadius:"3px",borderBottomRightRadius:"3px"},[`& ${bd}`]:{display:"flex"}}}}),PA=oe("div",{position:"absolute",right:"1rem",top:"1rem",display:"flex",justifyContent:"flex-end",zIndex:"1"}),I6=oe("input",{flexGrow:"1",border:"none",backgroundColor:"$secondaryMuted",color:"$primary",marginRight:"1rem",height:"2rem",padding:"0 1rem",borderRadius:"2rem",fontFamily:"inherit",fontSize:"1rem",lineHeight:"1rem",boxShadow:"inset 1px 1px 2px #0001","&::placeholder":{color:"$primaryMuted"}}),ql=oe("button",{display:"flex",background:"none",border:"none",width:"2rem !important",height:"2rem !important",padding:"0",margin:"0",fontWeight:"700",borderRadius:"2rem",backgroundColor:"$accent",color:"$secondary",cursor:"pointer",boxSizing:"content-box !important",transition:"$all",svg:{height:"60%",width:"60%",padding:"20%",fill:"$secondary",stroke:"$secondary",opacity:"1",filter:"drop-shadow(5px 5px 5px #000D)",boxSizing:"inherit",transition:"$all"},"&:disabled":{backgroundColor:"transparent",boxShadow:"none",svg:{opacity:"0.25"}}}),P6=oe("div",{display:"flex",marginRight:"0.618rem",backgroundColor:"$accentAlt",borderRadius:"2rem",boxShadow:"5px 5px 5px #0003",color:"$secondary",alignItems:"center","> span":{display:"flex",margin:"0 0.5rem",fontSize:"0.7222rem",fontWeight:"bold",gap:"0.25rem",em:{opacity:"0.25"}}}),L6=oe("div",{display:"flex",position:"relative",zIndex:"1",width:"100%",padding:"0",transition:"$all",variants:{isToggle:{true:{paddingTop:"2.618rem",[`& ${PA}`]:{width:"calc(100% - 2rem)","@sm":{width:"calc(100% - 2rem)"}}}}}}),k6=(i,e)=>{ne(()=>{function t(n){n.key===i&&e()}return window.addEventListener("keyup",t),()=>window.removeEventListener("keyup",t)},[])},LA=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:"10",strokeWidth:"45",d:"M244 400L100 256l144-144M120 256h292"})]}),kA=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:"10",strokeWidth:"45",d:"M268 112l144 144-144 144M392 256H100"})]}),D6=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M289.94 256l95-95A24 24 0 00351 127l-95 95-95-95a24 24 0 00-34 34l95 95-95 95a24 24 0 1034 34l95-95 95 95a24 24 0 0034-34z"})]}),O6=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M456.69 421.39L362.6 327.3a173.81 173.81 0 0034.84-104.58C397.44 126.38 319.06 48 222.72 48S48 126.38 48 222.72s78.38 174.72 174.72 174.72A173.81 173.81 0 00327.3 362.6l94.09 94.09a25 25 0 0035.3-35.3zM97.92 222.72a124.8 124.8 0 11124.8 124.8 124.95 124.95 0 01-124.8-124.8z"})]}),M6=({handleCanvasToggle:i,handleFilter:e,activeIndex:t,canvasLength:n,isRtlPaged:r=!1})=>{const[s,o]=se(!1),[a,l]=se(!1),[c,u]=se(!1),{t:d}=dn();ne(()=>{u(t===0),t===n-1?l(!0):l(!1)},[t,n]),k6("Escape",()=>{o(!1),e("")});const h=()=>{o(p=>!p),e("")};return T(L6,{isToggle:s,className:"clover-viewer-media-controls",children:T(PA,{children:[s&&T(I6,{autoFocus:!0,onChange:p=>e(p.target.value),placeholder:d("commonSearchPlaceholder")}),!s&&T(P6,{className:"clover-viewer-media-navigation","data-rtl-paged":r,children:r?T(Ee,{children:[T(ql,{onClick:()=>i(1),disabled:a,type:"button",children:T(LA,{title:d("commonNext")})}),T("span",{children:[t+1," ",T("em",{children:"/"})," ",n]}),T(ql,{onClick:()=>i(-1),disabled:c,type:"button",children:T(kA,{title:d("commonPrevious")})})]}):T(Ee,{children:[T(ql,{onClick:()=>i(-1),disabled:c,type:"button",children:T(LA,{title:d("commonPrevious")})}),T("span",{children:[t+1," ",T("em",{children:"/"})," ",n]}),T(ql,{onClick:()=>i(1),disabled:a,type:"button",children:T(kA,{title:d("commonNext")})})]})}),T(ql,{onClick:h,type:"button",className:"clover-viewer-media-search",children:s?T(D6,{title:d("commonClose")}):T(O6,{title:d("commonSearch")})})]})})},F6=({children:i,rootMargin:e="100px",attributes:t={},isVisibleCallback:n=()=>{}})=>{const r=ge(null),[s,o]=se(!1);return ne(()=>{const a=r.current;if(!a)return;const l=new IntersectionObserver(([c])=>{c.isIntersecting&&(n(!0),o(!0),l.disconnect())},{rootMargin:e});return l.observe(a),()=>l.disconnect()},[r]),T("div",{ref:r,...t,children:s?i:null})},N6=({type:i})=>{switch(i){case"Sound":return T(ri.Audio,{});case"Image":return T(ri.Image,{});case"Video":return T(ri.Video,{});default:return T(ri.Image,{})}},B6=({canvas:i,canvasIndex:e,isActive:t,type:n,handleChange:r})=>{const[s,o]=se(!1),[a,l]=se(),c=gt(),{vault:u}=c,d=200,h=i!=null&&i.label?Di(i==null?void 0:i.label):String(e+1);ne(()=>{s&&(async()=>{var p,g;try{if(((p=i==null?void 0:i.thumbnail)==null?void 0:p.length)!==0)l((g=i==null?void 0:i.thumbnail[0])==null?void 0:g.id);else{const{best:m}=await Zk(i,{vault:u,dereference:!0,width:d,height:d});l(m==null?void 0:m.id)}}catch(m){console.error("Error fetching thumbnail",m)}})()},[i,s]);const f=p=>{o(p)};return T(Qm,{"aria-checked":t,"data-testid":"media-thumbnail","data-canvas":e,onClick:()=>r(i.id),value:i.id,children:T("figure",{children:[T(Ad,{children:[T(F6,{isVisibleCallback:f,attributes:{className:"media-thumbnail-lazyload","data-lazyload":String(s),"data-testid":"media-thumbnail-lazyload"},children:a&&T("img",{alt:h,"data-testid":"media-thumbnail-image",src:a})}),T(_d,{}),T(IA,{children:T(bd,{isIcon:!0,"data-testid":"thumbnail-tag",children:[T(_6,{}),T(ri,{"aria-label":n,children:T(N6,{type:n})}),["Video","Sound"].includes(n)&&T(A6,{children:Fx(i.duration)})]})})]}),T("figcaption",{"data-testid":"fig-caption",children:i.label?T(yr,{label:i.label}):(e+1).toString()})]})})},U6=i=>i.body?i.body.type:"Image",$6=({items:i})=>{const{t:e}=dn(),t=Ti(),n=gt(),{activeCanvas:r,isPaged:s,vault:o,sequence:a,viewingDirection:l}=n,c=s&&l==="right-to-left",[u,d]=se(""),[h,f]=se([]),[p,g]=se(0),m=et.useRef(null),v="painting",y=E=>{r!==E&&t({type:"updateActiveCanvas",canvasId:E})};return ne(()=>{if(!h.length){const E=["Image","Sound","Video"],C=i.map(b=>Ub(o,b,v,E)).filter(b=>b.annotations.length>0);f(C)}},[i,h.length,o]),ne(()=>{h.forEach((E,C)=>{E!=null&&E.canvas&&E.canvas.id===r&&g(C)})},[r,h]),ne(()=>{const E=document.querySelector(`[data-canvas="${p}"]`);if(E instanceof HTMLElement&&m.current){const C=E.offsetLeft-m.current.offsetWidth/2+E.offsetWidth/2;m.current.scrollTo({left:C,behavior:"smooth"})}},[p]),T(Ee,{children:[T(M6,{handleFilter:E=>d(E),handleCanvasToggle:E=>{const C=a[1].findIndex(P=>P.includes(p)),b=C+E>=0?C+E:a[1].length-1;if(!a[1][b])return;const I=a[1][b][0],D=a[0][I].id;D&&y(D)},activeIndex:p,canvasLength:i.length,isRtlPaged:c}),T(R6,{"aria-label":e("media.selectItem"),"data-testid":"media","data-active-canvas":i[p].id,"data-canvas-length":i.length,"data-filter":u,"data-rtl-paged":c,ref:m,style:{direction:c?"rtl":"ltr"},children:a[1].filter(E=>E.some(C=>{var P;const b=a[0][C].id,I=h.find(k=>{var N;return((N=k==null?void 0:k.canvas)==null?void 0:N.id)===b});if(!I)return!1;const D=Di((P=I==null?void 0:I.canvas)==null?void 0:P.label)||"";return!(u&&!D.toLowerCase().includes(u.toLowerCase()))})).map((E,C)=>{const b=E.map(I=>a[0][I].id).includes(r);return T(C6,{"data-active":b,children:E.map(I=>{var k,N;const D=a[0][I].id,P=h.find(B=>{var K;return((K=B==null?void 0:B.canvas)==null?void 0:K.id)===D});return P?T(B6,{canvas:P.canvas,canvasIndex:h.findIndex(B=>B===P),handleChange:y,isActive:r===((k=P==null?void 0:P.canvas)==null?void 0:k.id),type:U6(P.annotations[0])},(N=P==null?void 0:P.canvas)==null?void 0:N.id):null})},C)})})]})},DA=oe("button",{position:"absolute",background:"none",border:"none",cursor:"zoom-in",margin:"0",padding:"0",width:"100%",height:"100%",transition:"$all",opacity:1,display:"flex",alignItems:"center",justifyContent:"center",img:{width:"100%",height:"100%",objectFit:"contain",color:"transparent",aspectRatio:"auto"},"&[data-paged=true]":{"img:first-child ":{objectPosition:"100% 50%"},"img:last-child":{objectPosition:"0 50%"}},"&[data-active=false]":{opacity:0,objectPosition:"50% 50%"},variants:{isMedia:{true:{cursor:"pointer"}}}}),OA=oe(jx,{position:"absolute",width:"2rem",top:"1rem",right:"1rem",zIndex:100,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",transition:"$all",borderRadius:"50%",backgroundColor:"$accent",cursor:"pointer","&:hover, &:focus":{backgroundColor:"$accent !important"},variants:{isInteractive:{true:{"&:hover":{opacity:"1"}},false:{}},isMedia:{true:{cursor:"pointer !important"}}},compoundVariants:[{isInteractive:!1,isMedia:!0,css:{top:"50%",right:"50%",width:"4rem",height:"4rem",transform:"translate(50%,-50%)"}}]}),H6=oe("div",{position:"relative",display:"flex",flexDirection:"column",flexGrow:"1",flexShrink:"1",zIndex:"0",overflow:"hidden","&:hover":{[`${OA}`]:{backgroundColor:"$accent"},[`${DA}`]:{backgroundColor:"#6662"}}}),z6=oe("div",{width:"100%",flexGrow:"1",minHeight:"0"});oe("img",{width:"100%",height:"100%",objectFit:"contain",display:"block"});function MA(i,[e,t]){return Math.min(t,Math.max(e,i))}var FA=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),V6="VisuallyHidden",G6=me((i,e)=>T(je.span,{...i,ref:e,style:{...FA,...i.style}}));G6.displayName=V6;var W6=[" ","Enter","ArrowUp","ArrowDown"],j6=[" ","Enter"],Js="Select",[Rd,Cd,K6]=zb(Js),[ua]=Ln(Js,[K6,gd]),Id=gd(),[q6,ls]=ua(Js),[Y6,X6]=ua(Js),NA=i=>{const{__scopeSelect:e,children:t,open:n,defaultOpen:r,onOpenChange:s,value:o,defaultValue:a,onValueChange:l,dir:c,name:u,autoComplete:d,disabled:h,required:f,form:p}=i,g=Id(e),[m,v]=se(null),[y,S]=se(null),[x,E]=se(!1),C=ju(c),[b,I]=Fr({prop:n,defaultProp:r??!1,onChange:s,caller:Js}),[D,P]=Fr({prop:o,defaultProp:a,onChange:l,caller:Js}),k=ge(null),N=m?p||!!m.closest("form"):!0,[B,K]=se(new Set),q=Array.from(B).map(H=>H.props.value).join(";");return T(J_,{...g,children:T(q6,{required:f,scope:e,trigger:m,onTriggerChange:v,valueNode:y,onValueNodeChange:S,valueNodeHasChildren:x,onValueNodeHasChildrenChange:E,contentId:qs(),value:D,onValueChange:P,open:b,onOpenChange:I,dir:C,triggerPointerDownPosRef:k,disabled:h,children:[T(Rd.Provider,{scope:e,children:T(Y6,{scope:i.__scopeSelect,onNativeOptionAdd:Ce(H=>{K(X=>new Set(X).add(H))},[]),onNativeOptionRemove:Ce(H=>{K(X=>{const F=new Set(X);return F.delete(H),F})},[]),children:t})}),N?T(aR,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:d,value:D,onChange:H=>P(H.target.value),disabled:h,form:p,children:[D===void 0?T("option",{value:""}):null,Array.from(B)]},q):null]})})};NA.displayName=Js;var BA="SelectTrigger",UA=me((i,e)=>{const{__scopeSelect:t,disabled:n=!1,...r}=i,s=Id(t),o=ls(BA,t),a=o.disabled||n,l=ut(e,o.onTriggerChange),c=Cd(t),u=ge("touch"),[d,h,f]=cR(g=>{const m=c().filter(S=>!S.disabled),v=m.find(S=>S.value===o.value),y=uR(m,g,v);y!==void 0&&o.onValueChange(y.value)}),p=g=>{a||(o.onOpenChange(!0),f()),g&&(o.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return T(Wm,{asChild:!0,...s,children:T(je.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":lR(o.value)?"":void 0,...r,ref:l,onClick:Ge(r.onClick,g=>{g.currentTarget.focus(),u.current!=="mouse"&&p(g)}),onPointerDown:Ge(r.onPointerDown,g=>{u.current=g.pointerType;const m=g.target;m.hasPointerCapture(g.pointerId)&&m.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(p(g),g.preventDefault())}),onKeyDown:Ge(r.onKeyDown,g=>{const m=d.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(m&&g.key===" ")&&W6.includes(g.key)&&(p(),g.preventDefault())})})})});UA.displayName=BA;var $A="SelectValue",HA=me((i,e)=>{const{__scopeSelect:t,className:n,style:r,children:s,placeholder:o="",...a}=i,l=ls($A,t),{onValueNodeHasChildrenChange:c}=l,u=s!==void 0,d=ut(e,l.onValueNodeChange);return Yt(()=>{c(u)},[c,u]),T(je.span,{...a,ref:d,style:{pointerEvents:"none"},children:lR(l.value)?T(Ee,{children:o}):s})});HA.displayName=$A;var Z6="SelectIcon",zA=me((i,e)=>{const{__scopeSelect:t,children:n,...r}=i;return T(je.span,{"aria-hidden":!0,...r,ref:e,children:n||"▼"})});zA.displayName=Z6;var Q6="SelectPortal",VA=i=>T(iA,{asChild:!0,...i});VA.displayName=Q6;var eo="SelectContent",GA=me((i,e)=>{const t=ls(eo,i.__scopeSelect),[n,r]=se();if(Yt(()=>{r(new DocumentFragment)},[]),!t.open){const s=n;return s?Dl.createPortal(T(WA,{scope:i.__scopeSelect,children:T(Rd.Slot,{scope:i.__scopeSelect,children:T("div",{children:i.children})})}),s):null}return T(jA,{...i,ref:e})});GA.displayName=eo;var wn=10,[WA,cs]=ua(eo),J6="SelectContentImpl",e8=Ol("SelectContent.RemoveScroll"),jA=me((i,e)=>{const{__scopeSelect:t,position:n="item-aligned",onCloseAutoFocus:r,onEscapeKeyDown:s,onPointerDownOutside:o,side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:h,collisionPadding:f,sticky:p,hideWhenDetached:g,avoidCollisions:m,...v}=i,y=ls(eo,t),[S,x]=se(null),[E,C]=se(null),b=ut(e,de=>x(de)),[I,D]=se(null),[P,k]=se(null),N=Cd(t),[B,K]=se(!1),q=ge(!1);ne(()=>{if(S)return rA(S)},[S]),p_();const H=Ce(de=>{const[Pe,...qe]=N().map(Ue=>Ue.ref.current),[Le]=qe.slice(-1),Fe=document.activeElement;for(const Ue of de)if(Ue===Fe||(Ue==null||Ue.scrollIntoView({block:"nearest"}),Ue===Pe&&E&&(E.scrollTop=0),Ue===Le&&E&&(E.scrollTop=E.scrollHeight),Ue==null||Ue.focus(),document.activeElement!==Fe))return},[N,E]),X=Ce(()=>H([I,S]),[H,I,S]);ne(()=>{B&&X()},[B,X]);const{onOpenChange:F,triggerPointerDownPosRef:U}=y;ne(()=>{if(S){let de={x:0,y:0};const Pe=Le=>{var Fe,Ue;de={x:Math.abs(Math.round(Le.pageX)-(((Fe=U.current)==null?void 0:Fe.x)??0)),y:Math.abs(Math.round(Le.pageY)-(((Ue=U.current)==null?void 0:Ue.y)??0))}},qe=Le=>{de.x<=10&&de.y<=10?Le.preventDefault():S.contains(Le.target)||F(!1),document.removeEventListener("pointermove",Pe),U.current=null};return U.current!==null&&(document.addEventListener("pointermove",Pe),document.addEventListener("pointerup",qe,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Pe),document.removeEventListener("pointerup",qe,{capture:!0})}}},[S,F,U]),ne(()=>{const de=()=>F(!1);return window.addEventListener("blur",de),window.addEventListener("resize",de),()=>{window.removeEventListener("blur",de),window.removeEventListener("resize",de)}},[F]);const[j,V]=cR(de=>{const Pe=N().filter(Fe=>!Fe.disabled),qe=Pe.find(Fe=>Fe.ref.current===document.activeElement),Le=uR(Pe,de,qe);Le&&setTimeout(()=>Le.ref.current.focus())}),Z=Ce((de,Pe,qe)=>{const Le=!q.current&&!qe;(y.value!==void 0&&y.value===Pe||Le)&&(D(de),Le&&(q.current=!0))},[y.value]),Q=Ce(()=>S==null?void 0:S.focus(),[S]),le=Ce((de,Pe,qe)=>{const Le=!q.current&&!qe;(y.value!==void 0&&y.value===Pe||Le)&&k(de)},[y.value]),re=n==="popper"?Jm:KA,ye=re===Jm?{side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:h,collisionPadding:f,sticky:p,hideWhenDetached:g,avoidCollisions:m}:{};return T(WA,{scope:t,content:S,viewport:E,onViewportChange:C,itemRefCallback:Z,selectedItem:I,onItemLeave:Q,itemTextRefCallback:le,focusSelectedItem:X,selectedItemText:P,position:n,isPositioned:B,searchRef:j,children:T(Zm,{as:e8,allowPinchZoom:!0,children:T(Lm,{asChild:!0,trapped:y.open,onMountAutoFocus:de=>{de.preventDefault()},onUnmountAutoFocus:Ge(r,de=>{var Pe;(Pe=y.trigger)==null||Pe.focus({preventScroll:!0}),de.preventDefault()}),children:T(Rm,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:de=>de.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:T(re,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:de=>de.preventDefault(),...v,...ye,onPlaced:()=>K(!0),ref:b,style:{display:"flex",flexDirection:"column",outline:"none",...v.style},onKeyDown:Ge(v.onKeyDown,de=>{const Pe=de.ctrlKey||de.altKey||de.metaKey;if(de.key==="Tab"&&de.preventDefault(),!Pe&&de.key.length===1&&V(de.key),["ArrowUp","ArrowDown","Home","End"].includes(de.key)){let Le=N().filter(Fe=>!Fe.disabled).map(Fe=>Fe.ref.current);if(["ArrowUp","End"].includes(de.key)&&(Le=Le.slice().reverse()),["ArrowUp","ArrowDown"].includes(de.key)){const Fe=de.target,Ue=Le.indexOf(Fe);Le=Le.slice(Ue+1)}setTimeout(()=>H(Le)),de.preventDefault()}})})})})})})});jA.displayName=J6;var t8="SelectItemAlignedPosition",KA=me((i,e)=>{const{__scopeSelect:t,onPlaced:n,...r}=i,s=ls(eo,t),o=cs(eo,t),[a,l]=se(null),[c,u]=se(null),d=ut(e,b=>u(b)),h=Cd(t),f=ge(!1),p=ge(!0),{viewport:g,selectedItem:m,selectedItemText:v,focusSelectedItem:y}=o,S=Ce(()=>{if(s.trigger&&s.valueNode&&a&&c&&g&&m&&v){const b=s.trigger.getBoundingClientRect(),I=c.getBoundingClientRect(),D=s.valueNode.getBoundingClientRect(),P=v.getBoundingClientRect();if(s.dir!=="rtl"){const Fe=P.left-I.left,Ue=D.left-Fe,Xe=b.left-Ue,it=b.width+Xe,zt=Math.max(it,I.width),De=window.innerWidth-wn,w=MA(Ue,[wn,Math.max(wn,De-zt)]);a.style.minWidth=it+"px",a.style.left=w+"px"}else{const Fe=I.right-P.right,Ue=window.innerWidth-D.right-Fe,Xe=window.innerWidth-b.right-Ue,it=b.width+Xe,zt=Math.max(it,I.width),De=window.innerWidth-wn,w=MA(Ue,[wn,Math.max(wn,De-zt)]);a.style.minWidth=it+"px",a.style.right=w+"px"}const k=h(),N=window.innerHeight-wn*2,B=g.scrollHeight,K=window.getComputedStyle(c),q=parseInt(K.borderTopWidth,10),H=parseInt(K.paddingTop,10),X=parseInt(K.borderBottomWidth,10),F=parseInt(K.paddingBottom,10),U=q+H+B+F+X,j=Math.min(m.offsetHeight*5,U),V=window.getComputedStyle(g),Z=parseInt(V.paddingTop,10),Q=parseInt(V.paddingBottom,10),le=b.top+b.height/2-wn,re=N-le,ye=m.offsetHeight/2,de=m.offsetTop+ye,Pe=q+H+de,qe=U-Pe;if(Pe<=le){const Fe=k.length>0&&m===k[k.length-1].ref.current;a.style.bottom="0px";const Ue=c.clientHeight-g.offsetTop-g.offsetHeight,Xe=Math.max(re,ye+(Fe?Q:0)+Ue+X),it=Pe+Xe;a.style.height=it+"px"}else{const Fe=k.length>0&&m===k[0].ref.current;a.style.top="0px";const Xe=Math.max(le,q+g.offsetTop+(Fe?Z:0)+ye)+qe;a.style.height=Xe+"px",g.scrollTop=Pe-le+g.offsetTop}a.style.margin=`${wn}px 0`,a.style.minHeight=j+"px",a.style.maxHeight=N+"px",n==null||n(),requestAnimationFrame(()=>f.current=!0)}},[h,s.trigger,s.valueNode,a,c,g,m,v,s.dir,n]);Yt(()=>S(),[S]);const[x,E]=se();Yt(()=>{c&&E(window.getComputedStyle(c).zIndex)},[c]);const C=Ce(b=>{b&&p.current===!0&&(S(),y==null||y(),p.current=!1)},[S,y]);return T(n8,{scope:t,contentWrapper:a,shouldExpandOnScrollRef:f,onScrollButtonChange:C,children:T("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:x},children:T(je.div,{...r,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...r.style}})})})});KA.displayName=t8;var i8="SelectPopperPosition",Jm=me((i,e)=>{const{__scopeSelect:t,align:n="start",collisionPadding:r=wn,...s}=i,o=Id(t);return T(eA,{...o,...s,ref:e,align:n,collisionPadding:r,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Jm.displayName=i8;var[n8,ev]=ua(eo,{}),tv="SelectViewport",qA=me((i,e)=>{const{__scopeSelect:t,nonce:n,...r}=i,s=cs(tv,t),o=ev(tv,t),a=ut(e,s.onViewportChange),l=ge(0);return T(Ee,{children:[T("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:n}),T(Rd.Slot,{scope:t,children:T(je.div,{"data-radix-select-viewport":"",role:"presentation",...r,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...r.style},onScroll:Ge(r.onScroll,c=>{const u=c.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:h}=o;if(h!=null&&h.current&&d){const f=Math.abs(l.current-u.scrollTop);if(f>0){const p=window.innerHeight-wn*2,g=parseFloat(d.style.minHeight),m=parseFloat(d.style.height),v=Math.max(g,m);if(v<p){const y=v+f,S=Math.min(p,y),x=y-S;d.style.height=S+"px",d.style.bottom==="0px"&&(u.scrollTop=x>0?x:0,d.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});qA.displayName=tv;var YA="SelectGroup",[r8,s8]=ua(YA),XA=me((i,e)=>{const{__scopeSelect:t,...n}=i,r=qs();return T(r8,{scope:t,id:r,children:T(je.div,{role:"group","aria-labelledby":r,...n,ref:e})})});XA.displayName=YA;var ZA="SelectLabel",QA=me((i,e)=>{const{__scopeSelect:t,...n}=i,r=s8(ZA,t);return T(je.div,{id:r.id,...n,ref:e})});QA.displayName=ZA;var Pd="SelectItem",[o8,JA]=ua(Pd),eR=me((i,e)=>{const{__scopeSelect:t,value:n,disabled:r=!1,textValue:s,...o}=i,a=ls(Pd,t),l=cs(Pd,t),c=a.value===n,[u,d]=se(s??""),[h,f]=se(!1),p=ut(e,y=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,y,n,r)}),g=qs(),m=ge("touch"),v=()=>{r||(a.onValueChange(n),a.onOpenChange(!1))};if(n==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return T(o8,{scope:t,value:n,disabled:r,textId:g,isSelected:c,onItemTextChange:Ce(y=>{d(S=>S||((y==null?void 0:y.textContent)??"").trim())},[]),children:T(Rd.ItemSlot,{scope:t,value:n,disabled:r,textValue:u,children:T(je.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":r||void 0,"data-disabled":r?"":void 0,tabIndex:r?void 0:-1,...o,ref:p,onFocus:Ge(o.onFocus,()=>f(!0)),onBlur:Ge(o.onBlur,()=>f(!1)),onClick:Ge(o.onClick,()=>{m.current!=="mouse"&&v()}),onPointerUp:Ge(o.onPointerUp,()=>{m.current==="mouse"&&v()}),onPointerDown:Ge(o.onPointerDown,y=>{m.current=y.pointerType}),onPointerMove:Ge(o.onPointerMove,y=>{var S;m.current=y.pointerType,r?(S=l.onItemLeave)==null||S.call(l):m.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ge(o.onPointerLeave,y=>{var S;y.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:Ge(o.onKeyDown,y=>{var x;((x=l.searchRef)==null?void 0:x.current)!==""&&y.key===" "||(j6.includes(y.key)&&v(),y.key===" "&&y.preventDefault())})})})})});eR.displayName=Pd;var Yl="SelectItemText",tR=me((i,e)=>{const{__scopeSelect:t,className:n,style:r,...s}=i,o=ls(Yl,t),a=cs(Yl,t),l=JA(Yl,t),c=X6(Yl,t),[u,d]=se(null),h=ut(e,v=>d(v),l.onItemTextChange,v=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,v,l.value,l.disabled)}),f=u==null?void 0:u.textContent,p=Ct(()=>T("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:g,onNativeOptionRemove:m}=c;return Yt(()=>(g(p),()=>m(p)),[g,m,p]),T(Ee,{children:[T(je.span,{id:l.textId,...s,ref:h}),l.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Dl.createPortal(s.children,o.valueNode):null]})});tR.displayName=Yl;var iR="SelectItemIndicator",nR=me((i,e)=>{const{__scopeSelect:t,...n}=i;return JA(iR,t).isSelected?T(je.span,{"aria-hidden":!0,...n,ref:e}):null});nR.displayName=iR;var iv="SelectScrollUpButton",rR=me((i,e)=>{const t=cs(iv,i.__scopeSelect),n=ev(iv,i.__scopeSelect),[r,s]=se(!1),o=ut(e,n.onScrollButtonChange);return Yt(()=>{if(t.viewport&&t.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=t.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[t.viewport,t.isPositioned]),r?T(oR,{...i,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=t;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});rR.displayName=iv;var nv="SelectScrollDownButton",sR=me((i,e)=>{const t=cs(nv,i.__scopeSelect),n=ev(nv,i.__scopeSelect),[r,s]=se(!1),o=ut(e,n.onScrollButtonChange);return Yt(()=>{if(t.viewport&&t.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,u=Math.ceil(l.scrollTop)<c;s(u)};const l=t.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[t.viewport,t.isPositioned]),r?T(oR,{...i,ref:o,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=t;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});sR.displayName=nv;var oR=me((i,e)=>{const{__scopeSelect:t,onAutoScroll:n,...r}=i,s=cs("SelectScrollButton",t),o=ge(null),a=Cd(t),l=Ce(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return ne(()=>()=>l(),[l]),Yt(()=>{var u;const c=a().find(d=>d.ref.current===document.activeElement);(u=c==null?void 0:c.ref.current)==null||u.scrollIntoView({block:"nearest"})},[a]),T(je.div,{"aria-hidden":!0,...r,ref:e,style:{flexShrink:0,...r.style},onPointerDown:Ge(r.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(n,50))}),onPointerMove:Ge(r.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),o.current===null&&(o.current=window.setInterval(n,50))}),onPointerLeave:Ge(r.onPointerLeave,()=>{l()})})}),a8="SelectSeparator",l8=me((i,e)=>{const{__scopeSelect:t,...n}=i;return T(je.div,{"aria-hidden":!0,...n,ref:e})});l8.displayName=a8;var rv="SelectArrow",c8=me((i,e)=>{const{__scopeSelect:t,...n}=i,r=Id(t),s=ls(rv,t),o=cs(rv,t);return s.open&&o.position==="popper"?T(tA,{...r,...n,ref:e}):null});c8.displayName=rv;var u8="SelectBubbleInput",aR=me(({__scopeSelect:i,value:e,...t},n)=>{const r=ge(null),s=ut(n,r),o=vm(e);return ne(()=>{const a=r.current;if(!a)return;const l=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(o!==e&&u){const d=new Event("change",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[o,e]),T(je.select,{...t,style:{...FA,...t.style},ref:s,defaultValue:e})});aR.displayName=u8;function lR(i){return i===""||i===void 0}function cR(i){const e=rs(i),t=ge(""),n=ge(0),r=Ce(o=>{const a=t.current+o;e(a),function l(c){t.current=c,window.clearTimeout(n.current),c!==""&&(n.current=window.setTimeout(()=>l(""),1e3))}(a)},[e]),s=Ce(()=>{t.current="",window.clearTimeout(n.current)},[]);return ne(()=>()=>window.clearTimeout(n.current),[]),[t,r,s]}function uR(i,e,t){const r=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,s=t?i.indexOf(t):-1;let o=d8(i,Math.max(s,0));r.length===1&&(o=o.filter(c=>c!==t));const l=o.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return l!==t?l:void 0}function d8(i,e){return i.map((t,n)=>i[(e+n)%i.length])}var h8=NA,f8=UA,p8=GA,g8=QA,m8=eR;const v8=oe("svg",{height:"19px",color:"$accent",fill:"$accent",stroke:"$accent",display:"flex",margin:"0.25rem 0.85rem"}),y8=oe(f8,{fontSize:"1.25rem",fontWeight:"400",fontFamily:"inherit",alignSelf:"flex-start",flexGrow:"1",cursor:"pointer",transition:"$all",border:"1px solid #6663",boxShadow:"2px 2px 5px #0001",borderRadius:"3px",display:"flex",alignItems:"center",paddingLeft:"0.5rem",width:"100%","@sm":{fontSize:"1rem"}}),S8=oe(p8,{borderRadius:"3px",boxShadow:"3px 3px 8px #0003",backgroundColor:"$secondary",marginTop:"2.25rem",marginLeft:"6px",paddingBottom:"0.25rem",maxHeight:"calc(61.8vh - 2.5rem) !important",borderTopLeftRadius:"0",border:"1px solid $secondaryMuted",maxWidth:"90vw"}),x8=oe(m8,{display:"flex",alignItems:"center",fontFamily:"inherit",padding:"0.25rem 0.5rem",color:"$primary",fontWeight:"400",fontSize:"0.8333rem",cursor:"pointer",backgroundColor:"$secondary",width:"calc(100% - 1rem)","> span":{whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden"},'&[data-state="checked"]':{fontWeight:"700",color:"$primary !important"},"&:hover":{color:"$accent"},img:{width:"31px",height:"31px",marginRight:"0.5rem",borderRadius:"3px"}}),T8=oe(g8,{color:"$primaryMuted",fontFamily:"inherit",fontSize:"0.85rem",padding:"0.5rem 1rem 0.5rem 0.5rem",display:"flex",alignItems:"center",marginBottom:"0.25rem",borderRadius:"3px",borderTopLeftRadius:"0",borderBottomLeftRadius:"0",borderBottomRightRadius:"0",backgroundColor:"$secondaryMuted"}),dR=oe(h8,{position:"relative",zIndex:"5",width:"100%"}),sv=({direction:i,title:e})=>T(v8,{xmlns:"http://www.w3.org/2000/svg",focusable:"false",viewBox:"0 0 512 512",role:"img",children:[T("title",{children:e}),i==="up"&&T(()=>T("path",{d:"M414 321.94L274.22 158.82a24 24 0 00-36.44 0L98 321.94c-13.34 15.57-2.28 39.62 18.22 39.62h279.6c20.5 0 31.56-24.05 18.18-39.62z"}),{}),i==="down"&&T(()=>T("path",{d:"M98 190.06l139.78 163.12a24 24 0 0036.44 0L414 190.06c13.34-15.57 2.28-39.62-18.22-39.62h-279.6c-20.5 0-31.56 24.05-18.18 39.62z"}),{})]}),ov=({children:i,label:e,maxHeight:t,onValueChange:n,value:r})=>T(dR,{onValueChange:n,value:r,children:[T(y8,{"data-testid":"select-button",children:[T(HA,{"data-testid":"select-button-value"}),T(zA,{children:T(sv,{direction:"down",title:"select"})})]}),T(VA,{children:T(S8,{css:{maxHeight:`${t} !important`},"data-testid":"select-content",children:[T(rR,{children:T(sv,{direction:"up",title:"scroll up for more"})}),T(qA,{children:T(XA,{children:[e&&T(T8,{children:T(yr,{"data-testid":"select-label",label:e})}),i]})}),T(sR,{children:T(sv,{direction:"down",title:"scroll down for more"})})]})})]}),av=i=>T(x8,{...i,children:[i.thumbnail&&T(Q1,{thumbnail:i.thumbnail}),T(tR,{children:T(yr,{label:i.label})}),T(nR,{})]}),E8=oe("div",{display:"flex",flexDirection:"column",gap:"0.3rem"}),w8=oe("div",{display:"flex",flexDirection:"row",alignItems:"center",gap:"0.5rem","@sm":{flexDirection:"column",alignItems:"flex-start"}}),b8=oe("div",{display:"flex",flexShrink:"0",alignItems:"center",borderRadius:"2rem",marginLeft:"auto"}),Ld=oe("button",{display:"flex",background:"none",border:"none",width:"2rem",height:"2rem",padding:"0",margin:"0",borderRadius:"2rem",color:"$accent",cursor:"pointer",transition:"$all",flexShrink:"0",opacity:"1",svg:{height:"50%",width:"50%",padding:"25%",opacity:"1",fill:"$accent",stroke:"$accent",boxSizing:"content-box",display:"block",transition:"$all"},"&:disabled":{backgroundColor:"transparent",boxShadow:"none",svg:{opacity:"0.25",color:"$accent",stroke:"$accent"}},"&:not(:disabled):hover":{opacity:"1",svg:{opacity:"1",color:"$accent",stroke:"$accent"}},"&[data-active=true]":{opacity:"1",svg:{opacity:"1",color:"$accent",path:{strokeWidth:"56"}}}}),_8=oe("span",{display:"flex",fontSize:"0.7222rem",gap:"0.25rem",fontWeight:"bold",whiteSpace:"nowrap",letterSpacing:"0",marginRight:"0.5rem",em:{opacity:"0.25",fontStyle:"normal"}}),A8=oe("div",{display:"flex",flexDirection:"row",paddingTop:"0.25rem",gap:"0.25rem",overflowX:"auto",alignItems:"center",scrollbarWidth:"none","&::-webkit-scrollbar":{display:"none"}}),R8=oe("button",{display:"flex",flexShrink:"0",padding:"0",margin:"0",background:"none",cursor:"pointer",border:"none",outline:"2px solid transparent",outlineOffset:"-3px",borderRadius:"2px",opacity:"0.75",transition:"$all",img:{display:"block",height:"61.8px",borderRadius:"2px"},"&[data-active=true]":{outline:"3px solid $accent",opacity:"1"}}),C8=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M133 440a35.37 35.37 0 01-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0135.77.45l247.85 148.36a36 36 0 010 61.11L151.23 435a35.5 35.5 0 01-18.23 5z"})]}),I8=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M224 432h-80V80h80zm144 0h-80V80h80z"})]}),P8=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M112 64a16 16 0 0116 16v136.43L360.77 77.11a35.13 35.13 0 0135.77.45c12 6.8 19.46 20 19.46 34.33v288.22c0 14.37-7.46 27.53-19.46 34.33a35.13 35.13 0 01-35.77.45L128 295.57V432a16 16 0 01-32 0V80a16 16 0 0116-16z"})]}),L8=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{d:"M400 64a16 16 0 00-16 16v136.43L151.23 77.11a35.13 35.13 0 00-35.77.45C103.46 84.36 96 97.52 96 111.89v288.22c0 14.37 7.46 27.53 19.46 34.33a35.13 35.13 0 0035.77.45L384 295.57V432a16 16 0 0032 0V80a16 16 0 00-16-16z"})]}),k8=({title:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",children:[T("title",{children:i}),T("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32",d:"M320 120l48 48-48 48"}),T("path",{d:"M352 168H144a80.24 80.24 0 00-80 80v16M192 392l-48-48 48-48",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32"}),T("path",{d:"M160 344h208a80.24 80.24 0 0080-80v-16",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"32"})]});function hR(i){const e=Math.floor(i/60),t=Math.floor(i%60),n=Math.floor(i%1*10);return`${String(e).padStart(2,"0")}:${String(t).padStart(2,"0")}.${n}`}const D8=({duration:i,frameIndex:e,isPlaying:t,isRepeat:n,playbackRate:r,totalFrames:s,onPlay:o,onPause:a,onPrevFrame:l,onNextFrame:c,onToggleRepeat:u,onSetPlaybackRate:d})=>{const{t:h}=dn(),f=s>0?i/s:0,p=e*f;return T(b8,{className:"clover-viewer-animation-controls",children:[T(_8,{children:i>0?T(Ee,{children:[hR(p)," ",T("em",{children:"/"})," ",hR(i)]}):T(Ee,{children:[e+1," ",T("em",{children:"/"})," ",s]})}),T(Ld,{onClick:l,disabled:e===0,type:"button","aria-label":h("canvasAnimationPreviousFrame"),children:T(P8,{title:h("canvasAnimationPreviousFrame")})}),T(Ld,{onClick:t?a:o,type:"button","aria-label":h(t?"canvasAnimationPause":"canvasAnimationPlay"),children:t?T(I8,{title:h("canvasAnimationPause")}):T(C8,{title:h("canvasAnimationPlay")})}),T(Ld,{onClick:u,type:"button","aria-label":h("canvasAnimationRepeat"),"aria-pressed":n,"data-active":n,children:T(k8,{title:h("canvasAnimationRepeat")})}),T(Ld,{onClick:c,disabled:e===s-1,type:"button","aria-label":h("canvasAnimationNextFrame"),children:T(L8,{title:h("canvasAnimationNextFrame")})})]})},O8=({isActive:i,isMedia:e,items:t,setIsInteractive:n})=>{const{vault:r}=gt(),[s,o]=se([]),a=s.length>1;if(ne(()=>{o([]);const u=t.map(d=>{const h=ns(r,d.id);if(!h)return null;const{id:f,width:p,height:g}=h[0];return f?{src:f,width:p||640,height:g||640,alt:d.label?im(d.label):"placeholder image"}:null}).filter(d=>d!==null);u.length&&o(u)},[t,a]),!i||!s.length)return null;const l=s.map(u=>u.width/u.height*1),c=l.reduce((u,d)=>u+d,0);return T(DA,{onClick:()=>n(!0),isMedia:e,className:"clover-viewer-placeholder","data-active":i,"data-paged":a,children:s.map((u,d)=>{const h=l[d]/c*100;return Ve("img",{...u,key:d,alt:u.alt,style:{width:`${h}%`}})})})},M8=oe("canvas",{position:"absolute",width:"100%",height:"100%",zIndex:"0"}),F8=et.forwardRef((i,e)=>{const t=et.useRef(null),n=Ce(()=>{var f,p;if((f=e.current)!=null&&f.currentTime&&((p=e.current)==null?void 0:p.currentTime)>0)return;const s=e.current;if(!s)return;const o=new AudioContext,a=o.createMediaElementSource(s),l=o.createAnalyser(),c=t.current;if(!c)return;c.width=s.offsetWidth,c.height=s.offsetHeight;const u=c.getContext("2d");a.connect(l),l.connect(o.destination),l.fftSize=256;const d=l.frequencyBinCount,h=new Uint8Array(d);setInterval(function(){r(l,u,d,h,c.width,c.height)},20)},[e]);et.useEffect(()=>{!e||!e.current||(e.current.onplay=n)},[n,e]);function r(s,o,a,l,c,u){const d=c/a*2.6;let h,f=0;s.getByteFrequencyData(l),o.fillStyle="#000000",o.fillRect(0,0,c,u);for(let p=0;p<a;p++)h=l[p]*2,o.fillStyle="rgba(78, 42, 132, 1)",o.fillRect(f,u-h,d,h),f+=d+6}return T(M8,{ref:t,role:"presentation"})}),N8=oe("div",{position:"relative",backgroundColor:"$primaryAlt",display:"flex",flexGrow:"0",flexShrink:"1",height:"100%",zIndex:"1",video:{backgroundColor:"transparent",objectFit:"contain",width:"100%",height:"100%",position:"relative",zIndex:"1"}}),B8=({resource:i,ignoreCaptionLabels:e})=>{const t=im(i.label,"en");return Array.isArray(t)&&t.some(r=>e.includes(r))?null:T("track",{src:i.id,label:Array.isArray(t)?t[0]:t,srcLang:"en","data-testid":"player-track"},i.id)},U8=({allSources:i,annotationResources:e,onEnded:t,painting:n})=>{const[r,s]=et.useState(0),[o,a]=et.useState(),l=et.useRef(null),c=et.useRef(t);et.useEffect(()=>{c.current=t},[t]);const u=Ti(),d=gt(),{activeCanvas:h,configOptions:f,contentStateAnnotation:p,isMediaPlaying:g,vault:m}=d,v=(n==null?void 0:n.type)==="Sound";return ne(()=>{if(!n.id||!l.current)return;const y=l.current;if(u({type:"updateActivePlayer",player:y}),!j1(n.id,n.format)){y.src=n.id,y.load();return}if(y.canPlayType("application/vnd.apple.mpegurl")){y.src=n.id,y.load();return}let S=!1,x;return(async()=>{const{default:E}=await Promise.resolve().then(()=>jP);if(S||!l.current)return;if(!E.isSupported()){l.current.src=n.id,l.current.load();return}const C={xhrSetup:function(b){b.withCredentials=!!f.withCredentials}};x=new E(C),x.attachMedia(l.current),x.on(E.Events.MEDIA_ATTACHED,function(){x==null||x.loadSource(n.id)}),x.on(E.Events.ERROR,function(b,I){if(I.fatal)switch(I.type){case E.ErrorTypes.NETWORK_ERROR:console.error(`fatal ${b} network error encountered, try to recover`),x==null||x.startLoad();break;case E.ErrorTypes.MEDIA_ERROR:console.error(`fatal ${b} media error encountered, try to recover`),x==null||x.recoverMediaError();break;default:x==null||x.destroy();break}})})(),()=>{S=!0,x&&l.current&&(x.detachMedia(),x.destroy(),l.current.currentTime=0)}},[f.withCredentials,n.id,n.format,u]),ne(()=>{var C,b,I,D;const y=m.get(h),S=(C=y.accompanyingCanvas)!=null&&C.id?ns(m,(b=y.accompanyingCanvas)==null?void 0:b.id):null,x=(I=y.placeholderCanvas)!=null&&I.id?ns(m,(D=y.placeholderCanvas)==null?void 0:D.id):null;!!(S&&x)?a(r===0?x[0].id:S[0].id):(S&&a(S[0].id),x&&a(x[0].id))},[h,r,m]),ne(()=>{const y=l==null?void 0:l.current;if(!y)return;let S=null,x=!1;const E=()=>{x||(x=!0,S=setInterval(()=>{y&&!y.paused&&!y.ended&&(s(y.currentTime),u({type:"updateActiveSelector",selector:{type:"PointSelector",t:Math.round(y.currentTime)}}))},500)),y&&y.paused&&(s(y.currentTime),u({type:"updateActiveSelector",selector:{type:"PointSelector",t:Math.round(y.currentTime)}}))},C=()=>{var b;return(b=c.current)==null?void 0:b.call(c)};return y.addEventListener("timeupdate",E),y.addEventListener("ended",C),()=>{y==null||y.removeEventListener("timeupdate",E),y==null||y.removeEventListener("ended",C),S&&clearInterval(S)}},[n.id,h]),ne(()=>{const y=l.current;if(!y||!g)return;const S=()=>y.play().catch(()=>{});return y.addEventListener("canplay",S,{once:!0}),()=>y.removeEventListener("canplay",S)},[n.id]),ne(()=>{const y=l.current;if(!y)return;const S=()=>u({type:"updateIsMediaPlaying",isMediaPlaying:!0}),x=()=>{y.ended||u({type:"updateIsMediaPlaying",isMediaPlaying:!1})};return y.addEventListener("play",S),y.addEventListener("pause",x),()=>{y.removeEventListener("play",S),y.removeEventListener("pause",x)}},[n.id,u]),ne(()=>{var y,S;if(p){const x=l==null?void 0:l.current;if(!x)return;const E=(y=p==null?void 0:p.target)==null?void 0:y.selector,{type:C,t:b,value:I}=E||{};if((((S=p==null?void 0:p.target)==null?void 0:S.source)||(p==null?void 0:p.target)).id!==h)return;if(b&&C==="PointSelector"&&(s(b),x.currentTime=b),C==="FragmentSelector"&&I){const P=I.split("=")[1];if(!P)return;const k=P.split(",")[0];s(k),x.currentTime=k}}},[l,p]),T(N8,{css:{backgroundColor:f.canvasBackgroundColor,maxHeight:f.canvasHeight,position:"relative"},"data-testid":"player-wrapper",className:"clover-viewer-player-wrapper",children:[T("video",{id:"clover-iiif-video",ref:l,"data-src":n.id,controls:!0,height:n.height,width:n.width,crossOrigin:f.crossOrigin,poster:o,style:{maxHeight:f.canvasHeight,position:"relative",zIndex:"1"},children:[i.map(y=>T("source",{src:y.id,type:y.format},y.id)),(e==null?void 0:e.length)>0&&e.map(y=>{const S=[];return y.items.forEach(x=>{m.get(x.id).body.forEach(C=>{const b=m.get(C.id);S.push(b)})}),S.map(x=>T(B8,{resource:x,ignoreCaptionLabels:f.ignoreCaptionLabels||[]},x.id))}),"Sorry, your browser doesn't support embedded videos."]},n.id),v&&T(F8,{ref:l})]})},$8=({label:i})=>T("svg",{xmlns:"http://www.w3.org/2000/svg","aria-labelledby":"close-svg-title",focusable:"false",viewBox:"0 0 512 512",role:"img",children:[T("title",{id:"close-svg-title",children:i}),T("path",{d:"M289.94 256l95-95A24 24 0 00351 127l-95 95-95-95a24 24 0 00-34 34l95 95-95 95a24 24 0 1034 34l95-95 95 95a24 24 0 0034-34z"})]}),H8=({isMedia:i,label:e})=>T("svg",{xmlns:"http://www.w3.org/2000/svg","aria-labelledby":"open-svg-title",focusable:"false",viewBox:"0 0 512 512",role:"img",children:[T("title",{id:"open-svg-title",children:e}),i?T("path",{d:"M133 440a35.37 35.37 0 01-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0135.77.45l247.85 148.36a36 36 0 010 61l-247.89 148.4A35.5 35.5 0 01133 440z"}):T(Ee,{children:[T("path",{d:"m456.69,421.39l-94.09-94.09c22.65-30.16,34.88-66.86,34.84-104.58,0-96.34-78.38-174.72-174.72-174.72S48,126.38,48,222.72s78.38,174.72,174.72,174.72c37.72.04,74.42-12.19,104.58-34.84l94.09,94.09c10.29,9.2,26.1,8.32,35.3-1.98,8.48-9.49,8.48-23.83,0-33.32Zm-233.97-73.87c-68.89-.08-124.72-55.91-124.8-124.8h0c0-68.93,55.87-124.8,124.8-124.8s124.8,55.87,124.8,124.8-55.87,124.8-124.8,124.8Z"}),T("path",{d:"m279.5,197.76h-3.35s-28.47,0-28.47,0v-31.82c-.77-13.79-12.57-24.33-26.36-23.56-12.71.71-22.85,10.86-23.56,23.56v3.35h0v28.47h-31.82c-13.79.77-24.33,12.57-23.56,26.36.71,12.71,10.86,22.85,23.56,23.56h3.35s28.47,0,28.47,0v31.82c.77,13.79,12.57,24.33,26.36,23.56,12.71-.71,22.85-10.86,23.56-23.56v-3.35h0v-28.47h31.82c13.79-.77,24.33-12.57,23.56-26.36-.71-12.71-10.86-22.85-23.56-23.56Z"})]})]}),z8=({handleToggle:i,isInteractive:e,isMedia:t})=>{const{t:n}=dn();return T(OA,{onClick:i,isInteractive:e,isMedia:t,"data-testid":"placeholder-toggle",children:e?T($8,{label:n("commonClose")}):T(H8,{isMedia:t,label:n("commonOpen")})})},V8=(i,e)=>{var o,a;const t=i.get(e);if(!((o=t==null?void 0:t.items)!=null&&o.length))return[];const n=i.get(t.items[0]);if(!((a=n==null?void 0:n.items)!=null&&a.length))return[];const r=i.get(n.items),s=[];for(const l of r){if(!(l!=null&&l.target))continue;const c=Ny(l.target);if(!c.t)continue;const u=c.t.split(",").map(Number);if(u.length!==2||isNaN(u[0])||isNaN(u[1]))continue;const[d,h]=u,f=Array.isArray(l.body)?l.body[0]:l.body;if(!f)continue;const p=typeof f=="string"?f:f.id;if(!p)continue;const g=i.get(p);g&&s.push({body:g,label:l.label??null,startTime:d,endTime:h,duration:h-d})}return s.sort((l,c)=>l.startTime-c.startTime)},G8=(i,e,t)=>{const n=i.get(e);if(!n)return{isAutoAdvance:!1,isManifestAutoAdvance:!1,isRepeat:!1,duration:0};const r=n.behavior||[],s=Array.isArray(r)?r:[r];let o=[];if(t){const l=i.get(t);if(l){const c=l.behavior||[];o=Array.isArray(c)?c:[c]}}const a=s.length>0?s:o;return{isAutoAdvance:a.includes("auto-advance"),isManifestAutoAdvance:o.includes("auto-advance"),isRepeat:a.includes("repeat"),duration:n.duration||0}},W8=({activeCanvas:i,annotationResources:e,contentSearchResource:t,isMedia:n,painting:r})=>{var xe,he,$e,ze;const[s,o]=se(0),[a,l]=se(!1),[c,u]=se([]),[d,h]=se([]),[f,p]=se(0),[g,m]=se(1),[v,y]=se(!1),[S,x]=se(!1),{activeManifest:E,configOptions:C,customDisplays:b,contentStateAnnotation:I,informationPanelResource:D,isPaged:P,openSeadragonViewer:k,sequence:N,vault:B,viewerId:K,viewingDirection:q,visibleCanvases:H}=gt(),X=P&&q==="right-to-left",[F,U]=se([]),j=!!I&&i===((he=(xe=I==null?void 0:I.target)==null?void 0:xe.source)==null?void 0:he.id),V=Ti(),Z=B.get(i),{isAutoAdvance:Q,isManifestAutoAdvance:le,isRepeat:re}=G8(B,i,E);ne(()=>{x(re)},[i,re]);const ye=(Z==null?void 0:Z.duration)??0,de=(r==null?void 0:r.length)??0,Pe=Ct(()=>V8(B,i),[B,i]),Le=Pe.length>0,Fe=(r==null?void 0:r.length)>1&&!Le,Ue=Le&&ye>0&&de>0?ye/de/g*1e3:0;ne(()=>{Le&&Q&&y(!0)},[Le,Q]),ne(()=>{Le&&r.forEach(ce=>{if(!ce.id)return;const fe=new window.Image;fe.src=ce.id})},[Le,r]),ne(()=>{if(!Le||!v||Ue<=0)return;const ce=setTimeout(()=>{o(fe=>{const He=fe+1;if(He>=de){if(S)return 0;if(y(!1),le){const R=N[0],A=R.findIndex(L=>L.id===i);A>=0&&A<R.length-1&&V({type:"updateActiveCanvas",canvasId:R[A+1].id})}return fe}return He})},Ue);return()=>clearTimeout(ce)},[Le,v,s,Ue,de,S,le,N,i,V]);const Xe=d.length&&!a&&!n,it=`${K}-${Bx(i+JSON.stringify(H)+f)}`,zt=()=>{l(!a),p(ce=>ce+1)},De=ce=>{const fe=r.findIndex(He=>He.id===ce);o(fe)},w=ce=>{y(!1),o(parseInt(ce,10))},O=Ce(ce=>{ce&&ce.scrollIntoView({inline:"nearest",block:"nearest",behavior:"smooth"})},[s]),z=b.find(ce=>{var A;let fe=!1;const{canvasId:He,paintingFormat:R}=ce.target;if(Array.isArray(He)&&He.length>0&&(fe=He.includes(i)),Array.isArray(R)&&R.length>0){const L=((A=r[s])==null?void 0:A.format)||"";fe=!!(L&&R.includes(L))}return fe});ne(()=>{j&&Xe&&f===0&&zt()},[j,Xe]),ne(()=>{Xe&&(V({type:"updateOpenSeadragonViewer",openSeadragonViewer:void 0}),V({type:"updateActiveSelector",selector:void 0}))},[Xe]),ne(()=>{var fe,He,R;const ce=[];if(D==="manifest-annotations"&&(e==null||e.forEach((A,L)=>{var M;(M=A==null?void 0:A.items)==null||M.forEach(Y=>{const ee=B.get(Y.id);ee&&ce.push({annotation:{...ee,body:ee.body.map(be=>{const Ze=B.get(be.id);return Ze||be})},targetIndex:L})})}),I)){const A=((fe=I==null?void 0:I.target)==null?void 0:fe.source)||(I==null?void 0:I.target);ce.push({annotation:{...I,body:(He=I==null?void 0:I.body)==null?void 0:He.map(L=>{const M=B.get(L.id);return M||L})},targetIndex:H.findIndex(L=>L.id===A.id)})}D==="manifest-content-search"&&((R=t==null?void 0:t.items)==null||R.forEach(A=>{const L=B.get(A.id);if(L){const M=H.findIndex(Y=>Y.id===L.target.source.id);typeof M=="number"&&ce.push({annotation:{...L,body:L.body.map(Y=>{const ee=B.get(Y.id);return ee||Y})},targetIndex:M})}})),U(ce)},[e,t,I,D,H]),ne(()=>{if(n)return;const ce=X?[...H].reverse():H,fe=ce.map(R=>{const A=R.id,L=ns(B,A);return L?L[s]:void 0}).filter(Boolean),He=ce.map(R=>{var ee;const A=R.id,L=B.get(A),M=(ee=L==null?void 0:L.placeholderCanvas)==null?void 0:ee.id;return!!!M||!M?null:{id:M,label:L==null?void 0:L.label}}).filter(R=>R!==null);u(fe),h(He)},[s,i,X,H,n,Z]),ne(()=>{o(0)},[H]);const ie=ce=>{ce&&!Xe&&(k==null?void 0:k.id)!==`openseadragon-${it}`&&V({type:"updateOpenSeadragonViewer",openSeadragonViewer:ce})},te=($e=z==null?void 0:z.display)==null?void 0:$e.component;return T(H6,{className:"clover-viewer-painting",children:[T(z6,{style:{backgroundColor:C.canvasBackgroundColor,...C.canvasHeight!=="auto"&&{height:C.canvasHeight}},children:[!!d.length&&!n&&T(z8,{handleToggle:zt,isInteractive:a,isMedia:n}),!!(d!=null&&d.length)&&!n&&T(O8,{isActive:!!Xe,isMedia:n,items:d,setIsInteractive:l}),!Xe&&!z&&(n?T(U8,{allSources:r,painting:r[s],annotationResources:e,onEnded:le?()=>{const ce=N[0],fe=ce.findIndex(He=>He.id===i);fe>=0&&fe<ce.length-1&&V({type:"updateActiveCanvas",canvasId:ce[fe+1].id})}:void 0}):r&&T(bT,{_cloverViewerHasPlaceholder:!!(d!=null&&d.length),annotations:F,body:c,instanceId:it,openSeadragonCallback:ie,openSeadragonConfig:C.openSeadragon},it)),!Xe&&te&&T(te,{id:i,annotationBody:r[s],hooks:{useViewerDispatch:Ti,useViewerState:gt},...z==null?void 0:z.display.componentProps})]}),Le&&!Xe&&T(E8,{children:[T(A8,{children:Pe.map((ce,fe)=>T(R8,{ref:fe===s?O:void 0,"data-active":fe===s,type:"button","aria-label":`Frame ${fe+1}`,onClick:()=>{y(!1),o(fe)},children:T("img",{src:ce.body.id,alt:""})},fe))}),T(w8,{children:[T(ov,{value:String(s),onValueChange:w,maxHeight:"200px",children:Pe.map((ce,fe)=>T(av,{value:String(fe),label:ce.label??{none:[String(fe+1)]}},fe))}),T(D8,{duration:ye,frameIndex:s,isPlaying:v,isRepeat:S,playbackRate:g,totalFrames:de,onPlay:()=>y(!0),onPause:()=>y(!1),onPrevFrame:()=>{y(!1),o(ce=>Math.max(0,ce-1))},onNextFrame:()=>{y(!1),o(ce=>Math.min(de-1,ce+1))},onToggleRepeat:()=>x(ce=>!ce),onSetPlaybackRate:m})]})]}),Fe&&T(ov,{value:(ze=r[s])==null?void 0:ze.id,onValueChange:De,maxHeight:"200px",children:r==null?void 0:r.map(ce=>T(av,{value:ce==null?void 0:ce.id,label:ce==null?void 0:ce.label},ce==null?void 0:ce.id))})]})},j8=({activeCanvas:i,annotationResources:e,searchServiceUrl:t,setContentSearchResource:n,contentSearchResource:r,contentSearchCallback:s,initialSearchQuery:o,isAudioVideo:a,items:l,painting:c})=>{var E,C;const{contentStateAnnotation:u,isInformationOpen:d,configOptions:h,sequence:f,visibleCanvases:p}=gt(),{informationPanel:g}=h,m=p.map(b=>b.id),y=(e.length>0||m.includes((C=(E=u==null?void 0:u.target)==null?void 0:E.source)==null?void 0:C.id))&&(g==null?void 0:g.renderAnnotation)&&(g==null?void 0:g.renderToggle)===!1&&d,S=(g==null?void 0:g.renderAbout)&&d||y,x=g==null?void 0:g.renderToggle;return T($b,{className:"clover-viewer-content","data-testid":"clover-viewer-content",children:[T(Hb,{"data-aside-active":S,"data-aside-toggle":x,children:[T(W8,{activeCanvas:i,annotationResources:e,contentSearchResource:r,isMedia:a,painting:c}),f[1].length>1&&T(bB,{className:"clover-viewer-media-wrapper",children:T($6,{items:l,activeItem:0})})]}),S&&T(_B,{"data-aside-active":S,"data-aside-toggle":x,children:T(L$,{activeCanvas:i,annotationResources:e,searchServiceUrl:t,setContentSearchResource:n,contentSearchResource:r,contentSearchCallback:s,initialSearchQuery:o})})]})},K8=oe(Qs.Trigger,{width:"30px",padding:"5px"}),fR=oe(Qs.Content,{display:"flex",flexDirection:"column",fontSize:"0.8333rem",border:"none",boxShadow:"2px 2px 5px #0003",zIndex:"2",button:{display:"flex",textDecoration:"none",marginBottom:"0.5em",color:"$accentAlt",cursor:"pointer",background:"$secondary",border:"none","&:last-child":{marginBottom:"0"}}}),q8=oe("span",{fontSize:"1.33rem",alignSelf:"flex-start",flexGrow:"0",flexShrink:"1",padding:"1rem","@sm":{fontSize:"1rem"},"&.visually-hidden":{position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:"0"}}),Y8=oe("header",{display:"flex",backgroundColor:"transparent !important",justifyContent:"space-between",alignItems:"flex-start",width:"100%",[`> ${dR}`]:{flexGrow:"1",flexShrink:"0"},form:{flexGrow:"0",flexShrink:"1"}}),X8=oe("div",{display:"flex",alignItems:"flex-end",justifyContent:"flex-end",padding:"1rem",flexShrink:"0",flexGrow:"1"}),Z8=()=>{var l;const i=Ti(),e=gt(),{activeManifest:t,collection:n,configOptions:r,vault:s}=e,o=r==null?void 0:r.canvasHeight,a=c=>{i({type:"updateActiveCanvas",canvasId:void 0}),i({type:"updateActiveManifest",manifestId:c}),i({type:"updateViewerId",viewerId:To()})};return T("div",{style:{margin:"0.75rem"},children:T(ov,{label:n.label,maxHeight:o,value:t,onValueChange:a,children:(l=n==null?void 0:n.items)==null?void 0:l.map(c=>T(av,{value:c.id,thumbnail:c!=null&&c.thumbnail?s.get(c==null?void 0:c.thumbnail):void 0,label:c.label},c.id))})})},Q8=(i,e=2500)=>{const{t}=dn(),[n,r]=se(""),s=Ce(()=>{navigator.clipboard.writeText(i).then(()=>r(t("copySuccess")),()=>r(t("copyFailure")))},[t,i]);return ne(()=>{if(!n)return;const o=setTimeout(()=>r(""),e);return()=>clearTimeout(o)},[n,e]),[n,s]},J8=oe("span",{display:"flex",alignContent:"center",alignItems:"center",padding:"0.125rem 0.25rem 0",marginTop:"-0.125rem",marginLeft:"0.5rem",backgroundColor:"$accent",color:"$secondary",borderRadius:"3px",lineHeight:"1em"}),ez=({status:i})=>i?T(J8,{"data-copy-status":i,children:i}):null,pR=({textPrompt:i,textToCopy:e})=>{const[t,n]=Q8(e);return T("button",{onClick:n,children:[i," ",T(ez,{status:t})]})},tz=({title:i})=>{const e="#ed1d33",t="#2873ab";return T("svg",{viewBox:"0 0 493.35999 441.33334",id:"iiif-logo",version:"1.1",children:[T("title",{children:i}),T("g",{transform:"matrix(1.3333333,0,0,-1.3333333,0,441.33333)",children:T("g",{transform:"scale(0.1)",children:[T("path",{style:{fill:t},d:"M 65.2422,2178.75 775.242,1915 773.992,15 65.2422,276.25 v 1902.5"}),T("path",{style:{fill:t},d:"m 804.145,2640.09 c 81.441,-240.91 -26.473,-436.2 -241.04,-436.2 -214.558,0 -454.511,195.29 -535.9527,436.2 -81.4335,240.89 26.4805,436.18 241.0387,436.18 214.567,0 454.512,-195.29 535.954,-436.18"}),T("path",{style:{fill:e},d:"M 1678.58,2178.75 968.578,1915 969.828,15 1678.58,276.25 v 1902.5"}),T("path",{style:{fill:e},d:"m 935.082,2640.09 c -81.437,-240.91 26.477,-436.2 241.038,-436.2 214.56,0 454.51,195.29 535.96,436.2 81.43,240.89 -26.48,436.18 -241.04,436.18 -214.57,0 -454.52,-195.29 -535.958,-436.18"}),T("path",{style:{fill:t},d:"m 1860.24,2178.75 710,-263.75 -1.25,-1900 -708.75,261.25 v 1902.5"}),T("path",{style:{fill:t},d:"m 2603.74,2640.09 c 81.45,-240.91 -26.47,-436.2 -241.03,-436.2 -214.58,0 -454.52,195.29 -535.96,436.2 -81.44,240.89 26.48,436.18 241.03,436.18 214.57,0 454.51,-195.29 535.96,-436.18"}),T("path",{style:{fill:e},d:"m 3700.24,3310 v -652.5 c 0,0 -230,90 -257.5,-142.5 -2.5,-247.5 0,-336.25 0,-336.25 l 257.5,83.75 V 1690 l -258.61,-92.5 V 262.5 L 2735.24,0 v 2360 c 0,0 -15,850 965,950"})]})})]})};var kd="Switch",[iz]=Ln(kd),[nz,rz]=iz(kd),gR=me((i,e)=>{const{__scopeSwitch:t,name:n,checked:r,defaultChecked:s,required:o,disabled:a,value:l="on",onCheckedChange:c,form:u,...d}=i,[h,f]=se(null),p=ut(e,S=>f(S)),g=ge(!1),m=h?u||!!h.closest("form"):!0,[v,y]=Fr({prop:r,defaultProp:s??!1,onChange:c,caller:kd});return T(nz,{scope:t,checked:v,disabled:a,children:[T(je.button,{type:"button",role:"switch","aria-checked":v,"aria-required":o,"data-state":SR(v),"data-disabled":a?"":void 0,disabled:a,value:l,...d,ref:p,onClick:Ge(i.onClick,S=>{y(x=>!x),m&&(g.current=S.isPropagationStopped(),g.current||S.stopPropagation())})}),m&&T(yR,{control:h,bubbles:!g.current,name:n,value:l,checked:v,required:o,disabled:a,form:u,style:{transform:"translateX(-100%)"}})]})});gR.displayName=kd;var mR="SwitchThumb",vR=me((i,e)=>{const{__scopeSwitch:t,...n}=i,r=rz(mR,t);return T(je.span,{"data-state":SR(r.checked),"data-disabled":r.disabled?"":void 0,...n,ref:e})});vR.displayName=mR;var sz="SwitchBubbleInput",yR=me(({__scopeSwitch:i,control:e,checked:t,bubbles:n=!0,...r},s)=>{const o=ge(null),a=ut(o,s),l=vm(t),c=mm(e);return ne(()=>{const u=o.current;if(!u)return;const d=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(d,"checked").set;if(l!==t&&f){const p=new Event("click",{bubbles:n});f.call(u,t),u.dispatchEvent(p)}},[l,t,n]),T("input",{type:"checkbox","aria-hidden":!0,defaultChecked:t,...r,tabIndex:-1,ref:a,style:{...r.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});yR.displayName=sz;function SR(i){return i?"checked":"unchecked"}var oz=gR,az=vR;const lz=oe(oz,{all:"unset",height:"2rem",width:"3.236rem",backgroundColor:"#6663",borderRadius:"9999px",position:"relative",WebkitTapHighlightColor:"transparent",cursor:"pointer","&:focus":{boxShadow:"0 0 0 2px $secondaryAlt"},'&[data-state="checked"]':{backgroundColor:"$accent",boxShadow:"inset 2px 2px 5px #0003"}}),cz=oe(az,{display:"block",height:"calc(2rem - 12px)",width:"calc(2rem - 12px)",backgroundColor:"$secondary",borderRadius:"100%",boxShadow:"2px 2px 5px #0001",transition:"$all",transform:"translateX(6px)",willChange:"transform",span:{fontFamily:"monospace",fontSize:"0.8333rem",fontWeight:"700",display:"flex",height:"100%",width:"100%",alignItems:"center",justifyContent:"center",color:"$primary",opacity:"0.382",userSelect:"none",pointerEvents:"none"},'&[data-state="checked"]':{transform:"translateX(calc(1.236rem + 6px))",span:{opacity:"1",color:"$accent"}}});oe("label",{fontSize:"0.8333rem",fontWeight:"400",lineHeight:"1em",userSelect:"none",cursor:"pointer",paddingRight:"0.618rem"});const uz=oe("form",{display:"flex",flexShrink:"0",flexGrow:"1",alignItems:"center",marginLeft:"1.618rem"}),dz=()=>{const{isInformationOpen:i}=gt(),e=Ti(),{t}=dn();return T(uz,{children:T(lz,{checked:i,onCheckedChange:r=>{e({type:"updateInformationOpen",isInformationOpen:r})},id:"information-toggle","aria-label":t("informationPanelToggle"),name:"toggled?",children:T(cz,{children:T("span",{children:"i"})})})})},hz=et.memo(dz),fz=oe(Qs.Trigger,{width:"30px",padding:"5px",marginBottom:"auto"}),pz=oe(fR,{h3:{color:"$primaryAlt",fontSize:"$2",fontWeight:"700",margin:"$2 0"},button:{},"& ul li":{marginBottom:"$1"}});function gz(i){const{vault:e}=gt();try{const t=i&&e.get(i);if(!t)throw new Error(`Vault entity ${i} not found.`);return(t==null?void 0:t["@id"])||(t==null?void 0:t.id)}catch(t){return console.error(t),i}}function xR(i,e){const t=[];if(!i)return t;for(const n of i)if(n.id){const r=e.get(n.id);r&&t.push(r)}return t}function mz(){const{activeCanvas:i,activeManifest:e,vault:t}=gt(),[n,r]=se({root:[],canvas:[]});return ne(()=>{const s=t.get(e),o=t.get(i),a=s==null?void 0:s.rendering,l=o==null?void 0:o.rendering,c=xR(a,t),u=xR(l,t);r({root:c,canvas:u})},[i,e,t]),{...n}}function TR(i,e){return i.map(({format:t,id:n,label:r})=>{const s=gz(n);return{format:t,id:s,label:Di(r)||e}})}function vz(){const i=mz(),e=TR((i==null?void 0:i.root)||[],"Root Rendering Label"),t=TR((i==null?void 0:i.canvas)||[],"Canvas Rendering Label");return{allPages:e,individualPages:t}}const yz=()=>{const{allPages:i,individualPages:e}=vz(),t=i.length>0||e.length>0,n=r=>{window.open(r,"_blank")};return t?T(Qs,{children:[T(fz,{"data-testid":"download-button",children:T(ri,{children:T(ri.Download,{})})}),T(pz,{"data-testid":"download-content",children:[e.length>0&&T(Ee,{children:[T("h3",{children:"Individual Pages"}),T("ul",{children:e.map(({format:r,id:s,label:o})=>T("li",{children:T("button",{onClick:()=>n(s),children:[o," (",r,")"]})},o))})]}),i.length>0&&T(Ee,{children:[T("h3",{children:"All Pages"}),T("ul",{children:i.map(({format:r,id:s,label:o})=>T("li",{children:T("button",{onClick:()=>n(s),children:[o," (",r,")"]})},o))})]})]})]}):null},Sz=({manifestId:i,manifestLabel:e})=>{const t=gt(),{collection:n,configOptions:r}=t,{informationPanel:s,showDownload:o,showIIIFBadge:a,showTitle:l}=r,c=o||a||(s==null?void 0:s.renderToggle),{t:u}=dn();return T(Y8,{className:"clover-viewer-header",children:[n!=null&&n.items?T(Z8,{}):T(q8,{className:l?"":"visually-hidden",children:l&&T(yr,{label:e,className:"label"})}),c&&T(X8,{children:[o&&T(yz,{}),a&&T(Qs,{children:[T(K8,{children:T(tz,{title:u("commonShare")})}),T(fR,{children:[(n==null?void 0:n.items)&&T("button",{onClick:d=>{d.preventDefault(),window.open(n.id,"_blank")},children:u("shareCollectionJson")}),T("button",{onClick:d=>{d.preventDefault(),window.open(i,"_blank")},children:u("shareManifestJson")})," ",(n==null?void 0:n.items)&&T(pR,{textPrompt:u("shareCollectionCopy"),textToCopy:n.id}),T(pR,{textPrompt:u("shareManifestCopy"),textToCopy:i})]})]}),(s==null?void 0:s.renderToggle)&&T(hz,{})]})]})},xz=i=>{const e=()=>window.matchMedia?window.matchMedia(i).matches:!1,[t,n]=se(e);return ne(()=>{const r=()=>n(e);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)}),t},Tz=({manifest:i,theme:e,iiifContentSearchQuery:t,contentSearchCallback:n})=>{var P;const r=gt(),s=Ti(),{activeCanvas:o,isInformationOpen:a,vault:l,configOptions:c,visibleCanvases:u}=r,d=["100%","auto"],h=(c==null?void 0:c.canvasHeight)&&d.includes(c==null?void 0:c.canvasHeight),[f,p]=se(!1),[g,m]=se([]),[v,y]=se([]),[S,x]=se(),E=xz(Ox.sm),[C,b]=se(),I=Ce(k=>{s({type:"updateInformationOpen",isInformationOpen:k})},[s]);ne(()=>{var k;(k=c==null?void 0:c.informationPanel)!=null&&k.open&&I(!E)},[E,(P=c==null?void 0:c.informationPanel)==null?void 0:P.open]),ne(()=>{},[E]),ne(()=>{const k=ns(l,o);k&&(p(["Sound","Video"].indexOf(k[0].type)>-1),m(k));const N=OD(l,i,o);s({type:"updateVisibleCanvases",visibleCanvases:N})},[o,E,i,l,s]),ne(()=>{(async()=>{const k=await Promise.all(u.map(N=>wB(l,N.id)));y(k.flat())})()},[u]);const D=i.service.some(k=>["SearchService1","SearchService2"].includes(k.type||k["@type"]));return ne(()=>{if(D){const k=i.service.find(N=>["SearchService1","SearchService2"].includes(N.type||N["@type"]));k&&b(k.id||k["@id"])}},[i,D]),ne(()=>{var k;C&&((k=c.informationPanel)==null?void 0:k.renderContentSearch)!==!1&&Bb(l,C,t).then(N=>x(N))},[C]),T(If,{FallbackComponent:Of,children:T(AB,{className:`${e} clover-viewer`,css:{background:c==null?void 0:c.background},"data-absolute-position":h,"data-information-panel-open":a,children:T(EB,{open:a,onOpenChange:I,children:[T(Sz,{manifestLabel:i.label,manifestId:i.id}),T(j8,{activeCanvas:o,painting:g,annotationResources:v,searchServiceUrl:C,setContentSearchResource:x,contentSearchResource:S,contentSearchCallback:n,initialSearchQuery:t==null?void 0:t.q,items:i.items,isAudioVideo:f})]})})})},ER={ignoreCache:!1,headers:{Accept:"application/json, text/javascript, text/plain"},timeout:5e3,withCredentials:!1};function Ez(i){return{ok:i.status>=200&&i.status<300,status:i.status,statusText:i.statusText,headers:i.getAllResponseHeaders(),data:i.responseText,json:()=>JSON.parse(i.responseText)}}function wR(i,e=null){return{ok:!1,status:i.status,statusText:i.statusText,headers:i.getAllResponseHeaders(),data:e||i.statusText,json:()=>JSON.parse(e||i.statusText)}}function wz(i,e=ER){const t=e.headers||ER.headers;return new Promise((n,r)=>{const s=new XMLHttpRequest;s.open("get",i),s.withCredentials=e.withCredentials,t&&Object.keys(t).forEach(o=>s.setRequestHeader(o,t[o])),s.onload=()=>{n(Ez(s))},s.onerror=()=>{r(wR(s,"Failed to make request."))},s.ontimeout=()=>{r(wR(s,"Request took longer than expected."))},s.send()})}const bR={"@context":"http://iiif.io/api/presentation/3/context.json",id:"https://example.org/iiif/content-state/specific-resource",type:"Annotation",motivation:["contentState"],target:{type:"SpecificResource",source:{id:"https://example.org/iiif/manifest/canvas/0",type:"Canvas",partOf:[{id:"https://example.org/iiif/manifest",type:"Manifest"}]}},body:[]},bz=({canvasIdCallback:i,contentStateCallback:e,contentSearchCallback:t,customDisplays:n=[],plugins:r=[],customTheme:s,iiifContent:o,id:a,manifestId:l,options:c,iiifContentSearchQuery:u})=>{var f,p,g;let d=o;a&&(d=a),l&&(d=l);const h=zx((p=(f=c==null?void 0:c.informationPanel)==null?void 0:f.vtt)==null?void 0:p.autoScroll);return T(RM,{initialState:{...Bf,customDisplays:n,plugins:r,isAutoScrollEnabled:h.enabled,isInformationOpen:!!((g=c==null?void 0:c.informationPanel)!=null&&g.open),vault:new wx({customFetcher:m=>wz(m,{withCredentials:c==null?void 0:c.withCredentials,headers:c==null?void 0:c.requestHeaders}).then(v=>JSON.parse(v.data))})},children:T(_z,{iiifContent:d,canvasIdCallback:i,contentStateCallback:e,contentSearchCallback:t,customTheme:s,options:c,iiifContentSearchQuery:u})})},_z=({canvasIdCallback:i,contentStateCallback:e,contentSearchCallback:t,customTheme:n,iiifContent:r,options:s,iiifContentSearchQuery:o})=>{const a=Ti(),l=gt(),{activeCanvas:c,activeManifest:u,activeSelector:d,isLoaded:h,vault:f,visibleCanvases:p}=l,[g,m]=se(),[v,y]=se();let S={};if(n&&(S=hM("custom",n)),ne(()=>{a({type:"updateActiveSelector",selector:void 0})},[c,u]),ne(()=>{var x;if(i&&i(c),e&&u&&c){const E=((x=p[0])==null?void 0:x.id)||c,C=`${u}/state/${Bx(E+JSON.stringify(d))}`,b={...bR,id:C,target:{type:"SpecificResource",source:{id:E,type:"Canvas",partOf:[{id:u,type:"Manifest"}]},selector:d}};e({json:b,encoded:PD(JSON.stringify(b))})}},[c,u,d,i,e,p]),ne(()=>{if(!u)return;const x=f.get(u);(x&&Array.isArray(x.items)?Promise.resolve(x):f.load(u)).then(C=>{if(!C)return;y(C);const b=GS(f,C),I=c||LO(C);a({type:"updateActiveCanvas",canvasId:I}),a({type:"updateManifestSequence",sequence:b});const D=C.viewingDirection||"left-to-right",P=C.behavior||[],k=Array.isArray(P)?P.includes("paged"):P==="paged";a({type:"updateViewingDirection",viewingDirection:D}),a({type:"updateIsPaged",isPaged:k})}).catch(C=>{console.error(`Manifest failed to load: ${C}`)}).finally(()=>{a({type:"updateIsLoaded",isLoaded:!0})})},[r,u,a,f]),ne(()=>{a({type:"updateConfigOptions",configOptions:s}),(async()=>{var C;if(!r)return;const E=PO(r);try{const b=typeof E=="object"&&(E!=null&&E.id)?await f.loadSync(E==null?void 0:E.id,E):await f.load(E);m(b)}catch(b){if((!E||!E.id)&&console.error(`Failed to load resource: ${b}`),E!=null&&E.id&&(E==null?void 0:E.type)==="Annotation"&&((C=E==null?void 0:E.motivation)!=null&&C.includes("contentState"))){const I=await f.loadSync(E.id,E);I&&m(I)}else E!=null&&E.id&&["Canvas","Manifest"].includes(E==null?void 0:E.type)&&await f.loadSync(E.id,E)&&m({...bR,target:E})}})()},[a,r,s,f]),ne(()=>{if(g)switch(g.type){case"Annotation":if(g!=null&&g.motivation&&(Array.isArray(g==null?void 0:g.motivation)?g!=null&&g.motivation.includes("contentState"):(g==null?void 0:g.motivation)==="content-state")){const{active:E}=bx(g);a({type:"updateActiveManifest",manifestId:E.manifest}),a({type:"updateActiveCanvas",canvasId:E.canvas}),a({type:"updateContentStateAnnotation",contentStateAnnotation:g})}break;case"Collection":const x=kO(g);a({type:"updateCollection",collection:g}),x&&a({type:"updateActiveManifest",manifestId:x});break;case"Manifest":a({type:"updateActiveManifest",manifestId:g.id});break}},[a,r,g]),!h)if(s!=null&&s.customLoadingComponent){const x=s.customLoadingComponent;return T(x,{})}else return T(Ee,{children:"Loading"});return!v||!v.items?(console.log(`The IIIF manifest ${r} failed to load.`),T(Ee,{})):v.items.length===0?(console.log(`The IIIF manifest ${r} does not contain canvases.`),T(Ee,{})):T(Tz,{manifest:v,theme:S,iiifContentSearchQuery:o,contentSearchCallback:t},v.id)};function Az(i){const e=ge(),{id:t}=i,n=i["iiif-content"];return Ki(()=>{i.__registerPublicApi&&i.__registerPublicApi(r=>{e.current=r})},[]),T(bz,{id:t,iiifContent:n})}typeof window<"u"&&_T(Az,"clover-viewer",["id","iiif-content"],{shadow:!1,onConstruct(i){i._props={__registerPublicApi:e=>{Object.assign(i,e(i))}}}});function Dd(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var us=Dd();function _R(i){us=i}var to={exec:()=>null};function Qe(i,e=""){let t=typeof i=="string"?i:i.source,n={replace:(r,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(si.caret,"$1"),t=t.replace(r,o),n},getRegex:()=>new RegExp(t,e)};return n}var Rz=((i="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+i)}catch{return!1}})(),si={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:i=>new RegExp(`^( {0,3}${i})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}#`),htmlBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:i=>new RegExp(`^ {0,${Math.min(3,i-1)}}>`)},Cz=/^(?:[ \t]*(?:\n|$))+/,Iz=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pz=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Lz=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,lv=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,AR=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,RR=Qe(AR).replace(/bull/g,lv).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),kz=Qe(AR).replace(/bull/g,lv).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),cv=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Dz=/^[^\n]+/,uv=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Oz=Qe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",uv).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Mz=Qe(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,lv).getRegex(),Od="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",dv=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Fz=Qe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",dv).replace("tag",Od).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),CR=Qe(cv).replace("hr",Xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Od).getRegex(),Nz=Qe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",CR).getRegex(),hv={blockquote:Nz,code:Iz,def:Oz,fences:Pz,heading:Lz,hr:Xl,html:Fz,lheading:RR,list:Mz,newline:Cz,paragraph:CR,table:to,text:Dz},IR=Qe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Od).getRegex(),Bz={...hv,lheading:kz,table:IR,paragraph:Qe(cv).replace("hr",Xl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",IR).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Od).getRegex()},Uz={...hv,html:Qe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",dv).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:to,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Qe(cv).replace("hr",Xl).replace("heading",` *#{1,6} *[^
|
|
121
|
+
]`).replace("lheading",RR).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},$z=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Hz=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,PR=/^( {2,}|\\)\n(?!\s*$)/,zz=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,da=/[\p{P}\p{S}]/u,Md=/[\s\p{P}\p{S}]/u,fv=/[^\s\p{P}\p{S}]/u,Vz=Qe(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Md).getRegex(),LR=/(?!~)[\p{P}\p{S}]/u,Gz=/(?!~)[\s\p{P}\p{S}]/u,Wz=/(?:[^\s\p{P}\p{S}]|~)/u,jz=Qe(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Rz?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),kR=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Kz=Qe(kR,"u").replace(/punct/g,da).getRegex(),qz=Qe(kR,"u").replace(/punct/g,LR).getRegex(),DR="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Yz=Qe(DR,"gu").replace(/notPunctSpace/g,fv).replace(/punctSpace/g,Md).replace(/punct/g,da).getRegex(),Xz=Qe(DR,"gu").replace(/notPunctSpace/g,Wz).replace(/punctSpace/g,Gz).replace(/punct/g,LR).getRegex(),Zz=Qe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,fv).replace(/punctSpace/g,Md).replace(/punct/g,da).getRegex(),Qz=Qe(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,da).getRegex(),Jz="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",e5=Qe(Jz,"gu").replace(/notPunctSpace/g,fv).replace(/punctSpace/g,Md).replace(/punct/g,da).getRegex(),t5=Qe(/\\(punct)/,"gu").replace(/punct/g,da).getRegex(),i5=Qe(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),n5=Qe(dv).replace("(?:-->|$)","-->").getRegex(),r5=Qe("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",n5).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Fd=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,s5=Qe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Fd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),OR=Qe(/^!?\[(label)\]\[(ref)\]/).replace("label",Fd).replace("ref",uv).getRegex(),MR=Qe(/^!?\[(ref)\](?:\[\])?/).replace("ref",uv).getRegex(),o5=Qe("reflink|nolink(?!\\()","g").replace("reflink",OR).replace("nolink",MR).getRegex(),FR=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,pv={_backpedal:to,anyPunctuation:t5,autolink:i5,blockSkip:jz,br:PR,code:Hz,del:to,delLDelim:to,delRDelim:to,emStrongLDelim:Kz,emStrongRDelimAst:Yz,emStrongRDelimUnd:Zz,escape:$z,link:s5,nolink:MR,punctuation:Vz,reflink:OR,reflinkSearch:o5,tag:r5,text:zz,url:to},a5={...pv,link:Qe(/^!?\[(label)\]\((.*?)\)/).replace("label",Fd).getRegex(),reflink:Qe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Fd).getRegex()},gv={...pv,emStrongRDelimAst:Xz,emStrongLDelim:qz,delLDelim:Qz,delRDelim:e5,url:Qe(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",FR).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Qe(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",FR).getRegex()},l5={...gv,br:Qe(PR).replace("{2,}","*").getRegex(),text:Qe(gv.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Nd={normal:hv,gfm:Bz,pedantic:Uz},Zl={normal:pv,gfm:gv,breaks:l5,pedantic:a5},c5={"&":"&","<":"<",">":">",'"':""","'":"'"},NR=i=>c5[i];function Vn(i,e){if(e){if(si.escapeTest.test(i))return i.replace(si.escapeReplace,NR)}else if(si.escapeTestNoEncode.test(i))return i.replace(si.escapeReplaceNoEncode,NR);return i}function BR(i){try{i=encodeURI(i).replace(si.percentDecode,"%")}catch{return null}return i}function UR(i,e){var s;let t=i.replace(si.findPipe,(o,a,l)=>{let c=!1,u=a;for(;--u>=0&&l[u]==="\\";)c=!c;return c?"|":" |"}),n=t.split(si.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!((s=n.at(-1))!=null&&s.trim())&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(si.slashPipe,"|");return n}function ds(i,e,t){let n=i.length;if(n===0)return"";let r=0;for(;r<n&&i.charAt(n-r-1)===e;)r++;return i.slice(0,n-r)}function $R(i){let e=i.split(`
|
|
122
|
+
`),t=e.length-1;for(;t>=0&&si.blankLine.test(e[t]);)t--;return e.length-t<=2?i:e.slice(0,t+1).join(`
|
|
123
|
+
`)}function u5(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<i.length;n++)if(i[n]==="\\")n++;else if(i[n]===e[0])t++;else if(i[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function d5(i,e=0){let t=e,n="";for(let r of i)if(r===" "){let s=4-t%4;n+=" ".repeat(s),t+=s}else n+=r,t++;return n}function HR(i,e,t,n,r){let s=e.href,o=e.title||null,a=i[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let l={type:i[0].charAt(0)==="!"?"image":"link",raw:t,href:s,title:o,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,l}function h5(i,e,t){let n=i.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(`
|
|
124
|
+
`).map(s=>{let o=s.match(t.other.beginningSpace);if(o===null)return s;let[a]=o;return a.length>=r.length?s.slice(r.length):s}).join(`
|
|
125
|
+
`)}var Ql=class{constructor(i){lt(this,"options");lt(this,"rules");lt(this,"lexer");this.options=i||us}space(i){let e=this.rules.block.newline.exec(i);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(i){let e=this.rules.block.code.exec(i);if(e){let t=this.options.pedantic?e[0]:$R(e[0]),n=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:n}}}fences(i){let e=this.rules.block.fences.exec(i);if(e){let t=e[0],n=h5(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:n}}}heading(i){let e=this.rules.block.heading.exec(i);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let n=ds(t,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(t=n.trim())}return{type:"heading",raw:ds(e[0],`
|
|
126
|
+
`),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(i){let e=this.rules.block.hr.exec(i);if(e)return{type:"hr",raw:ds(e[0],`
|
|
127
|
+
`)}}blockquote(i){let e=this.rules.block.blockquote.exec(i);if(e){let t=ds(e[0],`
|
|
128
|
+
`).split(`
|
|
129
|
+
`),n="",r="",s=[];for(;t.length>0;){let o=!1,a=[],l;for(l=0;l<t.length;l++)if(this.rules.other.blockquoteStart.test(t[l]))a.push(t[l]),o=!0;else if(!o)a.push(t[l]);else break;t=t.slice(l);let c=a.join(`
|
|
130
|
+
`),u=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
131
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
132
|
+
${c}`:c,r=r?`${r}
|
|
133
|
+
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,s,!0),this.lexer.state.top=d,t.length===0)break;let h=s.at(-1);if((h==null?void 0:h.type)==="code")break;if((h==null?void 0:h.type)==="blockquote"){let f=h,p=f.raw+`
|
|
134
|
+
`+t.join(`
|
|
135
|
+
`),g=this.blockquote(p);s[s.length-1]=g,n=n.substring(0,n.length-f.raw.length)+g.raw,r=r.substring(0,r.length-f.text.length)+g.text;break}else if((h==null?void 0:h.type)==="list"){let f=h,p=f.raw+`
|
|
136
|
+
`+t.join(`
|
|
137
|
+
`),g=this.list(p);s[s.length-1]=g,n=n.substring(0,n.length-h.raw.length)+g.raw,r=r.substring(0,r.length-f.raw.length)+g.raw,t=p.substring(s.at(-1).raw.length).split(`
|
|
138
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:s,text:r}}}list(i){var t,n;let e=this.rules.block.list.exec(i);if(e){let r=e[1].trim(),s=r.length>1,o={type:"list",raw:"",ordered:s,start:s?+r.slice(0,-1):"",loose:!1,items:[]};r=s?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=s?r:"[*+-]");let a=this.rules.other.listItemRegex(r),l=!1;for(;i;){let u=!1,d="",h="";if(!(e=a.exec(i))||this.rules.block.hr.test(i))break;d=e[0],i=i.substring(d.length);let f=d5(e[2].split(`
|
|
139
|
+
`,1)[0],e[1].length),p=i.split(`
|
|
140
|
+
`,1)[0],g=!f.trim(),m=0;if(this.options.pedantic?(m=2,h=f.trimStart()):g?m=e[1].length+1:(m=f.search(this.rules.other.nonSpaceChar),m=m>4?1:m,h=f.slice(m),m+=e[1].length),g&&this.rules.other.blankLine.test(p)&&(d+=p+`
|
|
141
|
+
`,i=i.substring(p.length+1),u=!0),!u){let v=this.rules.other.nextBulletRegex(m),y=this.rules.other.hrRegex(m),S=this.rules.other.fencesBeginRegex(m),x=this.rules.other.headingBeginRegex(m),E=this.rules.other.htmlBeginRegex(m),C=this.rules.other.blockquoteBeginRegex(m);for(;i;){let b=i.split(`
|
|
142
|
+
`,1)[0],I;if(p=b,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),I=p):I=p.replace(this.rules.other.tabCharGlobal," "),S.test(p)||x.test(p)||E.test(p)||C.test(p)||v.test(p)||y.test(p))break;if(I.search(this.rules.other.nonSpaceChar)>=m||!p.trim())h+=`
|
|
143
|
+
`+I.slice(m);else{if(g||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(f)||x.test(f)||y.test(f))break;h+=`
|
|
144
|
+
`+p}g=!p.trim(),d+=b+`
|
|
145
|
+
`,i=i.substring(b.length+1),f=I.slice(m)}}o.loose||(l?o.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(l=!0)),o.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),o.raw+=d}let c=o.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let u of o.items){if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),u.task){if(u.text=u.text.replace(this.rules.other.listReplaceTask,""),((t=u.tokens[0])==null?void 0:t.type)==="text"||((n=u.tokens[0])==null?void 0:n.type)==="paragraph"){u.tokens[0].raw=u.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),u.tokens[0].text=u.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(u.raw);if(d){let h={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};u.checked=h.checked,o.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=h.raw+u.tokens[0].raw,u.tokens[0].text=h.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(h)):u.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):u.tokens.unshift(h)}}if(!o.loose){let d=u.tokens.filter(f=>f.type==="space"),h=d.length>0&&d.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let u of o.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return o}}html(i){let e=this.rules.block.html.exec(i);if(e){let t=$R(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(i){let e=this.rules.block.def.exec(i);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:ds(e[0],`
|
|
146
|
+
`),href:n,title:r}}}table(i){var o;let e=this.rules.block.table.exec(i);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=UR(e[1]),n=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=(o=e[3])!=null&&o.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
147
|
+
`):[],s={type:"table",raw:ds(e[0],`
|
|
148
|
+
`),header:[],align:[],rows:[]};if(t.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a<t.length;a++)s.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:s.align[a]});for(let a of r)s.rows.push(UR(a,s.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:s.align[c]})));return s}}lheading(i){let e=this.rules.block.lheading.exec(i);if(e){let t=e[1].trim();return{type:"heading",raw:ds(e[0],`
|
|
149
|
+
`),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(i){let e=this.rules.block.paragraph.exec(i);if(e){let t=e[1].charAt(e[1].length-1)===`
|
|
150
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(i){let e=this.rules.block.text.exec(i);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(i){let e=this.rules.inline.escape.exec(i);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(i){let e=this.rules.inline.tag.exec(i);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(i){let e=this.rules.inline.link.exec(i);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let s=ds(t.slice(0,-1),"\\");if((t.length-s.length)%2===0)return}else{let s=u5(e[2],"()");if(s===-2)return;if(s>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+s;e[2]=e[2].substring(0,s),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let n=e[2],r="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(n);s&&(n=s[1],r=s[3])}else r=e[3]?e[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?n=n.slice(1):n=n.slice(1,-1)),HR(e,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(i,e){let t;if((t=this.rules.inline.reflink.exec(i))||(t=this.rules.inline.nolink.exec(i))){let n=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=e[n.toLowerCase()];if(!r){let s=t[0].charAt(0);return{type:"text",raw:s,text:s}}return HR(t,r,t[0],this.lexer,this.rules)}}emStrong(i,e,t=""){let n=this.rules.inline.emStrongLDelim.exec(i);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!t||this.rules.inline.punctuation.exec(t))){let r=[...n[0]].length-1,s,o,a=r,l=0,c=n[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*i.length+r);(n=c.exec(e))!==null;){if(s=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!s)continue;if(o=[...s].length,n[3]||n[4]){a+=o;continue}else if((n[5]||n[6])&&r%3&&!((r+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let u=[...n[0]][0].length,d=i.slice(0,r+n.index+u+o);if(Math.min(r,o)%2){let f=d.slice(1,-1);return{type:"em",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}let h=d.slice(2,-2);return{type:"strong",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(i){let e=this.rules.inline.code.exec(i);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(t),r=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return n&&r&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(i){let e=this.rules.inline.br.exec(i);if(e)return{type:"br",raw:e[0]}}del(i,e,t=""){let n=this.rules.inline.delLDelim.exec(i);if(n&&(!n[1]||!t||this.rules.inline.punctuation.exec(t))){let r=[...n[0]].length-1,s,o,a=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*i.length+r);(n=l.exec(e))!==null;){if(s=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!s||(o=[...s].length,o!==r))continue;if(n[3]||n[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let c=[...n[0]][0].length,u=i.slice(0,r+n.index+c+o),d=u.slice(r,-r);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(i){let e=this.rules.inline.autolink.exec(i);if(e){let t,n;return e[2]==="@"?(t=e[1],n="mailto:"+t):(t=e[1],n=t),{type:"link",raw:e[0],text:t,href:n,tokens:[{type:"text",raw:t,text:t}]}}}url(i){var t;let e;if(e=this.rules.inline.url.exec(i)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let s;do s=e[0],e[0]=((t=this.rules.inline._backpedal.exec(e[0]))==null?void 0:t[0])??"";while(s!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(i){let e=this.rules.inline.text.exec(i);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},rn=class k0{constructor(e){lt(this,"tokens");lt(this,"options");lt(this,"state");lt(this,"inlineQueue");lt(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||us,this.options.tokenizer=this.options.tokenizer||new Ql,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:si,block:Nd.normal,inline:Zl.normal};this.options.pedantic?(t.block=Nd.pedantic,t.inline=Zl.pedantic):this.options.gfm&&(t.block=Nd.gfm,this.options.breaks?t.inline=Zl.breaks:t.inline=Zl.gfm),this.tokenizer.rules=t}static get rules(){return{block:Nd,inline:Zl}}static lex(e,t){return new k0(t).lex(e)}static lexInline(e,t){return new k0(t).inlineTokens(e)}lex(e){e=e.replace(si.carriageReturn,`
|
|
151
|
+
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){var s,o,a;this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(si.tabCharGlobal," ").replace(si.spaceLine,""));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let l;if((o=(s=this.options.extensions)==null?void 0:s.block)!=null&&o.some(u=>(l=u.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.space(e)){e=e.substring(l.raw.length);let u=t.at(-1);l.raw.length===1&&u!==void 0?u.raw+=`
|
|
152
|
+
`:t.push(l);continue}if(l=this.tokenizer.code(e)){e=e.substring(l.raw.length);let u=t.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(`
|
|
153
|
+
`)?"":`
|
|
154
|
+
`)+l.raw,u.text+=`
|
|
155
|
+
`+l.text,this.inlineQueue.at(-1).src=u.text):t.push(l);continue}if(l=this.tokenizer.fences(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.heading(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.hr(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.blockquote(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.list(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.html(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.def(e)){e=e.substring(l.raw.length);let u=t.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(`
|
|
156
|
+
`)?"":`
|
|
157
|
+
`)+l.raw,u.text+=`
|
|
158
|
+
`+l.raw,this.inlineQueue.at(-1).src=u.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},t.push(l));continue}if(l=this.tokenizer.table(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.lheading(e)){e=e.substring(l.raw.length),t.push(l);continue}let c=e;if((a=this.options.extensions)!=null&&a.startBlock){let u=1/0,d=e.slice(1),h;this.options.extensions.startBlock.forEach(f=>{h=f.call({lexer:this},d),typeof h=="number"&&h>=0&&(u=Math.min(u,h))}),u<1/0&&u>=0&&(c=e.substring(0,u+1))}if(this.state.top&&(l=this.tokenizer.paragraph(c))){let u=t.at(-1);n&&(u==null?void 0:u.type)==="paragraph"?(u.raw+=(u.raw.endsWith(`
|
|
159
|
+
`)?"":`
|
|
160
|
+
`)+l.raw,u.text+=`
|
|
161
|
+
`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):t.push(l),n=c.length!==e.length,e=e.substring(l.raw.length);continue}if(l=this.tokenizer.text(e)){e=e.substring(l.raw.length);let u=t.at(-1);(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(`
|
|
162
|
+
`)?"":`
|
|
163
|
+
`)+l.raw,u.text+=`
|
|
164
|
+
`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):t.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){var c,u,d,h,f;this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)s=r[2]?r[2].length:0,n=n.slice(0,r.index+s)+"["+"a".repeat(r[0].length-s-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=((u=(c=this.options.hooks)==null?void 0:c.emStrongMask)==null?void 0:u.call({lexer:this},n))??n;let o=!1,a="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(a=""),o=!1;let p;if((h=(d=this.options.extensions)==null?void 0:d.inline)!=null&&h.some(m=>(p=m.call({lexer:this},e,t))?(e=e.substring(p.raw.length),t.push(p),!0):!1))continue;if(p=this.tokenizer.escape(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.tag(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.link(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(p.raw.length);let m=t.at(-1);p.type==="text"&&(m==null?void 0:m.type)==="text"?(m.raw+=p.raw,m.text+=p.text):t.push(p);continue}if(p=this.tokenizer.emStrong(e,n,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.codespan(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.br(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.del(e,n,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.autolink(e)){e=e.substring(p.raw.length),t.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(e))){e=e.substring(p.raw.length),t.push(p);continue}let g=e;if((f=this.options.extensions)!=null&&f.startInline){let m=1/0,v=e.slice(1),y;this.options.extensions.startInline.forEach(S=>{y=S.call({lexer:this},v),typeof y=="number"&&y>=0&&(m=Math.min(m,y))}),m<1/0&&m>=0&&(g=e.substring(0,m+1))}if(p=this.tokenizer.inlineText(g)){e=e.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),o=!0;let m=t.at(-1);(m==null?void 0:m.type)==="text"?(m.raw+=p.raw,m.text+=p.text):t.push(p);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},Jl=class{constructor(i){lt(this,"options");lt(this,"parser");this.options=i||us}space(i){return""}code({text:i,lang:e,escaped:t}){var s;let n=(s=(e||"").match(si.notSpaceStart))==null?void 0:s[0],r=i.replace(si.endingNewline,"")+`
|
|
165
|
+
`;return n?'<pre><code class="language-'+Vn(n)+'">'+(t?r:Vn(r,!0))+`</code></pre>
|
|
166
|
+
`:"<pre><code>"+(t?r:Vn(r,!0))+`</code></pre>
|
|
167
|
+
`}blockquote({tokens:i}){return`<blockquote>
|
|
168
|
+
${this.parser.parse(i)}</blockquote>
|
|
169
|
+
`}html({text:i}){return i}def(i){return""}heading({tokens:i,depth:e}){return`<h${e}>${this.parser.parseInline(i)}</h${e}>
|
|
170
|
+
`}hr(i){return`<hr>
|
|
171
|
+
`}list(i){let e=i.ordered,t=i.start,n="";for(let o=0;o<i.items.length;o++){let a=i.items[o];n+=this.listitem(a)}let r=e?"ol":"ul",s=e&&t!==1?' start="'+t+'"':"";return"<"+r+s+`>
|
|
172
|
+
`+n+"</"+r+`>
|
|
173
|
+
`}listitem(i){return`<li>${this.parser.parse(i.tokens)}</li>
|
|
174
|
+
`}checkbox({checked:i}){return"<input "+(i?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:i}){return`<p>${this.parser.parseInline(i)}</p>
|
|
175
|
+
`}table(i){let e="",t="";for(let r=0;r<i.header.length;r++)t+=this.tablecell(i.header[r]);e+=this.tablerow({text:t});let n="";for(let r=0;r<i.rows.length;r++){let s=i.rows[r];t="";for(let o=0;o<s.length;o++)t+=this.tablecell(s[o]);n+=this.tablerow({text:t})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
176
|
+
<thead>
|
|
177
|
+
`+e+`</thead>
|
|
178
|
+
`+n+`</table>
|
|
179
|
+
`}tablerow({text:i}){return`<tr>
|
|
180
|
+
${i}</tr>
|
|
181
|
+
`}tablecell(i){let e=this.parser.parseInline(i.tokens),t=i.header?"th":"td";return(i.align?`<${t} align="${i.align}">`:`<${t}>`)+e+`</${t}>
|
|
182
|
+
`}strong({tokens:i}){return`<strong>${this.parser.parseInline(i)}</strong>`}em({tokens:i}){return`<em>${this.parser.parseInline(i)}</em>`}codespan({text:i}){return`<code>${Vn(i,!0)}</code>`}br(i){return"<br>"}del({tokens:i}){return`<del>${this.parser.parseInline(i)}</del>`}link({href:i,title:e,tokens:t}){let n=this.parser.parseInline(t),r=BR(i);if(r===null)return n;i=r;let s='<a href="'+i+'"';return e&&(s+=' title="'+Vn(e)+'"'),s+=">"+n+"</a>",s}image({href:i,title:e,text:t,tokens:n}){n&&(t=this.parser.parseInline(n,this.parser.textRenderer));let r=BR(i);if(r===null)return Vn(t);i=r;let s=`<img src="${i}" alt="${Vn(t)}"`;return e&&(s+=` title="${Vn(e)}"`),s+=">",s}text(i){return"tokens"in i&&i.tokens?this.parser.parseInline(i.tokens):"escaped"in i&&i.escaped?i.text:Vn(i.text)}},Bd=class{strong({text:i}){return i}em({text:i}){return i}codespan({text:i}){return i}del({text:i}){return i}html({text:i}){return i}text({text:i}){return i}link({text:i}){return""+i}image({text:i}){return""+i}br(){return""}checkbox({raw:i}){return i}},sn=class D0{constructor(e){lt(this,"options");lt(this,"renderer");lt(this,"textRenderer");this.options=e||us,this.options.renderer=this.options.renderer||new Jl,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bd}static parse(e,t){return new D0(t).parse(e)}static parseInline(e,t){return new D0(t).parseInline(e)}parse(e){var n,r;this.renderer.parser=this;let t="";for(let s=0;s<e.length;s++){let o=e[s];if((r=(n=this.options.extensions)==null?void 0:n.renderers)!=null&&r[o.type]){let l=o,c=this.options.extensions.renderers[l.type].call({parser:this},l);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){t+=c||"";continue}}let a=o;switch(a.type){case"space":{t+=this.renderer.space(a);break}case"hr":{t+=this.renderer.hr(a);break}case"heading":{t+=this.renderer.heading(a);break}case"code":{t+=this.renderer.code(a);break}case"table":{t+=this.renderer.table(a);break}case"blockquote":{t+=this.renderer.blockquote(a);break}case"list":{t+=this.renderer.list(a);break}case"checkbox":{t+=this.renderer.checkbox(a);break}case"html":{t+=this.renderer.html(a);break}case"def":{t+=this.renderer.def(a);break}case"paragraph":{t+=this.renderer.paragraph(a);break}case"text":{t+=this.renderer.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return t}parseInline(e,t=this.renderer){var r,s;this.renderer.parser=this;let n="";for(let o=0;o<e.length;o++){let a=e[o];if((s=(r=this.options.extensions)==null?void 0:r.renderers)!=null&&s[a.type]){let c=this.options.extensions.renderers[a.type].call({parser:this},a);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){n+=c||"";continue}}let l=a;switch(l.type){case"escape":{n+=t.text(l);break}case"html":{n+=t.html(l);break}case"link":{n+=t.link(l);break}case"image":{n+=t.image(l);break}case"checkbox":{n+=t.checkbox(l);break}case"strong":{n+=t.strong(l);break}case"em":{n+=t.em(l);break}case"codespan":{n+=t.codespan(l);break}case"br":{n+=t.br(l);break}case"del":{n+=t.del(l);break}case"text":{n+=t.text(l);break}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return n}},ha=(Ch=class{constructor(i){lt(this,"options");lt(this,"block");this.options=i||us}preprocess(i){return i}postprocess(i){return i}processAllTokens(i){return i}emStrongMask(i){return i}provideLexer(i=this.block){return i?rn.lex:rn.lexInline}provideParser(i=this.block){return i?sn.parse:sn.parseInline}},lt(Ch,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),lt(Ch,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Ch),zR=class{constructor(...i){lt(this,"defaults",Dd());lt(this,"options",this.setOptions);lt(this,"parse",this.parseMarkdown(!0));lt(this,"parseInline",this.parseMarkdown(!1));lt(this,"Parser",sn);lt(this,"Renderer",Jl);lt(this,"TextRenderer",Bd);lt(this,"Lexer",rn);lt(this,"Tokenizer",Ql);lt(this,"Hooks",ha);this.use(...i)}walkTokens(i,e){var n,r;let t=[];for(let s of i)switch(t=t.concat(e.call(this,s)),s.type){case"table":{let o=s;for(let a of o.header)t=t.concat(this.walkTokens(a.tokens,e));for(let a of o.rows)for(let l of a)t=t.concat(this.walkTokens(l.tokens,e));break}case"list":{let o=s;t=t.concat(this.walkTokens(o.items,e));break}default:{let o=s;(r=(n=this.defaults.extensions)==null?void 0:n.childTokens)!=null&&r[o.type]?this.defaults.extensions.childTokens[o.type].forEach(a=>{let l=o[a].flat(1/0);t=t.concat(this.walkTokens(l,e))}):o.tokens&&(t=t.concat(this.walkTokens(o.tokens,e)))}}return t}use(...i){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return i.forEach(t=>{let n={...t};if(n.async=this.defaults.async||n.async||!1,t.extensions&&(t.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let s=e.renderers[r.name];s?e.renderers[r.name]=function(...o){let a=r.renderer.apply(this,o);return a===!1&&(a=s.apply(this,o)),a}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=e[r.level];s?s.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),n.extensions=e),t.renderer){let r=this.defaults.renderer||new Jl(this.defaults);for(let s in t.renderer){if(!(s in r))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,a=t.renderer[o],l=r[o];r[o]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}n.renderer=r}if(t.tokenizer){let r=this.defaults.tokenizer||new Ql(this.defaults);for(let s in t.tokenizer){if(!(s in r))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,a=t.tokenizer[o],l=r[o];r[o]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}n.tokenizer=r}if(t.hooks){let r=this.defaults.hooks||new ha;for(let s in t.hooks){if(!(s in r))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,a=t.hooks[o],l=r[o];ha.passThroughHooks.has(s)?r[o]=c=>{if(this.defaults.async&&ha.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await a.call(r,c);return l.call(r,d)})();let u=a.call(r,c);return l.call(r,u)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(r,c);return d===!1&&(d=await l.apply(r,c)),d})();let u=a.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}n.hooks=r}if(t.walkTokens){let r=this.defaults.walkTokens,s=t.walkTokens;n.walkTokens=function(o){let a=[];return a.push(s.call(this,o)),r&&(a=a.concat(r.call(this,o))),a}}this.defaults={...this.defaults,...n}}),this}setOptions(i){return this.defaults={...this.defaults,...i},this}lexer(i,e){return rn.lex(i,e??this.defaults)}parser(i,e){return sn.parse(i,e??this.defaults)}parseMarkdown(i){return(e,t)=>{let n={...t},r={...this.defaults,...n},s=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&n.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=i),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(e):e,a=await(r.hooks?await r.hooks.provideLexer(i):i?rn.lex:rn.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(i):i?sn.parse:sn.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(s);try{r.hooks&&(e=r.hooks.preprocess(e));let o=(r.hooks?r.hooks.provideLexer(i):i?rn.lex:rn.lexInline)(e,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(i):i?sn.parse:sn.parseInline)(o,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(o){return s(o)}}}onError(i,e){return t=>{if(t.message+=`
|
|
183
|
+
Please report this to https://github.com/markedjs/marked.`,i){let n="<p>An error occurred:</p><pre>"+Vn(t.message+"",!0)+"</pre>";return e?Promise.resolve(n):n}if(e)return Promise.reject(t);throw t}}},io=new zR;function tt(i,e){return io.parse(i,e)}tt.options=tt.setOptions=function(i){return io.setOptions(i),tt.defaults=io.defaults,_R(tt.defaults),tt},tt.getDefaults=Dd,tt.defaults=us,tt.use=function(...i){return io.use(...i),tt.defaults=io.defaults,_R(tt.defaults),tt},tt.walkTokens=function(i,e){return io.walkTokens(i,e)},tt.parseInline=io.parseInline,tt.Parser=sn,tt.parser=sn.parse,tt.Renderer=Jl,tt.TextRenderer=Bd,tt.Lexer=rn,tt.lexer=rn.lex,tt.Tokenizer=Ql,tt.Hooks=ha,tt.parse=tt;var f5=tt.options,p5=tt.setOptions,g5=tt.use,m5=tt.walkTokens,v5=tt.parseInline,y5=tt,S5=sn.parse,x5=rn.lex;const T5=Object.freeze(Object.defineProperty({__proto__:null,Hooks:ha,Lexer:rn,Marked:zR,Parser:sn,Renderer:Jl,TextRenderer:Bd,Tokenizer:Ql,get defaults(){return us},getDefaults:Dd,lexer:x5,marked:tt,options:f5,parse:y5,parseInline:v5,parser:S5,setOptions:p5,use:g5,walkTokens:m5},Symbol.toStringTag,{value:"Module"}));function E5(i,e){const t={type:"footnotes",raw:e,rawItems:[],items:[]};return{name:"footnote",level:"block",childTokens:["content"],tokenizer(n){i.hasFootnotes||(this.lexer.tokens.push(t),i.tokens=this.lexer.tokens,i.hasFootnotes=!0,t.rawItems=[],t.items=[]);const r=/^\[\^([^\]\n]+)\]:(?:[ \t]+|[\n]*?|$)([^\n]*?(?:\n|$)(?:\n*?[ ]{4,}[^\n]*)*)/.exec(n);if(r){const[s,o,a=""]=r;let l=a.split(`
|
|
184
|
+
`).reduce((d,h)=>d+`
|
|
185
|
+
`+h.replace(/^(?:[ ]{4}|[\t])/,""),"");const c=l.trimEnd().split(`
|
|
186
|
+
`).pop();l+=c&&/^[ \t]*?[>\-*][ ]|[`]{3,}$|^[ \t]*?[|].+[|]$/.test(c)?`
|
|
187
|
+
|
|
188
|
+
`:"";const u={type:"footnote",raw:s,label:o,refs:[],content:this.lexer.blockTokens(l)};return t.rawItems.push(u),u}},renderer(){return""}}}function w5(i){return i.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function b5(i,e=!1,t=!1){let n=0;return{name:"footnoteRef",level:"inline",tokenizer(r){const s=/^\[\^([^\]\n]+)\]/.exec(r);if(s){const[o,a]=s,l=this.lexer.tokens[0],c=l.rawItems.filter(f=>f.label===a);if(!c.length)return;const u=c[0],d=l.items.filter(f=>f.label===a)[0],h={type:"footnoteRef",raw:o,index:u.refs.length,id:"",label:a};return d?(h.id=d.refs[0].id,d.refs.push(h)):(n++,h.id=String(n),u.refs.push(h),l.items.push(u)),h}},renderer({index:r,id:s,label:o}){n=0;const a=encodeURIComponent(o),l=t?w5(o):s,c=r>0?`-${r+1}`:"";return`<sup><a id="${i}ref-${a}${c}" href="#${i+a}" data-${i}ref aria-describedby="${i}label">${e?`[${l}]`:l}</a></sup>`}}}function _5(i,e,t,n,r,s){return{name:"footnotes",renderer({raw:o,items:a=[]}){if(a.length===0)return"";const l=a.reduce((h,{label:f,content:p,refs:g})=>{const m=encodeURIComponent(f),v=this.parser.parse(p).trimEnd(),y=v.endsWith("</p>");let S=`<li id="${i+m}">
|
|
189
|
+
`;return S+=y?v.replace(/<\/p>$/,""):v,g.forEach((x,E)=>{const C=s.replace("{0}",f);let b,I;if(E>0){const D=E+1;b=`↩<sup>${D}</sup>`,I=`-${D}`}else b="↩",I="";S+=` <a href="#${i}ref-${m}${I}" data-${i}backref aria-label="${C}">${b}</a>`}),S+=y?`</p>
|
|
190
|
+
`:`
|
|
191
|
+
`,S+=`</li>
|
|
192
|
+
`,h+S},"");let c="";t&&(c+=`<hr data-${e}footnotes>
|
|
193
|
+
`);let u="";n&&(u=` class="${n}"`);let d="";return r&&(d=` class="${r}"`),c+=`<section${u} data-${e}footnotes>
|
|
194
|
+
`,c+=`<h2 id="${i}label"${d}>${o.trimEnd()}</h2>
|
|
195
|
+
`,c+=`<ol>
|
|
196
|
+
${l}</ol>
|
|
197
|
+
`,c+=`</section>
|
|
198
|
+
`,c}}}function A5(i={}){const{prefixId:e="footnote-",prefixData:t="",description:n="Footnotes",refMarkers:r=!1,footnoteDivider:s=!1,keepLabels:o=!1,sectionClass:a="footnotes",headingClass:l="sr-only",backRefLabel:c="Back to reference {0}"}=i,u={hasFootnotes:!1,tokens:[]};return{extensions:[E5(u,n),b5(e,r,o),_5(e,t,s,a,l,c)],walkTokens(d){d.type==="footnotes"&&u.tokens.indexOf(d)===0&&d.items.length&&(u.tokens[0]={type:"space",raw:""},u.tokens.push(d)),u.hasFootnotes&&(u.hasFootnotes=!1)}}}const R5=Object.freeze(Object.defineProperty({__proto__:null,default:A5},Symbol.toStringTag,{value:"Module"})),pe=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},C5=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=I5},I5=Number.MAX_SAFE_INTEGER||9007199254740991;let we=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),W=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i}({}),_=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({});var Ke={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ve={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class fa{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){const n=Math.pow(this.alpha_,e);this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class P5{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fa(e),this.fast_=new fa(t),this.defaultTTFB_=r,this.ttfb_=new fa(e)}update(e,t){const{slow_:n,fast_:r,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new fa(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new fa(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new fa(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const n=8*t,r=e/1e3,s=n/r;this.fast_.sample(r,s),this.slow_.sample(r,s)}sampleTTFB(e){const t=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function L5(i,e,t){return(e=D5(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function at(){return at=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(i[n]=t[n])}return i},at.apply(null,arguments)}function VR(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,n)}return t}function rt(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?VR(Object(t),!0).forEach(function(n){L5(i,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):VR(Object(t)).forEach(function(n){Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n))})}return i}function k5(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function D5(i){var e=k5(i,"string");return typeof e=="symbol"?e:e+""}class on{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const n=`[${e}]:`;this.trace=hs,this.debug=t.debug.bind(null,n),this.log=t.log.bind(null,n),this.warn=t.warn.bind(null,n),this.info=t.info.bind(null,n),this.error=t.error.bind(null,n)}}const hs=function(){},O5={trace:hs,debug:hs,log:hs,warn:hs,info:hs,error:hs};function mv(){return at({},O5)}function M5(i,e){const t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):hs}function GR(i,e,t){return e[i]?e[i].bind(e):M5(i,t)}const vv=mv();function F5(i,e,t){const n=mv();if(typeof console=="object"&&i===!0||typeof i=="object"){const r=["debug","log","info","warn","error"];r.forEach(s=>{n[s]=GR(s,i,t)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.6.13`)}catch{return mv()}r.forEach(s=>{vv[s]=GR(s,i)})}else at(vv,n);return n}const st=vv;function Er(i=!0){return typeof self>"u"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function N5(i){return typeof self<"u"&&i===self.ManagedMediaSource}function WR(i,e){const t=Object.keys(i),n=Object.keys(e),r=t.length,s=n.length;return!r||!s||r===s&&!t.some(o=>n.indexOf(o)===-1)}function Vi(i,e=!1){if(typeof TextDecoder<"u"){const c=new TextDecoder("utf-8").decode(i);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const t=i.length;let n,r,s,o="",a=0;for(;a<t;){if(n=i[a++],n===0&&e)return o;if(n===0||n===3)continue;switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:r=i[a++],o+=String.fromCharCode((n&31)<<6|r&63);break;case 14:r=i[a++],s=i[a++],o+=String.fromCharCode((n&15)<<12|(r&63)<<6|(s&63)<<0);break}}return o}function gi(i){let e="";for(let t=0;t<i.length;t++){let n=i[t].toString(16);n.length<2&&(n="0"+n),e+=n}return e}function jR(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function B5(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var yv={exports:{}},KR;function U5(){return KR||(KR=1,function(i,e){(function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var d=a.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=a.normalizePath(d.path),a.buildURLFromParts(d)}var h=a.parseURL(c);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=a.normalizePath(h.path),a.buildURLFromParts(h)):c;var f=a.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var p=r.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(g.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)g.path=f.path,h.params||(g.params=f.params,h.query||(g.query=f.query));else{var m=f.path,v=m.substring(0,m.lastIndexOf("/")+1)+h.path;g.path=a.normalizePath(v)}return g.path===null&&(g.path=u.alwaysNormalize?a.normalizePath(h.path):h.path),a.buildURLFromParts(g)},parseURL:function(l){var c=n.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(s,"");l.length!==(l=l.replace(o,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};i.exports=a})()}(yv)),yv.exports}var Sv=U5();class Ud{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var dt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class xv{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,$5(this,"stats")}setByteRange(e,t){const n=e.split("@",2);let r;n.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(n[1]),this._byteRange=[r,parseInt(n[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[dt.AUDIO]:null,[dt.VIDEO]:null,[dt.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Ud),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Sv.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[dt.AUDIO]=null,e[dt.VIDEO]=null,e[dt.AUDIOVIDEO]=null}}function Ft(i){return i.sn!=="initSegment"}class $d extends xv{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(pe(e)&&pe(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const n=Object.keys(t);if(n.length===1){const r=this._decryptdata=t[n[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=pe(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const n=Object.keys(this.levelkeys),r=n.length;if(r>1||r===1&&(t=this.levelkeys[n[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!pe(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ft(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var n;const r=t[e];r&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,s,o=!1){const{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:s,partial:o};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,n),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}}class qR extends xv{constructor(e,t,n,r,s){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function YR(i,e){const t=Object.getPrototypeOf(i);if(t){const n=Object.getOwnPropertyDescriptor(t,e);return n||YR(t,e)}}function $5(i,e){const t=YR(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}const XR=Math.pow(2,32)-1,H5=[].push,ZR={video:1,audio:2,id3:3,text:4};function $t(i){return String.fromCharCode.apply(null,i)}function QR(i,e){const t=i[e]<<8|i[e+1];return t<0?65536+t:t}function Me(i,e){const t=eC(i,e);return t<0?4294967296+t:t}function JR(i,e){let t=Me(i,e);return t*=Math.pow(2,32),t+=Me(i,e+4),t}function eC(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function z5(i){const e=i.byteLength;for(let t=0;t<e;){const n=Me(i,t);if(n>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=n>1?t+n:e}return!1}function We(i,e){const t=[];if(!e.length)return t;const n=i.byteLength;for(let r=0;r<n;){const s=Me(i,r),o=$t(i.subarray(r+4,r+8)),a=s>1?r+s:n;if(o===e[0])if(e.length===1)t.push(i.subarray(r+8,a));else{const l=We(i.subarray(r+8,a),e.slice(1));l.length&&H5.apply(t,l)}r=a}return t}function V5(i){const e=[],t=i[0];let n=8;const r=Me(i,n);n+=4;let s=0,o=0;t===0?(s=Me(i,n),o=Me(i,n+4),n+=8):(s=JR(i,n),o=JR(i,n+8),n+=16),n+=2;let a=i.length+o;const l=QR(i,n);n+=2;for(let c=0;c<l;c++){let u=n;const d=Me(i,u);u+=4;const h=d&2147483647;if((d&2147483648)>>>31===1)return st.warn("SIDX has hierarchical references (not supported)"),null;const p=Me(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:p,info:{duration:p/r,start:a,end:a+h-1}}),a+=h,u+=4,n=u}return{earliestPresentationTime:s,timescale:r,version:t,referencesCount:l,references:e}}function tC(i){const e=[],t=We(i,["moov","trak"]);for(let r=0;r<t.length;r++){const s=t[r],o=We(s,["tkhd"])[0];if(o){let a=o[0];const l=Me(o,a===0?12:20),c=We(s,["mdia","mdhd"])[0];if(c){a=c[0];const u=Me(c,a===0?12:20),d=We(s,["mdia","hdlr"])[0];if(d){const h=$t(d.subarray(8,12)),f={soun:dt.AUDIO,vide:dt.VIDEO}[h],p=We(s,["mdia","minf","stbl","stsd"])[0],g=G5(p);f?(e[l]={timescale:u,type:f,stsd:g},e[f]=rt({timescale:u,id:l},g)):e[l]={timescale:u,type:h,stsd:g}}}}}return We(i,["moov","mvex","trex"]).forEach(r=>{const s=Me(r,4),o=e[s];o&&(o.default={duration:Me(r,12),flags:Me(r,20)})}),e}function G5(i){const e=i.subarray(8),t=e.subarray(86),n=$t(e.subarray(4,8));let r=n,s;const o=n==="enca"||n==="encv";if(o){const c=We(e,[n])[0].subarray(n==="enca"?28:78);We(c,["sinf"]).forEach(d=>{const h=We(d,["schm"])[0];if(h){const f=$t(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const p=We(d,["frma"])[0];p&&(r=$t(p))}}})}const a=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=We(t,["avcC"])[0];l&&l.length>3&&(r+="."+zd(l[1])+zd(l[2])+zd(l[3]),s=Hd(a==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const l=We(e,[n])[0],c=We(l.subarray(28),["esds"])[0];if(c&&c.length>7){let u=4;if(c[u++]!==3)break;u=Tv(c,u),u+=2;const d=c[u++];if(d&128&&(u+=2),d&64&&(u+=c[u++]),c[u++]!==4)break;u=Tv(c,u);const h=c[u++];if(h===64)r+="."+zd(h);else break;if(u+=12,c[u++]!==5)break;u=Tv(c,u);const f=c[u++];let p=(f&248)>>3;p===31&&(p+=1+((f&7)<<3)+((c[u]&224)>>5)),r+="."+p}break}case"hvc1":case"hev1":{const l=We(t,["hvcC"])[0];if(l&&l.length>12){const c=l[1],u=["","A","B","C"][c>>6],d=c&31,h=Me(l,2),f=(c&32)>>5?"H":"L",p=l[12],g=l.subarray(6,12);r+="."+u+d,r+="."+W5(h).toString(16).toUpperCase(),r+="."+f+p;let m="";for(let v=g.length;v--;){const y=g[v];(y||m)&&(m="."+y.toString(16).toUpperCase()+m)}r+=m}s=Hd(a=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Hd(r,t)||r;break}case"vp09":{const l=We(t,["vpcC"])[0];if(l&&l.length>6){const c=l[4],u=l[5],d=l[6]>>4&15;r+="."+Gn(c)+"."+Gn(u)+"."+Gn(d)}break}case"av01":{const l=We(t,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,u=l[1]&31,d=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,p=c===2&&h?f?12:10:h?10:8,g=(l[2]&16)>>4,m=(l[2]&8)>>3,v=(l[2]&4)>>2,y=l[2]&3;r+="."+c+"."+Gn(u)+d+"."+Gn(p)+"."+g+"."+m+v+y+"."+Gn(1)+"."+Gn(1)+"."+Gn(1)+"."+0,s=Hd("dav1",t)}break}}return{codec:r,encrypted:o,supplemental:s}}function Hd(i,e){const t=We(e,["dvvC"]),n=t.length?t[0]:We(e,["dvcC"])[0];if(n){const r=n[2]>>1&127,s=n[2]<<5&32|n[3]>>3&31;return i+"."+Gn(r)+"."+Gn(s)}}function W5(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function Tv(i,e){const t=e+5;for(;i[e++]&128&&e<t;);return e}function zd(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Gn(i){return(i<10?"0":"")+i}function j5(i,e){if(!i||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&iC(i,(n,r)=>{const s=n.subarray(8,24);s.some(o=>o!==0)||(st.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${gi(s)} -> ${gi(t)}`),n.set(t,8))})}function K5(i){const e=[];return iC(i,t=>e.push(t.subarray(8,24))),e}function iC(i,e){We(i,["moov","trak"]).forEach(n=>{const r=We(n,["mdia","minf","stbl","stsd"])[0];if(!r)return;const s=r.subarray(8);let o=We(s,["enca"]);const a=o.length>0;a||(o=We(s,["encv"])),o.forEach(l=>{const c=a?l.subarray(28):l.subarray(78);We(c,["sinf"]).forEach(d=>{const h=nC(d);h&&e(h,a)})})})}function nC(i){const e=We(i,["schm"])[0];if(e){const t=$t(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const n=We(i,["schi","tenc"])[0];if(n)return n}}}function q5(i,e,t){const n={},r=We(i,["moof","traf"]);for(let s=0;s<r.length;s++){const o=r[s],a=We(o,["tfhd"])[0],l=Me(a,4),c=e[l];if(!c)continue;n[l]||(n[l]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const u=n[l],d=We(o,["tfdt"])[0];if(d){const S=d[0];let x=Me(d,4);S===1&&(x===XR?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(x*=XR+1,x+=Me(d,8))),pe(x)&&(!pe(u.start)||x<u.start)&&(u.start=x)}const h=c.default,f=Me(a,0)|(h==null?void 0:h.flags);let p=(h==null?void 0:h.duration)||0;f&8&&(f&2?p=Me(a,12):p=Me(a,8));const g=We(o,["trun"]);let m=u.start||0,v=0,y=p;for(let S=0;S<g.length;S++){const x=g[S],E=Me(x,4),C=u.sampleCount;u.sampleCount+=E;const b=x[3]&1,I=x[3]&4,D=x[2]&1,P=x[2]&2,k=x[2]&4,N=x[2]&8;let B=8,K=E;for(b&&(B+=4),I&&E&&(!(x[B+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=C),B+=4,D?(y=Me(x,B),B+=4):y=p,P&&(B+=4),N&&(B+=4),m+=y,v+=y,K--);K--;)D?(y=Me(x,B),B+=4):y=p,P&&(B+=4),k&&(x[B+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(K+1),u.keyFrameStart=m),B+=4),N&&(B+=4),m+=y,v+=y;!v&&p&&(v+=p*E)}u.duration+=v}if(!Object.keys(n).some(s=>n[s].duration)){let s=1/0,o=0;const a=We(i,["sidx"]);for(let l=0;l<a.length;l++){const c=V5(a[l]);if(c!=null&&c.references){s=Math.min(s,c.earliestPresentationTime/c.timescale);const u=c.references.reduce((d,h)=>d+h.info.duration||0,0);o=Math.max(o,u+c.earliestPresentationTime/c.timescale)}}o&&pe(o)&&Object.keys(n).forEach(l=>{n[l].duration||(n[l].duration=o*n[l].timescale-n[l].start)})}return n}function Y5(i){const e={valid:null,remainder:null},t=We(i,["moof"]);if(t.length<2)return e.remainder=i,e;const n=t[t.length-1];return e.valid=i.slice(0,n.byteOffset-8),e.remainder=i.slice(n.byteOffset-8),e}function an(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function rC(i,e){const t=[],n=e.samples,r=e.timescale,s=e.id;let o=!1;return We(n,["moof"]).map(l=>{const c=l.byteOffset-8;We(l,["traf"]).map(d=>{const h=We(d,["tfdt"]).map(f=>{const p=f[0];let g=Me(f,4);return p===1&&(g*=Math.pow(2,32),g+=Me(f,8)),g/r})[0];return h!==void 0&&(i=h),We(d,["tfhd"]).map(f=>{const p=Me(f,4),g=Me(f,0)&16777215,m=(g&1)!==0,v=(g&2)!==0,y=(g&8)!==0;let S=0;const x=(g&16)!==0;let E=0;const C=(g&32)!==0;let b=8;p===s&&(m&&(b+=8),v&&(b+=4),y&&(S=Me(f,b),b+=4),x&&(E=Me(f,b),b+=4),C&&(b+=4),e.type==="video"&&(o=Vd(e.codec)),We(d,["trun"]).map(I=>{const D=I[0],P=Me(I,0)&16777215,k=(P&1)!==0;let N=0;const B=(P&4)!==0,K=(P&256)!==0;let q=0;const H=(P&512)!==0;let X=0;const F=(P&1024)!==0,U=(P&2048)!==0;let j=0;const V=Me(I,4);let Z=8;k&&(N=Me(I,Z),Z+=4),B&&(Z+=4);let Q=N+c;for(let le=0;le<V;le++){if(K?(q=Me(I,Z),Z+=4):q=S,H?(X=Me(I,Z),Z+=4):X=E,F&&(Z+=4),U&&(D===0?j=Me(I,Z):j=eC(I,Z),Z+=4),e.type===dt.VIDEO){let re=0;for(;re<X;){const ye=Me(n,Q);if(Q+=4,X5(o,n[Q])){const de=n.subarray(Q,Q+ye);Ev(de,o?2:1,i+j/r,t)}Q+=ye,re+=ye+4}}i+=q/r}}))})})}),t}function Vd(i){if(!i)return!1;const e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function X5(i,e){if(i){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Ev(i,e,t,n){const r=sC(i);let s=0;s+=e;let o=0,a=0,l=0;for(;s<r.length;){o=0;do{if(s>=r.length)break;l=r[s++],o+=l}while(l===255);a=0;do{if(s>=r.length)break;l=r[s++],a+=l}while(l===255);const c=r.length-s;let u=s;if(a<c)s+=a;else if(a>c){st.error(`Malformed SEI payload. ${a} is too small, only ${c} bytes left to parse.`);break}if(o===4){if(r[u++]===181){const h=QR(r,u);if(u+=2,h===49){const f=Me(r,u);if(u+=4,f===1195456820){const p=r[u++];if(p===3){const g=r[u++],m=31&g,v=64&g,y=v?2+m*3:0,S=new Uint8Array(y);if(v){S[0]=g;for(let x=1;x<y;x++)S[x]=r[u++]}n.push({type:p,payloadType:o,pts:t,bytes:S})}}}}}else if(o===5&&a>16){const d=[];for(let p=0;p<16;p++){const g=r[u++].toString(16);d.push(g.length==1?"0"+g:g),(p===3||p===5||p===7||p===9)&&d.push("-")}const h=a-16,f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=r[u++];n.push({payloadType:o,pts:t,uuid:d.join(""),userData:Vi(f),userDataBytes:f})}}}function sC(i){const e=i.byteLength,t=[];let n=1;for(;n<e-2;)i[n]===0&&i[n+1]===0&&i[n+2]===3?(t.push(n+2),n+=2):n++;if(t.length===0)return i;const r=e-t.length,s=new Uint8Array(r);let o=0;for(n=0;n<r;o++,n++)o===t[0]&&(o++,t.shift()),s[n]=i[o];return s}function Z5(i){const e=i[0];let t="",n="",r=0,s=0,o=0,a=0,l=0,c=0;if(e===0){for(;$t(i.subarray(c,c+1))!=="\0";)t+=$t(i.subarray(c,c+1)),c+=1;for(t+=$t(i.subarray(c,c+1)),c+=1;$t(i.subarray(c,c+1))!=="\0";)n+=$t(i.subarray(c,c+1)),c+=1;n+=$t(i.subarray(c,c+1)),c+=1,r=Me(i,12),s=Me(i,16),a=Me(i,20),l=Me(i,24),c=28}else if(e===1){c+=4,r=Me(i,c),c+=4;const d=Me(i,c);c+=4;const h=Me(i,c);for(c+=4,o=2**32*d+h,C5(o)||(o=Number.MAX_SAFE_INTEGER,st.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=Me(i,c),c+=4,l=Me(i,c),c+=4;$t(i.subarray(c,c+1))!=="\0";)t+=$t(i.subarray(c,c+1)),c+=1;for(t+=$t(i.subarray(c,c+1)),c+=1;$t(i.subarray(c,c+1))!=="\0";)n+=$t(i.subarray(c,c+1)),c+=1;n+=$t(i.subarray(c,c+1)),c+=1}const u=i.subarray(c,i.byteLength);return{schemeIdUri:t,value:n,timeScale:r,presentationTime:o,presentationTimeDelta:s,eventDuration:a,id:l,payload:u}}function Q5(i,...e){const t=e.length;let n=8,r=t;for(;r--;)n+=e[r].byteLength;const s=new Uint8Array(n);for(s[0]=n>>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=n&255,s.set(i,4),r=0,n=8;r<t;r++)s.set(e[r],n),n+=e[r].byteLength;return s}function J5(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let n,r;n=0,r=new Uint8Array;let s;n>0?(s=new Uint8Array(4),e.length>0&&new DataView(s.buffer).setUint32(0,e.length,!1)):s=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),Q5([112,115,115,104],new Uint8Array([n,0,0,0]),i,s,r,o,t)}function eV(i){const e=[];if(i instanceof ArrayBuffer){const t=i.byteLength;let n=0;for(;n+32<t;){const r=new DataView(i,n),s=tV(r);e.push(s),n+=s.size}}return e}function tV(i){const e=i.getUint32(0),t=i.byteOffset,n=i.byteLength;if(n<e)return{offset:t,size:n};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};const s=i.getUint32(8)>>>24;if(s!==0&&s!==1)return{offset:t,size:e};const o=i.buffer,a=gi(new Uint8Array(o,t+12,16));let l=null,c=null,u=0;if(s===0)u=28;else{const h=i.getUint32(28);if(!h||n<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(o,t+32+f*16,16));u=32+h*16}if(!u)return{offset:t,size:e};const d=i.getUint32(u);return e-32<d?{offset:t,size:e}:(c=new Uint8Array(o,t+u+4,d),{version:s,systemId:a,kids:l,data:c,offset:t,size:e})}const oC=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),pa={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function wv(i,e){const t=pa[e];return!!t&&!!t[i.slice(0,4)]}function ec(i,e,t=!0){return!i.split(",").some(n=>!bv(n,e,t))}function bv(i,e,t=!0){var n;const r=Er(t);return(n=r==null?void 0:r.isTypeSupported(tc(i,e)))!=null?n:!1}function tc(i,e){return`${e}/mp4;codecs=${i}`}function aC(i){if(i){const e=i.substring(0,4);return pa.video[e]}return 2}function Gd(i){const e=oC();return i.split(",").reduce((t,n)=>{const s=e&&Vd(n)?9:pa.video[n];return s?(s*2+t)/(t?3:2):(pa.audio[n]+t)/(t?2:1)},0)}const _v={};function iV(i,e=!0){if(_v[i])return _v[i];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var n;if(bv(t[r],"audio",e))return _v[i]=t[r],t[r];if(t[r]==="mp3"&&(n=Er(e))!=null&&n.isTypeSupported("audio/mpeg"))return""}return i}const nV=/flac|opus|mp4a\.40\.34/i;function Wd(i,e=!0){return i.replace(nV,t=>iV(t.toLowerCase(),e))}function rV(i,e){const t=[];if(i){const n=i.split(",");for(let r=0;r<n.length;r++)wv(n[r],"video")||t.push(n[r])}return e&&t.push(e),t.join(",")}function jd(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(lC(i,"audio")||lC(i,"video")))return i;if(e){const t=e.split(",");if(t.length>1){if(i){for(let n=t.length;n--;)if(t[n].substring(0,4)===i.substring(0,4))return t[n]}return t[0]}}return e||i}function lC(i,e){return wv(i,e)&&bv(i,e)}function sV(i){const e=i.split(",");for(let t=0;t<e.length;t++){const n=e[t].split(".");n.length>2&&n[0]==="avc1"&&(e[t]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return e.join(",")}function oV(i){if(i.startsWith("av01.")){const e=i.split("."),t=["0","111","01","01","01","0"];for(let n=e.length;n>4&&n<10;n++)e[n]=t[n-4];return e.join(".")}return i}function cC(i){const e=Er(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Av(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const aV={supported:!0,powerEfficient:!0,smooth:!0},lV={supported:!1,smooth:!1,powerEfficient:!1},uC={supported:!0,configurations:[],decodingInfoResults:[aV]};function dC(i,e){return{supported:!1,configurations:e,decodingInfoResults:[lV],error:i}}function cV(i,e,t,n,r,s){const o=i.videoCodec,a=i.audioCodec?i.audioGroups:null,l=s==null?void 0:s.audioCodec,c=s==null?void 0:s.channels,u=c?parseInt(c):l?1/0:2;let d=null;if(a!=null&&a.length)try{a.length===1&&a[0]?d=e.groups[a[0]].channels:d=a.reduce((h,f)=>{if(f){const p=e.groups[f];if(!p)throw new Error(`Audio track group ${f} not found`);Object.keys(p.channels).forEach(g=>{h[g]=(h[g]||0)+p.channels[g]})}return h},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(h=>Vd(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(n,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!d&&pe(u)&&Object.keys(d).some(h=>parseInt(h)>u)}function hC(i,e,t,n={}){const r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(uC);const s=[],o=uV(i),a=o.length,l=dV(i,e,a>0),c=l.length;for(let u=a||1*c||1;u--;){const d={type:"media-source"};if(a&&(d.video=o[u%a]),c){d.audio=l[u%c];const h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}s.push(d)}if(r){const u=navigator.userAgent;if(r.split(",").some(d=>Vd(d))&&oC())return Promise.resolve(dC(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),s))}return Promise.all(s.map(u=>{const d=fV(u);return n[d]||(n[d]=t.decodingInfo(u))})).then(u=>({supported:!u.some(d=>!d.supported),configurations:s,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:s,decodingInfoResults:[],error:u}))}function uV(i){var e;const t=(e=i.videoCodec)==null?void 0:e.split(","),n=fC(i),r=i.width||640,s=i.height||480,o=i.frameRate||30,a=i.videoRange.toLowerCase();return t?t.map(l=>{const c={contentType:tc(oV(l),"video"),width:r,height:s,bitrate:n,framerate:o};return a!=="sdr"&&(c.transferFunction=a),c}):[]}function dV(i,e,t){var n;const r=(n=i.audioCodec)==null?void 0:n.split(","),s=fC(i);return r&&i.audioGroups?i.audioGroups.reduce((o,a)=>{var l;const c=a?(l=e.groups[a])==null?void 0:l.tracks:null;return c?c.reduce((u,d)=>{if(d.groupId===a){const h=parseFloat(d.channels||"");r.forEach(f=>{const p={contentType:tc(f,"audio"),bitrate:t?hV(f,s):s};h&&(p.channels=""+h),u.push(p)})}return u},o):o},[]):[]}function hV(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function fC(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function fV(i){let e="";const{audio:t,video:n}=i;if(n){const r=Av(n.contentType);e+=`${r}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(t){const r=Av(t.contentType);e+=`${n?"_":""}${r}_c${t.channels}`}return e}const Rv=["NONE","TYPE-0","TYPE-1",null];function pV(i){return Rv.indexOf(i)>-1}const Kd=["SDR","PQ","HLG"];function gV(i){return!!i&&Kd.indexOf(i)>-1}var ic={No:"",Yes:"YES",v2:"v2"};function pC(i){const{canSkipUntil:e,canSkipDateRanges:t,age:n}=i,r=n<e/2;return e&&r?t?ic.v2:ic.Yes:ic.No}class Cv{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class ga{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(n=>!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const n=(t=e.supplemental)==null?void 0:t.videoCodec;n&&n!==e.videoCodec&&(this.codecSet+=`,${n.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return gC(this._audioGroups,e)}hasSubtitleGroup(e){return gC(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(t)===-1&&n.push(t)}else if(e==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(t)===-1&&n.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function gC(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function mV(){if(typeof matchMedia=="function"){const i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function vV(i,e){let t=!1,n=[];if(i&&(t=i!=="SDR",n=[i]),e){n=e.allowedVideoRanges||Kd.slice(0);const r=n.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&mV(),t||(n=["SDR"])}return{preferHDR:t,allowedVideoRanges:n}}const yV=i=>{const e=new WeakSet;return(t,n)=>{if(i&&(n=i(t,n)),typeof n=="object"&&n!==null){if(e.has(n))return;e.add(n)}return n}},ht=(i,e)=>JSON.stringify(i,yV(e));function SV(i,e,t,n,r){const s=Object.keys(i),o=n==null?void 0:n.channels,a=n==null?void 0:n.audioCodec,l=r==null?void 0:r.videoCodec,c=o&&parseInt(o)===2;let u=!1,d=!1,h=1/0,f=1/0,p=1/0,g=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:S}=vV(e,r);for(let I=s.length;I--;){const D=i[s[I]];u||(u=D.channels[2]>0),h=Math.min(h,D.minHeight),f=Math.min(f,D.minFramerate),p=Math.min(p,D.minBitrate),S.filter(k=>D.videoRanges[k]>0).length>0&&(d=!0)}h=pe(h)?h:0,f=pe(f)?f:0;const x=Math.max(1080,h),E=Math.max(30,f);p=pe(p)?p:t,t=Math.max(p,t),d||(e=void 0);const C=s.length>1;return{codecSet:s.reduce((I,D)=>{const P=i[D];if(D===I)return I;if(v=d?S.filter(k=>P.videoRanges[k]>0):[],C){if(P.minBitrate>t)return Wn(D,`min bitrate of ${P.minBitrate} > current estimate of ${t}`),I;if(!P.hasDefaultAudio)return Wn(D,"no renditions with default or auto-select sound found"),I;if(a&&D.indexOf(a.substring(0,4))%5!==0)return Wn(D,`audio codec preference "${a}" not found`),I;if(o&&!c){if(!P.channels[o])return Wn(D,`no renditions with ${o} channel sound found (channels options: ${Object.keys(P.channels)})`),I}else if((!a||c)&&u&&P.channels[2]===0)return Wn(D,"no renditions with stereo sound found"),I;if(P.minHeight>x)return Wn(D,`min resolution of ${P.minHeight} > maximum of ${x}`),I;if(P.minFramerate>E)return Wn(D,`min framerate of ${P.minFramerate} > maximum of ${E}`),I;if(!v.some(k=>P.videoRanges[k]>0))return Wn(D,`no variants with VIDEO-RANGE of ${ht(v)} found`),I;if(l&&D.indexOf(l.substring(0,4))%5!==0)return Wn(D,`video codec preference "${l}" not found`),I;if(P.maxScore<m)return Wn(D,`max score of ${P.maxScore} < selected max of ${m}`),I}return I&&(Gd(D)>=Gd(I)||P.fragmentError>i[I].fragmentError)?I:(g=P.minIndex,m=P.maxScore,D)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:p,minIndex:g}}function Wn(i,e){st.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function mC(i){return i.reduce((e,t)=>{let n=e.groups[t.groupId];n||(n=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(t);const r=t.channels||"2";return n.channels[r]=(n.channels[r]||0)+1,n.hasDefault=n.hasDefault||t.default,n.hasAutoSelect=n.hasAutoSelect||t.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function xV(i,e,t,n){return i.slice(t,n+1).reduce((r,s,o)=>{if(!s.codecSet)return r;const a=s.audioGroups;let l=r[s.codecSet];l||(r[s.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,s.bitrate);const c=Math.min(s.height,s.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,s.frameRate),l.minIndex=Math.min(l.minIndex,o),l.maxScore=Math.max(l.maxScore,s.score),l.fragmentError+=s.fragmentError,l.videoRanges[s.videoRange]=(l.videoRanges[s.videoRange]||0)+1,a&&a.forEach(u=>{if(!u)return;const d=e.groups[u];d&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+d.channels[h]}))}),r},{})}function vC(i){if(!i)return i;const{lang:e,assocLang:t,characteristics:n,channels:r,audioCodec:s}=i;return{lang:e,assocLang:t,characteristics:n,channels:r,audioCodec:s}}function jn(i,e,t){if("attrs"in i){const n=e.indexOf(i);if(n!==-1)return n}for(let n=0;n<e.length;n++){const r=e[n];if(no(i,r,t))return n}return-1}function no(i,e,t){const{groupId:n,name:r,lang:s,assocLang:o,default:a}=i,l=i.forced;return(n===void 0||e.groupId===n)&&(r===void 0||e.name===r)&&(s===void 0||TV(s,e.lang))&&(s===void 0||e.assocLang===o)&&(a===void 0||e.default===a)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||EV(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function TV(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function EV(i,e=""){const t=i.split(","),n=e.split(",");return t.length===n.length&&!t.some(r=>n.indexOf(r)===-1)}function ro(i,e){const{audioCodec:t,channels:n}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(n===void 0||n===(e.channels||"2"))}function wV(i,e,t,n,r){const s=e[n],a=e.reduce((h,f,p)=>{const g=f.uri;return(h[g]||(h[g]=[])).push(p),h},{})[s.uri];a.length>1&&(n=Math.max.apply(Math,a));const l=s.videoRange,c=s.frameRate,u=s.codecSet.substring(0,4),d=yC(e,n,h=>{if(h.videoRange!==l||h.frameRate!==c||h.codecSet.substring(0,4)!==u)return!1;const f=h.audioGroups,p=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return jn(i,p,r)>-1});return d>-1?d:yC(e,n,h=>{const f=h.audioGroups,p=t.filter(g=>!f||f.indexOf(g.groupId)!==-1);return jn(i,p,r)>-1})}function yC(i,e,t){for(let n=e;n>-1;n--)if(t(i[n]))return n;for(let n=e+1;n<i.length;n++)if(t(i[n]))return n;return-1}function qd(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}class SC extends on{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var n;const{fragCurrent:r,partCurrent:s,hls:o}=this,{autoLevelEnabled:a,media:l}=o;if(!r||!l)return;const c=performance.now(),u=s?s.stats:r.stats,d=s?s.duration:r.duration,h=c-u.loading.start,f=o.minAutoLevel,p=r.level,g=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||p<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const m=g>-1&&g!==p,v=!!t||m;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=o.mainForwardBufferInfo;if(!v&&y===null)return;const S=this.bwEstimator.getEstimateTTFB(),x=Math.abs(l.playbackRate);if(h<=Math.max(S,1e3*(d/(x*2))))return;const E=y?y.len/x:0,C=u.loading.first?u.loading.first-u.loading.start:-1,b=u.loaded&&C>-1,I=this.getBwEstimate(),D=o.levels,P=D[p],k=Math.max(u.loaded,Math.round(d*(r.bitrate||P.averageBitrate)/8));let N=b?h-C:h;N<1&&b&&(N=Math.min(h,u.loaded*8/I));const B=b?u.loaded*1e3/N:0,K=S/1e3,q=B?(k-u.loaded)/B:k*8/I+K;if(q<=E)return;const H=B?B*8:I,X=((n=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,F=this.hls.config.abrBandWidthUpFactor;let U=Number.POSITIVE_INFINITY,j;for(j=p-1;j>f;j--){const le=D[j].maxBitrate,re=!D[j].details||X;if(U=this.getTimeToLoadFrag(K,H,d*le,re),U<Math.min(E,d+K))break}if(U>=q||U>d*10)return;b?this.bwEstimator.sample(h-Math.min(S,C),u.loaded):this.bwEstimator.sampleTTFB(h);const V=D[j].maxBitrate;this.getBwEstimate()*F>V&&this.resetEstimator(V);const Z=this.findBestLevel(V,f,j,0,E,1,1);Z>-1&&(j=Z),this.warn(`Fragment ${r.sn}${s?" part "+s.index:""} of level ${p} is loading too slowly;
|
|
199
|
+
Fragment duration: ${r.duration.toFixed(3)}
|
|
200
|
+
Time to underbuffer: ${E.toFixed(3)} s
|
|
201
|
+
Estimated load time for current fragment: ${q.toFixed(3)} s
|
|
202
|
+
Estimated load time for down switch fragment: ${U.toFixed(3)} s
|
|
203
|
+
TTFB estimate: ${C|0} ms
|
|
204
|
+
Current BW estimate: ${pe(I)?I|0:"Unknown"} bps
|
|
205
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
206
|
+
Switching to level ${j} @ ${V|0} bps`),o.nextLoadLevel=o.nextAutoLevel=j,this.clearTimer();const Q=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===j&&j>0){const le=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${j>0?"and switching down":""}
|
|
207
|
+
Fragment duration: ${r.duration.toFixed(3)} s
|
|
208
|
+
Time to underbuffer: ${le.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,j>f){let re=this.findBestLevel(this.hls.levels[f].bitrate,f,j,0,le,1,1);re===-1&&(re=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=re,this.resetEstimator(this.hls.levels[re].bitrate)}}};m||q>U*2?Q():this.timer=self.setInterval(Q,U*1e3),o.trigger(_.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new P5(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(_.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const n=t.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var r;this.fragCurrent=n,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case W.BUFFER_ADD_CODEC_ERROR:case W.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case W.FRAG_LOAD_TIMEOUT:{const n=t.frag,{fragCurrent:r,partCurrent:s}=this;if(n&&r&&n.sn===r.sn&&n.level===r.level){const o=performance.now(),a=s?s.stats:n.stats,l=o-a.loading.start,c=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&c>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,c),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,n,r){const s=e+n/t,o=r?e+this.lastLevelLoadSec:0;return s+o}onLevelLoaded(e,t){const n=this.hls.config,{loading:r}=t.stats,s=r.end-r.first;pe(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:n}){const r=n?n.stats:t.stats;if(t.type===ve.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=n?n.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+r.loaded,l=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(_.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:n,part:r}=t,s=r!=null&&r.stats.loaded?r.stats:n.stats;if(s.aborted||this.ignoreFragment(n))return;const o=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,s.loaded),s.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ve.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,n=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(n,t,e,0,r,1,1);if(s>-1)return s;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=n&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,s)&&o[e].loadError<=o[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:r,config:s,minAutoLevel:o}=n,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(c){const m=this.findBestLevel(l,o,r,c,0,u,d);if(m>=0)return this.rebufferNotice=-1,m}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!c){const m=this.bitrateTestDelay;m&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=d=1)}const f=this.findBestLevel(l,o,r,c,h,u,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const p=n.levels[o],g=n.loadLevelObj;return g&&(p==null?void 0:p.bitrate)<g.bitrate?o:n.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const n=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,n,r,s,o,a){var l;const c=r+s,u=this.lastLoadedFragLevel,d=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:p,allAudioTracks:g,loadLevel:m,config:v}=this.hls;if(p.length===1)return 0;const y=p[d],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),x=m===-1||u===-1;let E,C="SDR",b=(y==null?void 0:y.frameRate)||0;const{audioPreference:I,videoPreference:D}=v,P=this.audioTracksByGroup||(this.audioTracksByGroup=mC(g));let k=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;const H=this.codecTiers||(this.codecTiers=xV(p,P,t,n)),X=SV(H,C,e,I,D),{codecSet:F,videoRanges:U,minFramerate:j,minBitrate:V,minIndex:Z,preferHDR:Q}=X;k=Z,E=F,C=Q?U[U.length-1]:U[0],b=j,e=Math.max(e,V),this.log(`picked start tier ${ht(X)}`)}else E=y==null?void 0:y.codecSet,C=y==null?void 0:y.videoRange;const N=f?f.duration:h?h.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let H=n;H>=t;H--){var q;const X=p[H],F=H>d;if(!X)continue;if(v.useMediaCapabilities&&!X.supportedResult&&!X.supportedPromise){const re=navigator.mediaCapabilities;typeof(re==null?void 0:re.decodingInfo)=="function"&&cV(X,P,C,b,e,I)?(X.supportedPromise=hC(X,P,re,this.supportedCache),X.supportedPromise.then(ye=>{if(!this.hls)return;X.supportedResult=ye;const de=this.hls.levels,Pe=de.indexOf(X);ye.error?this.warn(`MediaCapabilities decodingInfo error: "${ye.error}" for level ${Pe} ${ht(ye)}`):ye.supported?ye.decodingInfoResults.some(qe=>qe.smooth===!1||qe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Pe} not smooth or powerEfficient: ${ht(ye)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Pe} ${ht(ye)}`),Pe>-1&&de.length>1&&(this.log(`Removing unsupported level ${Pe}`),this.hls.removeLevel(Pe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ye=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ye}`)})):X.supportedResult=uC}if((E&&X.codecSet!==E||C&&X.videoRange!==C||F&&b>X.frameRate||!F&&b>0&&b<X.frameRate||(q=X.supportedResult)!=null&&(q=q.decodingInfoResults)!=null&&q.some(re=>re.smooth===!1))&&(!x||H!==k)){K.push(H);continue}const U=X.details,j=(f?U==null?void 0:U.partTarget:U==null?void 0:U.averagetargetduration)||N;let V;F?V=a*e:V=o*e;const Z=N&&r>=N*2&&s===0?X.averageBitrate:X.maxBitrate,Q=this.getTimeToLoadFrag(B,V,Z*j,U===void 0);if(V>=Z&&(H===u||X.loadError===0&&X.fragmentError===0)&&(Q<=B||!pe(Q)||S&&!this.bitrateTestDelay||Q<c)){const re=this.forcedAutoLevel;return H!==m&&(re===-1||re!==m)&&(K.length&&this.trace(`Skipped level(s) ${K.join(",")} of ${n} max with CODECS and VIDEO-RANGE:"${p[K[0]].codecs}" ${p[K[0]].videoRange}; not compatible with "${E}" ${C}`),this.info(`switch candidate:${d}->${H} adjustedbw(${Math.round(V)})-bitrate=${Math.round(V-Z)} ttfb:${B.toFixed(1)} avgDuration:${j.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${Q.toFixed(1)} firstSelection:${x} codecSet:${X.codecSet} videoRange:${X.videoRange} hls.loadLevel:${m}`)),x&&(this.firstSelection=H),H}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),t)}}const xC={search:function(i,e){let t=0,n=i.length-1,r=null,s=null;for(;t<=n;){r=(t+n)/2|0,s=i[r];const o=e(s);if(o>0)t=r+1;else if(o<0)n=r-1;else return s}return null}};function bV(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!pe(e))return null;const n=i[0].programDateTime;if(e<(n||0))return null;const r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let s=0;s<i.length;++s){const o=i[s];if(AV(e,t,o))return o}return null}function so(i,e,t=0,n=0,r=.005){let s=null;if(i){s=e[1+i.sn-e[0].sn]||null;const a=i.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),s&&i.level!==s.level&&s.end<=i.end&&(s=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&((!i||i.level===s.level)&&TC(t,n,s)===0||_V(s,i,Math.min(r,n))))return s;const o=xC.search(e,TC.bind(null,t,n));return o&&(o!==i||!s)?o:s}function _V(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){const n=e.tagList.reduce((r,s)=>(s[0]==="INF"&&(r+=parseFloat(s[1])),r),t);return i.start<=n}return!1}function TC(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const n=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-n<=i?1:t.start-n>i&&t.start?-1:0}function AV(i,e,t){const n=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-n>i}function EC(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let n=i.fragments;const{fragmentHint:r}=i;r&&(n=n.concat(r));let s;return xC.search(n,o=>o.cc<e?1:o.cc>e?-1:(s=o,o.end<=t?1:o.start>t?-1:0)),s||null}return null}function Yd(i){switch(i.details){case W.FRAG_LOAD_TIMEOUT:case W.KEY_LOAD_TIMEOUT:case W.LEVEL_LOAD_TIMEOUT:case W.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function wC(i){return i.details.startsWith("key")}function bC(i){return wC(i)&&!!i.frag&&!i.frag.decryptdata}function _C(i,e){const t=Yd(e);return i.default[`${t?"timeout":"error"}Retry`]}function Iv(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function AC(i){return rt(rt({},i),{errorRetry:null,timeoutRetry:null})}function Xd(i,e,t,n){if(!i)return!1;const r=n==null?void 0:n.code,s=e<i.maxNumRetry&&(RV(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,n,s):s}function RV(i){return Pv(i)||!!i&&(i<400||i>499)}function Pv(i){return i===0&&navigator.onLine===!1}var Wt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ri={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class RC extends on{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(_.ERROR,this.onError,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(_.ERROR,this.onError,this),e.off(_.ERROR,this.onErrorOut,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===ve.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,n=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||n===-1?t.loadLevel:n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;const r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(o=>r.indexOf(o.groupId)>=0).some(o=>{var a;return(a=o.details)==null?void 0:a.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;const r=this.hls,s=t.context;switch(t.details){case W.FRAG_LOAD_ERROR:case W.FRAG_LOAD_TIMEOUT:case W.KEY_LOAD_ERROR:case W.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case W.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=ma();return}case W.FRAG_GAP:case W.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Wt.SendAlternateToPenaltyBox;return}case W.LEVEL_EMPTY_ERROR:case W.LEVEL_PARSING_ERROR:{var o;const l=t.parent===ve.MAIN?t.level:r.loadLevel;t.details===W.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case W.LEVEL_LOAD_ERROR:case W.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case W.AUDIO_TRACK_LOAD_ERROR:case W.AUDIO_TRACK_LOAD_TIMEOUT:case W.SUBTITLE_LOAD_ERROR:case W.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const l=r.loadLevelObj;if(l&&(s.type===Ke.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===Ke.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Wt.SendAlternateToPenaltyBox,t.errorAction.flags=Ri.MoveAllAlternatesMatchingHost;return}}return;case W.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Wt.SendAlternateToPenaltyBox,flags:Ri.MoveAllAlternatesMatchingHDCP};return;case W.KEY_SYSTEM_SESSION_UPDATE_FAILED:case W.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case W.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Wt.SendAlternateToPenaltyBox,flags:Ri.MoveAllAlternatesMatchingKey};return;case W.BUFFER_ADD_CODEC_ERROR:case W.REMUX_ALLOC_ERROR:case W.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:r.loadLevel)}return;case W.INTERNAL_EXCEPTION:case W.BUFFER_APPENDING_ERROR:case W.BUFFER_FULL_ERROR:case W.LEVEL_SWITCH_ERROR:case W.BUFFER_STALLED_ERROR:case W.BUFFER_SEEK_OVER_HOLE:case W.BUFFER_NUDGE_ON_STALL:t.errorAction=ma();return}t.type===we.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ma())}getPlaylistRetryOrSwitchAction(e,t){const n=this.hls,r=_C(n.config.playlistLoadPolicy,e),s=this.playlistError++;if(Xd(r,s,Yd(e),e.response))return{action:Wt.RetryRequest,flags:Ri.None,retryConfig:r,retryCount:s};const a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:s,keyLoadPolicy:o}=t.config,a=_C(wC(e)?o:s,e),l=t.levels.reduce((u,d)=>u+d.fragmentError,0);if(r&&(e.details!==W.FRAG_GAP&&r.fragmentError++,!bC(e)&&Xd(a,l,Yd(e),e.response)))return{action:Wt.RetryRequest,flags:Ri.None,retryConfig:a,retryCount:l};const c=this.getLevelSwitchAction(e,n);return a&&(c.retryConfig=a,c.retryCount=l),c}getLevelSwitchAction(e,t){const n=this.hls;t==null&&(t=n.loadLevel);const r=this.hls.levels[t];if(r){var s,o;const c=e.details;r.loadError++,c===W.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:p}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const g=(s=e.frag)==null?void 0:s.type,v=(g===ve.AUDIO&&c===W.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===W.BUFFER_ADD_CODEC_ERROR||c===W.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:C})=>r.audioCodec!==C),S=e.sourceBufferName==="video"&&(c===W.BUFFER_ADD_CODEC_ERROR||c===W.BUFFER_APPEND_ERROR)&&d.some(({codecSet:C,audioCodec:b})=>r.codecSet!==C&&r.audioCodec===b),{type:x,groupId:E}=(o=e.context)!=null?o:{};for(let C=d.length;C--;){const b=(C+h)%d.length;if(b!==h&&b>=f&&b<=p&&d[b].loadError===0){var a,l;const I=d[b];if(c===W.FRAG_GAP&&g===ve.MAIN&&e.frag){const D=d[b].details;if(D){const P=so(e.frag,D.fragments,e.frag.start);if(P!=null&&P.gap)continue}}else{if(x===Ke.AUDIO_TRACK&&I.hasAudioGroup(E)||x===Ke.SUBTITLE_TRACK&&I.hasSubtitleGroup(E))continue;if(g===ve.AUDIO&&(a=r.audioGroups)!=null&&a.some(D=>I.hasAudioGroup(D))||g===ve.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(D=>I.hasSubtitleGroup(D))||v&&r.audioCodec===I.audioCodec||S&&r.codecSet===I.codecSet||!v&&r.codecSet!==I.codecSet)continue}u=b;break}}if(u>-1&&n.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Wt.SendAlternateToPenaltyBox,flags:Ri.None,nextAutoLevel:u}}return{action:Wt.SendAlternateToPenaltyBox,flags:Ri.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var n;switch((n=t.errorAction)==null?void 0:n.action){case Wt.DoNothing:break;case Wt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==W.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,n=e.errorAction;if(!n)return;const{flags:r}=n,s=n.nextAutoLevel;switch(r){case Ri.None:this.switchLevel(e,s);break;case Ri.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),c=t.levels[l],u=c==null?void 0:c.attrs["HDCP-LEVEL"];if(n.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Rv[Rv.indexOf(u)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ri.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const c=this.hls.levels,u=c.length;for(let h=u;h--;)if(this.variantHasKey(c[h],l)){var o,a;this.log(`Banned key found in level ${h} (${c[h].bitrate}bps) or audio group "${(o=c[h].audioGroups)==null?void 0:o.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${gi(l.keyId||[])}`),c[h].fragmentError++,c[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const d=e.frag;if(this.hls.levels.length<u)n.resolved=!0;else if(d&&d.type!==ve.MAIN){const h=d.decryptdata;h&&!l.matches(h)&&(n.resolved=!0)}}break}}n.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===W.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const n=Av(e.mimeType),r=this.hls.levels;for(let s=r.length;s--;)r[s][`${e.sourceBufferName}Codec`]===n&&(this.log(`Removing level ${s} for ${e.details} ("${n}" not supported)`),this.hls.removeLevel(s))}}}function ma(i){const e={action:Wt.DoNothing,flags:Ri.None};return i&&(e.resolved=!0),e}var Ht={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class CV{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const n=this.activePartLists[t];if(n)for(let r=n.length;r--;){const s=n[r];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,n){const{fragments:r}=this,s=Object.keys(r);for(let o=s.length;o--;){const a=r[s[o]];if((a==null?void 0:a.body.type)===t&&(!n||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,n,r,s){this.timeRanges&&(this.timeRanges[e]=t);const o=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===n&&this.removeFragment(l.body);return}const c=l.range[e];if(c){if(c.time.length===0){this.removeFragment(l.body);return}c.time.some(u=>{const d=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return d&&this.removeFragment(l.body),d})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const n=e.frag,r=va(n),s=this.fragments[r];if(!s||s.buffered&&n.gap)return;const o=!n.relurl;Object.keys(t).forEach(a=>{const l=n.elementaryStreams[a];if(!l)return;const c=t[a],u=o||l.partial===!0;s.range[a]=this.getBufferedTimes(n,e.part,u,c)}),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=n.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Zd(s)||this.removeParts(n.sn-1,n.type)):this.removeFragment(s.body)}removeParts(e,t){const n=this.activePartLists[t];n&&(this.activePartLists[t]=CC(n,r=>r.fragment.sn>=e))}fragBuffered(e,t){const n=va(e);let r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,n,r){const s={time:[],partial:n},o=e.start,a=e.end,l=e.minEndPTS||a,c=e.maxStartPTS||o;for(let u=0;u<r.length;u++){const d=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(c>=d&&l<=h){s.time.push({startPTS:Math.max(o,r.start(u)),endPTS:Math.min(a,r.end(u))});break}else if(o<h&&a>d){const f=Math.max(o,r.start(u)),p=Math.min(a,r.end(u));p>f&&(s.partial=!0,s.time.push({startPTS:f,endPTS:p}))}else if(a<=d)break}return s}getPartialFragment(e){let t=null,n,r,s,o=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&Zd(u)&&(r=u.body.start-a,s=u.body.end+a,e>=r&&e<=s&&(n=Math.min(e-r,s-e),o<=n&&(t=u.body,o=n)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Zd(t))}getState(e){const t=va(e),n=this.fragments[t];return n?n.buffered?Zd(n)?Ht.PARTIAL:Ht.OK:Ht.APPENDING:Ht.NOT_LOADED}isTimeBuffered(e,t,n){let r,s;for(let o=0;o<n.length;o++){if(r=n.start(o)-this.bufferPadding,s=n.end(o)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const n=t.frag,r=t.part?null:t,s=va(n);this.fragments[s]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:n,part:r,timeRanges:s,type:o}=t;if(n.sn==="initSegment")return;const a=n.type;if(r){let c=this.activePartLists[a];c||(this.activePartLists[a]=c=[]),c.push(r)}this.timeRanges=s;const l=s[o];this.detectEvictedFragments(o,l,a,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=va(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;){const s=t[n[r]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,n,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const l=a.body;l.type!==n||r&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=va(e);e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const r=e.sn;this.activePartLists[e.type]=CC(n,s=>s.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(n=>n.clearElementaryStreamInfo())}}function Zd(i){var e,t,n;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(n=i.range.audiovideo)!=null&&n.partial)}function va(i){return`${i.type}_${i.level}_${i.sn}`}function CC(i,e){return i.filter(t=>{const n=e(t);return n||t.clearElementaryStreamInfo(),n})}var fs={cbc:0,ctr:1};class IV{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case fs.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case fs.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function PV(i){const e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}class LV{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),n=new Uint32Array(4);for(let r=0;r<4;r++)n[r]=t.getUint32(r*4);return n}initTable(){const e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],s=n[1],o=n[2],a=n[3],l=this.invSubMix,c=l[0],u=l[1],d=l[2],h=l[3],f=new Uint32Array(256);let p=0,g=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[p]=v,t[v]=p;const y=f[p],S=f[y],x=f[S];let E=f[v]*257^v*16843008;r[p]=E<<24|E>>>8,s[p]=E<<16|E>>>16,o[p]=E<<8|E>>>24,a[p]=E,E=x*16843009^S*65537^y*257^p*16843008,c[v]=E<<24|E>>>8,u[v]=E<<16|E>>>16,d[v]=E<<8|E>>>24,h[v]=E,p?(p=y^f[f[f[x^y]]],g^=f[f[g]]):p=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const o=this.ksRows=(s+6+1)*4;let a,l;const c=this.keySchedule=new Uint32Array(o),u=this.invKeySchedule=new Uint32Array(o),d=this.sBox,h=this.rcon,f=this.invSubMix,p=f[0],g=f[1],m=f[2],v=f[3];let y,S;for(a=0;a<o;a++){if(a<s){y=c[a]=t[a];continue}S=y,a%s===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=h[a/s|0]<<24):s>6&&a%s===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),c[a]=y=(c[a-s]^S)>>>0}for(l=0;l<o;l++)a=o-l,l&3?S=c[a]:S=c[a-4],l<4||a<=4?u[l]=S:u[l]=p[d[S>>>24]]^g[d[S>>>16&255]]^m[d[S>>>8&255]]^v[d[S&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){const r=this.keySize+6,s=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],c=a[1],u=a[2],d=a[3],h=this.uint8ArrayToUint32Array_(n);let f=h[0],p=h[1],g=h[2],m=h[3];const v=new Int32Array(e),y=new Int32Array(v.length);let S,x,E,C,b,I,D,P,k,N,B,K,q,H;const X=this.networkToHostOrderSwap;for(;t<v.length;){for(k=X(v[t]),N=X(v[t+1]),B=X(v[t+2]),K=X(v[t+3]),b=k^s[0],I=K^s[1],D=B^s[2],P=N^s[3],q=4,H=1;H<r;H++)S=l[b>>>24]^c[I>>16&255]^u[D>>8&255]^d[P&255]^s[q],x=l[I>>>24]^c[D>>16&255]^u[P>>8&255]^d[b&255]^s[q+1],E=l[D>>>24]^c[P>>16&255]^u[b>>8&255]^d[I&255]^s[q+2],C=l[P>>>24]^c[b>>16&255]^u[I>>8&255]^d[D&255]^s[q+3],b=S,I=x,D=E,P=C,q=q+4;S=o[b>>>24]<<24^o[I>>16&255]<<16^o[D>>8&255]<<8^o[P&255]^s[q],x=o[I>>>24]<<24^o[D>>16&255]<<16^o[P>>8&255]<<8^o[b&255]^s[q+1],E=o[D>>>24]<<24^o[P>>16&255]<<16^o[b>>8&255]<<8^o[I&255]^s[q+2],C=o[P>>>24]<<24^o[b>>16&255]<<16^o[I>>8&255]<<8^o[D&255]^s[q+3],y[t]=X(S^f),y[t+1]=X(C^p),y[t+2]=X(E^g),y[t+3]=X(x^m),f=k,p=N,g=B,m=K,t=t+4}return y.buffer}}class kV{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){const e=DV(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function DV(i){switch(i){case fs.cbc:return"AES-CBC";case fs.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}const OV=16;class Lv{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const n=self.crypto;n&&(this.subtle=n.subtle||n.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?PV(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,n,r){return this.useSoftware?new Promise((s,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,n,r);const l=this.flush();l?s(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){const{currentIV:s,currentResult:o,remainderData:a}=this;if(r!==fs.cbc||t.byteLength!==16)return st.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=an(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(n=s);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new LV),c.expandKey(t);const u=o;return this.currentResult=c.decrypt(l.buffer,0,n),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new kV(this.subtle,t,r)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new IV(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(st.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const n=e.length-e.length%OV;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&(st.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const IC=Math.pow(2,17);class MV{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const n=e.url;if(!n)return Promise.reject(new wr({type:we.NETWORK_ERROR,details:W.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,o=r.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){l(LC(e));return}else e.gap=!1;const c=this.loader=s?new s(r):new o(r),u=PC(e);e.loader=c;const d=AC(r.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:IC};e.stats=c.stats;const f={onSuccess:(p,g,m,v)=>{this.resetLoader(e,c);let y=p.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:e,part:null,payload:y,networkDetails:v})},onError:(p,g,m,v)=>{this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:rt({url:n,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:m,stats:v}))},onAbort:(p,g,m)=>{this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:p}))},onTimeout:(p,g,m)=>{this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:p}))}};t&&(f.onProgress=(p,g,m,v)=>t({frag:e,part:null,payload:m,networkDetails:v})),c.load(u,h,f)})}loadPart(e,t,n){this.abort();const r=this.config,s=r.fLoader,o=r.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(LC(e,t));return}const c=this.loader=s?new s(r):new o(r),u=PC(e,t);e.loader=c;const d=AC(r.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:IC};t.stats=c.stats,c.load(u,h,{onSuccess:(f,p,g,m)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:m};n(v),a(v)},onError:(f,p,g,m)=>{this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:rt({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:m}))},onAbort:(f,p,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,p,g)=>{this.resetLoader(e,c),l(new wr({type:we.NETWORK_ERROR,details:W.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){const n=e.stats,r=t.stats,s=r.total;if(n.loaded+=r.loaded,s){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(n.loaded/s),l),d=(l-c)*Math.round(n.loaded/c);n.total=n.loaded+d}else n.total=Math.max(n.loaded,n.total);const o=n.loading,a=r.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function PC(i,e=null){const t=e||i,n={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,s=t.byteRangeEndOffset;if(pe(r)&&pe(s)){var o;let a=r,l=s;if(i.sn==="initSegment"&&FV((o=i.decryptdata)==null?void 0:o.method)){const c=s-r;c%16&&(l=s+(16-c%16)),r!==0&&(n.resetIV=!0,a=r-16)}n.rangeStart=a,n.rangeEnd=l}return n}function LC(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),n={type:we.MEDIA_ERROR,details:W.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(n.part=e),(e||i).stats.aborted=!0,new wr(n)}function FV(i){return i==="AES-128"||i==="AES-256"}class wr extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class kC extends on{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Qd{constructor(e,t,n,r=0,s=-1,o=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Jd(),this.buffering={audio:Jd(),video:Jd(),audiovideo:Jd()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=s,this.partial=o}}function Jd(){return{start:0,executeStart:0,executeEnd:0,end:0}}const DC={length:0,start:()=>0,end:()=>0};class Be{static isBuffered(e,t){if(e){const n=Be.getBuffered(e);for(let r=n.length;r--;)if(t>=n.start(r)&&t<=n.end(r))return!0}return!1}static bufferedRanges(e){if(e){const t=Be.getBuffered(e);return Be.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let n=0;n<e.length;n++)t.push({start:e.start(n),end:e.end(n)});return t}static bufferInfo(e,t,n){if(e){const r=Be.bufferedRanges(e);if(r.length)return Be.bufferedInfo(r,t,n)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.length>1&&e.sort((u,d)=>u.start-d.start||d.end-u.end);let r=-1,s=[];if(n)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);const d=s.length;if(d){const h=s[d-1].end;e[u].start-h<n?e[u].end>h&&(s[d-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let o=0,a,l=t,c=t;for(let u=0;u<s.length;u++){const d=s[u].start,h=s[u].end;if(r===-1&&t>=d&&t<=h&&(r=u),t+n>=d&&t<h)l=d,c=h,o=c-t;else if(t+n<d){a=d;break}}return{len:o,start:l||0,end:c||0,nextStart:a,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||DC}catch(t){return st.log("failed to get media.buffered",t),DC}}}const OC=/\{\$([a-zA-Z0-9-_]+)\}/g;function MC(i){return OC.test(i)}function kv(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(OC,n=>{const r=n.substring(2,n.length-1),s=t==null?void 0:t[r];return s===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),n):s})}return e}function FC(i,e,t){let n=i.variableList;n||(i.variableList=n={});let r,s;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(r))s=o.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(o){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else r=e.NAME,s=e.VALUE;r in n?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function NV(i,e,t){const n=e.IMPORT;if(t&&n in t){let r=i.variableList;r||(i.variableList=r={}),r[n]=t[n]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const BV=/^(\d+)x(\d+)$/,NC=/(.+?)=(".*?"|.*?)(?:,|$)/g;class xt{constructor(e,t){typeof e=="string"&&(e=xt.parseAttrList(e,t)),at(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const n=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((r,s)=>(r[s.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=BV.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n;const r={},s='"';for(NC.lastIndex=0;(n=NC.exec(e))!==null;){const o=n[1].trim();let a=n[2];const l=a.indexOf(s)===0&&a.lastIndexOf(s)===a.length-1;let c=!1;if(l)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))a=kv(t,a);else if(!c&&!l)switch(o){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":st.warn(`${e}: attribute ${o} is missing quotes`)}r[o]=a}return r}}const UV="com.apple.hls.interstitial";function $V(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function HV(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class Dv{constructor(e,t,n=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:n,t){const s=t.attr;for(const o in s)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==s[o]){st.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=at(new xt({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);pe(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(st.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(pe(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===UV}get isValid(){return!!this.id&&!this._badValueForSameId&&pe(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const zV=10;class BC{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let n=t.decryptdata;return n||(t.setKeyFormat(e.keyFormat),n=t.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?pe(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||zV}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let n=e.length;n--;)if(e[n].index>t)return e[n].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function eh(i,e){return i.length===e.length?!i.some((t,n)=>t!==e[n]):!1}function UC(i,e){return!i&&!e?!0:!i||!e?!1:eh(i,e)}function ya(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Ov(i){switch(i){case"AES-128":case"AES-256":return fs.cbc;case"AES-256-CTR":return fs.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function Mv(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function Fv(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function VV(i){const e=Fv(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function $C(i){const e=function(n,r,s){const o=n[r];n[r]=n[s],n[s]=o};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function HC(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),r=n[n.length-1].split(",");if(r.length===2){const s=r[0]==="base64",o=r[1];s?(n.splice(-1,1),t=Mv(o)):t=VV(o)}}return t}const th=typeof self<"u"?self:void 0;var Tt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},jt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ih(i){switch(i){case jt.FAIRPLAY:return Tt.FAIRPLAY;case jt.PLAYREADY:return Tt.PLAYREADY;case jt.WIDEVINE:return Tt.WIDEVINE;case jt.CLEARKEY:return Tt.CLEARKEY}}function Nv(i){switch(i){case Tt.FAIRPLAY:return jt.FAIRPLAY;case Tt.PLAYREADY:return jt.PLAYREADY;case Tt.WIDEVINE:return jt.WIDEVINE;case Tt.CLEARKEY:return jt.CLEARKEY}}function nc(i){const{drmSystems:e,widevineLicenseUrl:t}=i,n=e?[Tt.FAIRPLAY,Tt.WIDEVINE,Tt.PLAYREADY,Tt.CLEARKEY].filter(r=>!!e[r]):[];return!n[Tt.WIDEVINE]&&t&&n.push(Tt.WIDEVINE),n}const Bv=function(i){return th!=null&&(i=th.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function GV(i,e,t,n){let r;switch(i){case Tt.FAIRPLAY:r=["cenc","sinf"];break;case Tt.WIDEVINE:case Tt.PLAYREADY:r=["cenc"];break;case Tt.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return WV(r,e,t,n)}function WV(i,e,t,n){return[{initDataTypes:i,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:t.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function jV(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function zC(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),n=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const l=Mv(a).subarray(0,16);return $C(l),l}}return null}let nh={};class ps{static clearKeyUriToKeyIdMap(){nh={}}static setKeyIdForUri(e,t){nh[e]=t}constructor(e,t,n,r=[1],s=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ya(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(jR(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&eh(e.keyFormatVersions,this.keyFormatVersions)&&UC(e.iv,this.iv)&&UC(e.keyId,this.keyId)}isSupported(){if(this.method){if(ya(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case jt.FAIRPLAY:case jt.WIDEVINE:case jt.PLAYREADY:case jt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(ya(this.method)){let s=this.iv;return s||(typeof e!="number"&&(st.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),s=qV(e)),new ps(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const s=nh[this.uri];if(s&&!eh(this.keyId,s)&&ps.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=HC(this.uri);if(n)switch(this.keyFormat){case jt.WIDEVINE:if(this.pssh=n,!this.keyId){const s=eV(n.buffer);if(s.length){var r;const o=s[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=VC(t));break;case jt.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=J5(s,null,n),this.keyId=zC(n);break}default:{let s=n.subarray(0,16);if(s.length!==16){const o=new Uint8Array(16);o.set(s,16-s.length),s=o}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s;s=KV(t),s||(s=VC(t),s||(s=nh[this.uri])),s&&(this.keyId=s,ps.setKeyIdForUri(this.uri,s))}return this}}function KV(i){const e=i==null?void 0:i[jt.WIDEVINE];return e?e.keyId:null}function VC(i){const e=i==null?void 0:i[jt.PLAYREADY];if(e){const t=HC(e.uri);if(t)return zC(t)}return null}function qV(i){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}const GC=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,WC=/#EXT-X-MEDIA:(.*)/g,YV=/^#EXT(?:INF|-X-TARGETDURATION):/m,Uv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),XV=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class bn{static findGroup(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(r.id===t)return r}}static resolve(e,t){return Sv.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return YV.test(e)}static parseMasterPlaylist(e,t){const n=MC(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:n},s=[];if(GC.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let o;for(;(o=GC.exec(e))!=null;)if(o[1]){var a;const c=new xt(o[1],r),u=kv(r,o[2]),d={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:bn.resolve(u,t)},h=c.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),YC(c.CODECS,d);const f=c["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},YC(f,d.supplemental)),(a=d.unknownCodecs)!=null&&a.length||s.push(d),r.levels.push(d)}else if(o[3]){const c=o[3],u=o[4];switch(c){case"SESSION-DATA":{const d=new xt(u,r),h=d["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=d);break}case"SESSION-KEY":{const d=KC(u,t,r);d.encrypted&&d.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(d)):st.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const d=new xt(u,r);FC(r,d,t)}break}case"CONTENT-STEERING":{const d=new xt(u,r);r.contentSteering={uri:bn.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=qC(u);break}}}const l=s.length>0&&s.length<r.levels.length;return r.levels=l?s:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,n){let r;const s={},o=n.levels,a={AUDIO:o.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:o.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(WC.lastIndex=0;(r=WC.exec(e))!==null;){const c=new xt(r[1],n),u=c.TYPE;if(u){const d=a[u],h=s[u]||[];s[u]=h;const f=c.LANGUAGE,p=c["ASSOC-LANGUAGE"],g=c.CHANNELS,m=c.CHARACTERISTICS,v=c["INSTREAM-ID"],y={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?bn.resolve(c.URI,t):""};if(p&&(y.assocLang=p),g&&(y.channels=g),m&&(y.characteristics=m),v&&(y.instreamId=v),d!=null&&d.length){const S=bn.findGroup(d,y.groupId)||d[0];XC(y,S,"audioCodec"),XC(y,S,"textCodec")}h.push(y)}}return s}static parseLevelPlaylist(e,t,n,r,s,o){var a;const l={url:t},c=new BC(t),u=c.fragments,d=[];let h=null,f=0,p=0,g=0,m=0,v=0,y=null,S=new $d(r,l),x,E,C,b=-1,I=!1,D=null,P;if(Uv.lastIndex=0,c.m3u8=e,c.hasVariableRefs=MC(e),((a=Uv.exec(e))==null?void 0:a[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(x=Uv.exec(e))!==null;){I&&(I=!1,S=new $d(r,l),S.playlistOffset=g,S.setStart(g),S.sn=f,S.cc=m,v&&(S.bitrate=v),S.level=n,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),D&&(S.setByteRange(D),D=null)));const K=x[1];if(K){S.duration=parseFloat(K);const q=(" "+x[2]).slice(1);S.title=q||null,S.tagList.push(q?["INF",K,q]:["INF",K])}else if(x[3]){if(pe(S.duration)){S.playlistOffset=g,S.setStart(g),C&&QC(S,C,c),S.sn=f,S.level=n,S.cc=m,u.push(S);const q=(" "+x[3]).slice(1);S.relurl=kv(c,q),$v(S,y,d),y=S,g+=S.duration,f++,p=0,I=!0}}else{if(x=x[0].match(XV),!x){st.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E<x.length&&x[E]===void 0;E++);const q=(" "+x[E]).slice(1),H=(" "+x[E+1]).slice(1),X=x[E+2]?(" "+x[E+2]).slice(1):null;switch(q){case"BYTERANGE":y?S.setByteRange(H,y):S.setByteRange(H);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=H,S.tagList.push(["PROGRAM-DATE-TIME",H]),b===-1&&(b=u.length);break;case"PLAYLIST-TYPE":c.type&&br(c,q,x),c.type=H.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?br(c,q,x):u.length>0&&JC(c,q,x),f=c.startSN=parseInt(H);break;case"SKIP":{c.skippedSegments&&br(c,q,x);const F=new xt(H,c),U=F.decimalInteger("SKIPPED-SEGMENTS");if(pe(U)){c.skippedSegments+=U;for(let V=U;V--;)u.push(null);f+=U}const j=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");j&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(j.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&br(c,q,x),c.targetduration=Math.max(parseInt(H),1);break;case"VERSION":c.version!==null&&br(c,q,x),c.version=parseInt(H);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||br(c,q,x),c.live=!1;break;case"#":(H||X)&&S.tagList.push(X?[H,X]:[H]);break;case"DISCONTINUITY":m++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([q]);break;case"BITRATE":S.tagList.push([q,H]),v=parseInt(H)*1e3,pe(v)?S.bitrate=v:v=0;break;case"DATERANGE":{const F=new xt(H,c),U=new Dv(F,c.dateRanges[F.ID],c.dateRangeTagCount);c.dateRangeTagCount++,U.isValid||c.skippedSegments?c.dateRanges[U.id]=U:st.warn(`Ignoring invalid DATERANGE tag: "${H}"`),S.tagList.push(["EXT-X-DATERANGE",H]);break}case"DEFINE":{{const F=new xt(H,c);"IMPORT"in F?NV(c,F,o):FC(c,F,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?br(c,q,x):u.length>0&&JC(c,q,x),c.startCC=m=parseInt(H);break;case"KEY":{const F=KC(H,t,c);if(F.isSupported()){if(F.method==="NONE"){C=void 0;break}C||(C={});const U=C[F.keyFormat];U!=null&&U.matches(F)||(U&&(C=at({},C)),C[F.keyFormat]=F)}else st.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${H}"`);break}case"START":c.startTimeOffset=qC(H);break;case"MAP":{const F=new xt(H,c);if(S.duration){const U=new $d(r,l);ZC(U,F,n,C),h=U,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime)}else{const U=S.byteRangeEndOffset;if(U){const j=S.byteRangeStartOffset;D=`${U-j}@${j}`}else D=null;ZC(S,F,n,C),h=S,I=!0}h.cc=m;break}case"SERVER-CONTROL":{P&&br(c,q,x),P=new xt(H),c.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),c.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&br(c,q,x);const F=new xt(H);c.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=c.partList;F||(F=c.partList=[]);const U=p>0?F[F.length-1]:void 0,j=p++,V=new xt(H,c),Z=new qR(V,S,l,j,U);F.push(Z),S.duration+=Z.duration;break}case"PRELOAD-HINT":{const F=new xt(H,c);c.preloadHint=F;break}case"RENDITION-REPORT":{const F=new xt(H,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(F);break}default:st.warn(`line parsed but not handled: ${x}`);break}}}y&&!y.relurl?(u.pop(),g-=y.duration,c.partList&&(c.fragmentHint=y)):c.partList&&($v(S,y,d),S.cc=m,c.fragmentHint=S,C&&QC(S,C,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const k=u.length,N=u[0],B=u[k-1];if(g+=c.skippedSegments*c.targetduration,g>0&&k&&B){c.averagetargetduration=g/k;const K=B.sn;c.endSN=K!=="initSegment"?K:0,c.live||(B.endList=!0),b>0&&(QV(u,b),N&&d.unshift(N))}return c.fragmentHint&&(g+=c.fragmentHint.duration),c.totalduration=g,d.length&&c.dateRangeTagCount&&N&&jC(d,c),c.endCC=m,c}}function jC(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){const a=e.fragments[e.fragments.length-1];i.push(a),t++}else return;const n=i[t-1],r=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let a=s.length;a--;){const l=e.dateRanges[s[a]],c=l.startDate.getTime();l.tagAnchor=n.ref;for(let u=t;u--;){var o;if(((o=i[u])==null?void 0:o.sn)<e.startSN)break;const d=ZV(e,c,i,u,r);if(d!==-1){l.tagAnchor=e.fragments[d].ref;break}}}}function ZV(i,e,t,n,r){const s=t[n];if(s){const a=s.programDateTime;if(e>=a||n===0){var o;const l=(((o=t[n+1])==null?void 0:o.start)||r)-s.start;if(e<=a+l*1e3){const c=t[n].sn-i.startSN;if(c<0)return-1;const u=i.fragments;if(u.length>t.length){const h=(t[n+1]||u[u.length-1]).sn-i.startSN;for(let f=h;f>c;f--){const p=u[f].programDateTime;if(e>=p&&e<p+u[f].duration*1e3)return f}}return c}}}return-1}function KC(i,e,t){var n,r;const s=new xt(i,t),o=(n=s.METHOD)!=null?n:"",a=s.URI,l=s.hexadecimalInteger("IV"),c=s.KEYFORMATVERSIONS,u=(r=s.KEYFORMAT)!=null?r:"identity";a&&s.IV&&!l&&st.error(`Invalid IV: ${s.IV}`);const d=a?bn.resolve(a,e):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new ps(o,d,u,h,l,s.KEYID)}function qC(i){const t=new xt(i).decimalFloatingPoint("TIME-OFFSET");return pe(t)?t:null}function YC(i,e){let t=(i||"").split(/[ ,]+/).filter(n=>n);["video","audio","text"].forEach(n=>{const r=t.filter(s=>wv(s,n));r.length&&(e[`${n}Codec`]=r.map(s=>s.split("/")[0]).join(","),t=t.filter(s=>r.indexOf(s)===-1))}),e.unknownCodecs=t}function XC(i,e,t){const n=e[t];n&&(i[t]=n)}function QV(i,e){let t=i[e];for(let n=e;n--;){const r=i[n];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function $v(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function ZC(i,e,t,n){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",n&&(i.levelkeys=n),i.initSegment=null}function QC(i,e,t){i.levelkeys=e;const{encryptedFragments:n}=t;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&n.push(i)}function br(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function JC(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Hv(i,e){const t=e.startPTS;if(pe(t)){let n=0,r;e.sn>i.sn?(n=t-i.start,r=i):(n=i.start-t,r=e),r.duration!==n&&r.setDuration(n)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function eI(i,e,t,n,r,s,o){n-t<=0&&(o.warn("Fragment should have a positive duration",e),n=t+e.duration,s=r+e.duration);let l=t,c=n;const u=e.startPTS,d=e.endPTS;if(pe(u)){const v=Math.abs(u-t);i&&v>i.totalduration?o.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):pe(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,u),t=Math.min(t,u),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,c=Math.min(n,d),n=Math.max(n,d),s=e.endDTS!==void 0?Math.max(s,e.endDTS):s}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(n-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=n,e.minEndPTS=c,e.endDTS=s;const f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let p;const g=f-i.startSN,m=i.fragments;for(m[g]=e,p=g;p>0;p--)Hv(m[p],m[p-1]);for(p=g;p<m.length-1;p++)Hv(m[p],m[p+1]);return i.fragmentHint&&Hv(m[m.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function JV(i,e,t){if(i===e)return;let n=null;const r=i.fragments;for(let u=r.length-1;u>=0;u--){const d=r[u].initSegment;if(d){n=d;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let s;iG(i,e,(u,d,h,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==u.cc){const p=u.cc-d.cc;for(let g=h;g<f.length;g++)f[g].cc+=p;e.endCC=f[f.length-1].cc}pe(u.startPTS)&&pe(u.endPTS)&&(d.setStart(d.startPTS=u.startPTS),d.startDTS=u.startDTS,d.maxStartPTS=u.maxStartPTS,d.endPTS=u.endPTS,d.endDTS=u.endDTS,d.minEndPTS=u.minEndPTS,d.setDuration(u.endPTS-u.startPTS),d.duration&&(s=d),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(d.elementaryStreams=u.elementaryStreams),d.loader=u.loader,u.hasStats&&(d.stats=u.stats),u.initSegment&&(d.initSegment=u.initSegment,n=u.initSegment)});const o=e.fragments,a=e.fragmentHint?o.concat(e.fragmentHint):o;if(n&&a.forEach(u=>{var d;u&&(!u.initSegment||u.initSegment.relurl===((d=n)==null?void 0:d.relurl))&&(u.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=eG(i.dateRanges,e,t));const u=i.fragments.filter(d=>d.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<a.length;d++)a[d].programDateTime===null&&$v(a[d],a[d-1],u);jC(u,e)}e.endCC=o[o.length-1].cc}if(!e.startCC){var l;const u=rI(i,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:o[0].cc}tG(i.partList,e.partList,(u,d)=>{d.elementaryStreams=u.elementaryStreams,d.stats=u.stats}),s?eI(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,t):iI(i,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const u=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=u),e.driftEndTime=c,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function eG(i,e,t){const{dateRanges:n,recentlyRemovedDateranges:r}=e,s=at({},i);r&&r.forEach(l=>{delete s[l]});const a=Object.keys(s).length;return a?(Object.keys(n).forEach(l=>{const c=s[l],u=new Dv(n[l].attr,c);u.isValid?(s[l]=u,c||(u.tagOrder+=a)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ht(n[l].attr)}"`)}),s):n}function tG(i,e,t){if(i&&e){let n=0;for(let r=0,s=i.length;r<=s;r++){const o=i[r],a=e[r+n];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):n--}}}function iG(i,e,t){const n=e.skippedSegments,r=Math.max(i.startSN,e.startSN)-e.startSN,s=(i.fragmentHint?1:0)+(n?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,o=e.startSN-i.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let c=r;c<=s;c++){const u=l[o+c];let d=a[c];if(n&&!d&&u&&(d=e.fragments[c]=u),u&&d){t(u,d,c,a);const h=u.relurl,f=d.relurl;if(h&&nG(h,f)){e.playlistParsingError=tI(`media sequence mismatch ${d.sn}:`,i,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=tI(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,i,e,u,d);return}}}}function tI(i,e,t,n,r){return new Error(`${i} ${r.url}
|
|
209
|
+
Playlist starting @${e.startSN}
|
|
210
|
+
${e.m3u8}
|
|
211
|
+
|
|
212
|
+
Playlist starting @${t.startSN}
|
|
213
|
+
${t.m3u8}`)}function iI(i,e,t=!0){const n=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,s=n>=0;let o=0;if(s&&n<r.length)o=r[n].start;else if(s&&e.startSN===i.endSN+1)o=i.fragmentEnd;else if(s&&t)o=i.fragmentStart+n*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=i.fragmentStart;else return;zv(e,o)}function zv(i,e){if(e){const t=i.fragments;for(let n=i.skippedSegments;n<t.length;n++)t[n].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function nI(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const n=i.fragments;if(n.length&&t*4>e){const s=n[n.length-1].duration*1e3;s<t&&(t=s)}}else t/=2;return Math.round(t)}function rI(i,e,t){if(!i)return null;let n=i.fragments[e-i.startSN];return n||(n=i.fragmentHint,n&&n.sn===e)?n:e<i.startSN&&t&&t.sn===e?t:null}function sI(i,e,t){return i?oI(i.partList,e,t):null}function oI(i,e,t){if(i)for(let n=i.length;n--;){const r=i[n];if(r.index===t&&r.fragment.sn===e)return r}return null}function aI(i){i.forEach((e,t)=>{var n;(n=e.details)==null||n.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function nG(i,e){return i!==e&&e?lI(i)!==lI(e):!1}function lI(i){return i.replace(/\?[^?]*$/,"")}function rc(i,e){for(let n=0,r=i.length;n<r;n++){var t;if(((t=i[n])==null?void 0:t.cc)===e)return i[n]}return null}function rG(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function cI(i,e){const t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function uI(i,e){const t=e.fragments;for(let n=0,r=t.length;n<r;n++)cI(t[n],i);e.fragmentHint&&cI(e.fragmentHint,i),e.alignedSliding=!0}function sG(i,e){i&&(dI(e,i),e.alignedSliding||rh(e,i),!e.alignedSliding&&!e.skippedSegments&&iI(i,e,!1))}function dI(i,e){if(!rG(e,i))return;const t=Math.min(e.endCC,i.endCC),n=rc(e.fragments,t),r=rc(i.fragments,t);if(!n||!r)return;st.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const s=n.start-r.start;uI(s,i)}function rh(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,n=e.fragments;if(!t.length||!n.length)return;let r,s;const o=Math.min(e.endCC,i.endCC);e.startCC<o&&i.startCC<o&&(r=rc(n,o),s=rc(t,o)),(!r||!s)&&(r=n[Math.floor(n.length/2)],s=rc(t,r.cc)||t[Math.floor(t.length/2)]);const a=r.programDateTime,l=s.programDateTime;if(!a||!l)return;const c=(l-a)/1e3-(s.start-r.start);uI(c,i)}function mi(i,e,t){Ci(i,e,t),i.addEventListener(e,t)}function Ci(i,e,t){i.removeEventListener(e,t)}const oG={toString:function(i){let e="";const t=i.length;for(let n=0;n<t;n++)e+=`[${i.start(n).toFixed(3)}-${i.end(n).toFixed(3)}]`;return e}},J={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class sh extends kC{constructor(e,t,n,r,s){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=J.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:o,fragCurrent:a,media:l,mediaBuffer:c,state:u}=this,d=l?l.currentTime:0,h=Be.bufferInfo(c||l,d,o.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${pe(d)?d.toFixed(3):d}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===J.ENDED)this.resetLoadingState();else if(a){const p=o.maxFragLookUpTolerance,g=a.start-p,m=a.start+a.duration+p;if(f||m<h.start||g>h.end){const v=d>m;(d<g||v)&&(v&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(d>p&&(this.lastCurrentTime=d),!this.loadingParts){const g=Math.max(h.end,d),m=this.shouldLoadParts(this.getLevelDetails(),g);m&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${g.toFixed(2)}`),this.loadingParts=m)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===J.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new MV(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Lv(e.config)}registerListeners(){const{hls:e}=this;e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===J.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=J.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;const s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=Be.bufferedInfo(s,e.start,0));const o=e.nextStart;if(o&&o>r&&o<t.edge||this.media.currentTime<e.start)return!1;const l=t.partList;if(l!=null&&l.length){const u=l[l.length-1];return Be.isBuffered(this.media,u.start+u.duration/2)}const c=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const n=this.media=this.mediaBuffer=t.media;mi(n,"seeking",this.onMediaSeeking),mi(n,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===J.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const n=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ci(r,"seeking",this.onMediaSeeking),Ci(r,"ended",this.onMediaEnded),this.keyLoader&&!n&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=J.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){const r=s=>{const o=s.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(o,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,n,r).then(s=>{if(!s)return;const o=this.state,a=s.frag;if(this.fragContextChanged(a)){(o===J.FRAG_LOADING||!this.fragCurrent&&o===J.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=J.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(_.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===J.STOPPED||this.state===J.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:n}=this;if(n.getState(e)===Ht.APPENDING){const s=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&n.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===Ht.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,n=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:n};this.hls.trigger(_.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(n=>{const r=n==null?void 0:n.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:r}=this,{frag:s,payload:o}=n,a=s.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&ya(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,Ov(a.method)).catch(c=>{throw r.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:s}),c}).then(c=>{const u=self.performance.now();return r.trigger(_.FRAG_DECRYPTED,{frag:s,payload:c,stats:{tstart:l,tdecrypt:u}}),n.payload=c,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===J.STOPPED||this.state===J.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const n=e.frag.stats;this.state!==J.STOPPED&&(this.state=J.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var n,r;const s=e.tracks;if(s&&!t.encrypted&&((n=s.audio)!=null&&n.encrypted||(r=s.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(a.message),!o||o.mediaKeys?!1:(this.hls.trigger(_.ERROR,{type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${n?oG.toString(Be.getBuffered(n)):"(detached)"})`),Ft(e)){var r;if(e.type!==ve.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=J.IDLE;return}}const s=(r=this.levels)==null?void 0:r[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=J.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:n,part:r,partsLoaded:s}=e,o=!s||s.length===0||s.some(l=>!l),a=new Qd(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var s;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=J.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(_.KEY_LOADED,h),this.state===J.KEY_LOADING&&(this.state=J.IDLE),h}),this.hls.trigger(_.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(Ft(e)&&(!l||e.sn!==l.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=h)}if(n=Math.max(e.start,n||0),this.loadingParts&&Ft(e)){const h=o.partList;if(h&&r){n>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const f=this.getNextPart(h,e,n);if(f>-1){const p=h[f];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=J.FRAG_LOADING;let g;return a?g=a.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,p,t,r)).catch(m=>this.handleFragLoadError(m)):g=this.doFragPartsLoad(e,p,t,r).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(_.FRAG_LOADING,{frag:e,part:p,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!e.url||this.loadedEndOfParts(h,n))return Promise.resolve(null)}}if(Ft(e)&&this.loadingParts){var c;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(c=o.partList)==null?void 0:c.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),pe(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=J.FRAG_LOADING;const u=this.config.progressive;let d;return u&&a?d=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,u?r:void 0),a]).then(([h])=>(!u&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(_.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,n,r){return new Promise((s,o)=>{var a;const l=[],c=(a=n.details)==null?void 0:a.partList,u=d=>{this.fragmentLoader.loadPart(e,d,r).then(h=>{l[d.index]=h;const f=h.part;this.hls.trigger(_.FRAG_LOADED,h);const p=sI(n.details,e.sn,d.index+1)||oI(c,e.sn,d.index+1);if(p)u(p);else return s({frag:e,part:f,partsLoaded:l})}).catch(o)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===W.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===we.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(_.ERROR,t)}else this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==J.PARSING){!this.fragCurrent&&this.state!==J.STOPPED&&this.state!==J.ERROR&&(this.state=J.IDLE);return}const{frag:n,part:r,level:s}=t,o=self.performance.now();n.stats.parsing.end=o,r&&(r.stats.parsing.end=o);const a=this.getLevelDetails(),c=a&&n.sn>a.endSN||this.shouldLoadParts(a,n.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=c),this.updateLevelTiming(n,r,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var n;const s=e.partList[0];if(s.fragment.type===ve.SUBTITLE)return!1;const o=s.end+(((n=e.fragmentHint)==null?void 0:n.duration)||0);if(t>=o){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:n}=this,{level:r,sn:s,part:o}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=t[r],l=a.details,c=o>-1?sI(l,s,o):null,u=c?c.fragment:rI(l,s,n);return u?(n&&n!==u&&(u.stats=n.stats),{frag:u,part:c,level:a}):null}bufferFragmentData(e,t,n,r,s){if(this.state!==J.PARSING)return;const{data1:o,data2:a}=e;let l=o;if(a&&(l=an(o,a)),!l.length)return;const c=this.initPTS[t.cc],u=c?-c.baseTime/c.timescale:void 0,d={type:e.type,frag:t,part:n,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(_.BUFFER_APPENDING,d),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Be.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const n=t.currentTime,r=Be.bufferInfo(t,n,0),s=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-o,r.end-o),n+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var n;const r=this.getLoadPosition();if(!pe(r))return null;const o=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,o)}getFwdBufferInfoAtPos(e,t,n,r){const s=Be.bufferInfo(e,t,r);if(s.len===0&&s.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,n);if(o&&(s.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(s.nextStart,o.end)-t,r);return Be.bufferInfo(e,t,a)}}return s}getMaxBufferLength(e){const{config:t}=this;let n;return e?n=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):n=t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t),s=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return s>=r?(n.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=ve.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(e,t){const n=t.fragments,r=n.length;if(!r)return null;const{config:s}=this,o=n[0].start,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const d=s.initialLiveManifestSize;if(r<d)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var c;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const h=this.hls.startPosition,f=this.hls.liveSyncPosition,p=l?(h!==-1&&h>=o?h:f)||l.start:e;this.log(`Setting startPosition to ${p} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(c=l)==null?void 0:c.start}`),this.startPosition=this.nextLoadPosition=p}}else e<=o&&(l=n[0]);if(!l){const d=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,d,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){const d=l.sn-t.startSN;u=this.filterReplacedPrimary(n[d+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const n=this.fragmentTracker.getState(e);return(n===Ht.OK||n===Ht.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,s){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&n.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r,0);if(a!==null&&n.len+a.len>=s){const l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(hI(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(hI(this.config)&&e.type!==ve.SUBTITLE){const n=this.hls.interstitialsManager,r=n==null?void 0:n.bufferingItem;if(r){const o=r.event;if(o){if(o.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&(t==null?void 0:t.live)===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}const s=n==null?void 0:n.playerQueue;if(s)for(let o=s.length;o--;){const a=s[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,n){let r=-1,s=!1,o=!0;for(let a=0,l=e.length;a<l;a++){const c=e[a];if(o=o&&!c.independent,r>-1&&n<c.start)break;const u=c.loaded;u?r=-1:(s||(c.independent||o)&&c.fragment===t)&&(c.fragment!==t&&this.warn(`Need buffer at ${n} but next unloaded part starts at ${c.start}`),r=a),s=u}return r}loadedEndOfParts(e,t){let n;for(let r=e.length;r--;){if(n=e[r],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,n=this.fragPrevious;let r=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),r=bV(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const s=n.sn+1;if(s>=e.startSN&&s<=e.endSN){const o=t[s-e.startSN];n.cc===o.cc&&(r=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=EC(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(r=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){const{config:r}=this;let{fragPrevious:s}=this,{fragments:o,endSN:a}=n;const{fragmentHint:l}=n,{maxFragLookUpTolerance:c}=r,u=n.partList,d=!!(this.loadingParts&&u!=null&&u.length&&l);d&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var f;const g=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;h=so(s,o,e,g)}else h=o[o.length-1];if(h){const p=h.sn-n.startSN,g=this.fragmentTracker.getState(h);if((g===Ht.OK||g===Ht.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!d||u[0].fragment.sn>h.sn||!n.live)&&h.level===s.level){const v=o[p+1];h.sn<a&&this.fragmentTracker.getState(v)!==Ht.OK?h=v:h=null}}return h}alignPlaylists(e,t,n){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,o=!t,a=e.alignedSliding&&pe(s);if(o||!a&&!s){sG(n,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n<t&&(n=-1);const r=this.timelineOffset;if(n===-1){const s=this.startTimeOffset!==null,o=s?this.startTimeOffset:e.startTimeOffset;o!==null&&pe(o)?(n=t+o,o<0&&(n+=e.edge),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${o} found in ${s?"multivariant":"media"} playlist`),this.startPosition=n):e.live?(n=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${n}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=n=0),this.lastCurrentTime=n+r}this.nextLoadPosition=n+r}getLoadPosition(){var e;const{media:t}=this;let n=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?n=t.currentTime:this.nextLoadPosition>=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ft(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==J.FRAG_LOADING_WAITING_RETRY)&&(this.state=J.IDLE)}onFragmentOrKeyLoadError(e,t){var n;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var s;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const o=t.details===W.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(r,!0);const a=t.errorAction;if(!a){this.state=J.ERROR;return}const{action:l,flags:c,retryCount:u=0,retryConfig:d}=a,h=!!d,f=h&&l===Wt.RetryRequest,p=h&&!a.resolved&&c===Ri.MoveAllAlternatesMatchingHost,g=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!f&&p&&Ft(r)&&!r.endList&&g&&!bC(t))this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=!0;else if((f||p)&&u<d.maxNumRetry){var m;const v=Pv((m=t.response)==null?void 0:m.code),y=Iv(d,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=J.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${u+1}/${d.maxNumRetry} in ${y}ms`)}else if(d)if(this.resetFragmentErrors(e),u<d.maxNumRetry)!o&&l!==Wt.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===Wt.SendAlternateToPenaltyBox?this.state=J.WAITING_LEVEL:this.state=J.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,n=t===1/0;(!t||e>=t||n&&!Pv(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=J.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===J.PARSING||this.state===J.PARSED){const t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);const o=!s;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===ve.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==J.STOPPED&&(this.state=J.IDLE)}afterBufferFlushed(e,t,n){if(!e)return;const r=Be.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===J.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==J.STOPPED&&(this.state=J.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){const s=n.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const d=u.endPTS-u.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${d})`),l||!1;const h=r?0:eI(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(_.LEVEL_PTS_UPDATED,{details:s,level:n,drift:h,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var a;if(n.fragmentError===0&&this.treatAsGap(e,n),((a=this.transmuxer)==null?void 0:a.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=J.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(_.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===ve.MAIN?"level":"track"}fragInfo(e,t=!0,n){var r,s;return`${this.playlistLabel()} ${e.level} (${n?"part":"frag"}:[${((r=t&&!n?e.startPTS:(n||e).start)!=null?r:NaN).toFixed(3)}-${((s=t&&!n?e.endPTS:(n||e).end)!=null?s:NaN).toFixed(3)}]${n&&e.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function hI(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class fI{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let n;if(e.length)e.length===1?n=e[0]:n=aG(e,t);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function aG(i,e){const t=new Uint8Array(e);let n=0;for(let r=0;r<i.length;r++){const s=i[r];t.set(s,n),n+=s.length}return t}var Vv={exports:{}},pI;function lG(){return pI||(pI=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function r(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,d||l,h),p=t?t+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=t?t+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},a.prototype.listenerCount=function(c){var u=t?t+c:c,d=this._events[u];return d?d.fn?1:d.length:0},a.prototype.emit=function(c,u,d,h,f,p){var g=t?t+c:c;if(!this._events[g])return!1;var m=this._events[g],v=arguments.length,y,S;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,d),!0;case 4:return m.fn.call(m.context,u,d,h),!0;case 5:return m.fn.call(m.context,u,d,h,f),!0;case 6:return m.fn.call(m.context,u,d,h,f,p),!0}for(S=1,y=new Array(v-1);S<v;S++)y[S-1]=arguments[S];m.fn.apply(m.context,y)}else{var x=m.length,E;for(S=0;S<x;S++)switch(m[S].once&&this.removeListener(c,m[S].fn,void 0,!0),v){case 1:m[S].fn.call(m[S].context);break;case 2:m[S].fn.call(m[S].context,u);break;case 3:m[S].fn.call(m[S].context,u,d);break;case 4:m[S].fn.call(m[S].context,u,d,h);break;default:if(!y)for(E=1,y=new Array(v-1);E<v;E++)y[E-1]=arguments[E];m[S].fn.apply(m[S].context,y)}}return!0},a.prototype.on=function(c,u,d){return s(this,c,u,d,!1)},a.prototype.once=function(c,u,d){return s(this,c,u,d,!0)},a.prototype.removeListener=function(c,u,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===u&&(!h||p.once)&&(!d||p.context===d)&&o(this,f);else{for(var g=0,m=[],v=p.length;g<v;g++)(p[g].fn!==u||h&&!p[g].once||d&&p[g].context!==d)&&m.push(p[g]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&o(this,u)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a}(Vv)),Vv.exports}var cG=lG(),Gv=B5(cG);const sc="1.6.13",Sa={};function uG(){return typeof __HLS_WORKER_BUNDLE__=="function"}function dG(){const i=Sa[sc];if(i)return i.clientCount++,i;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return Sa[sc]=r,r}function hG(i){const e=Sa[i];if(e)return e.clientCount++,e;const t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Sa[i]=r,r}function fG(i){const e=Sa[i||sc];if(e&&e.clientCount--===1){const{worker:n,objectURL:r}=e;delete Sa[i||sc],r&&self.URL.revokeObjectURL(r),n.terminate()}}function gI(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Wv(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function oh(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function oc(i,e){const t=e;let n=0;for(;Wv(i,e);){n+=10;const r=oh(i,e+6);n+=r,gI(i,e+10)&&(n+=10),e+=n}if(n>0)return i.subarray(t,t+n)}function pG(i,e,t,n){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[t+2],o=s>>2&15;if(o>12){const f=new Error(`invalid ADTS sampling index:${o}`);i.emit(_.ERROR,_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const a=(s>>6&3)+1,l=e[t+3]>>6&3|(s&1)<<2,c="mp4a.40."+a,u=r[o];let d=o;(a===5||a===29)&&(d-=3);const h=[a<<3|(d&14)>>1,(d&1)<<7|l<<3];return st.log(`manifest codec:${n}, parsed codec:${c}, channels:${l}, rate:${u} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:u,channelCount:l,codec:c,parsedCodec:c,manifestCodec:n}}function mI(i,e){return i[e]===255&&(i[e+1]&246)===240}function vI(i,e){return i[e+1]&1?7:9}function jv(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function gG(i,e){return e+5<i.length}function ah(i,e){return e+1<i.length&&mI(i,e)}function mG(i,e){return gG(i,e)&&mI(i,e)&&jv(i,e)<=i.length-e}function vG(i,e){if(ah(i,e)){const t=vI(i,e);if(e+t>=i.length)return!1;const n=jv(i,e);if(n<=t)return!1;const r=e+n;return r===i.length||ah(i,r)}return!1}function yI(i,e,t,n,r){if(!i.samplerate){const s=pG(e,t,n,r);if(!s)return;at(i,s)}}function SI(i){return 1024*9e4/i}function yG(i,e){const t=vI(i,e);if(e+t<=i.length){const n=jv(i,e)-t;if(n>0)return{headerLength:t,frameLength:n}}}function xI(i,e,t,n,r){const s=SI(i.samplerate),o=n+r*s,a=yG(e,t);let l;if(a){const{frameLength:d,headerLength:h}=a,f=h+d,p=Math.max(0,t+f-e.length);p?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);const g={unit:l,pts:o};return p||i.samples.push(g),{sample:g,length:f,missing:p}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:c,missing:-1}}function SG(i,e){return Wv(i,e)&&oh(i,e+6)+10<=i.length-e}function xG(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function Kv(i,e=0,t=1/0){return TG(i,e,t,Uint8Array)}function TG(i,e,t,n){const r=EG(i);let s=1;"BYTES_PER_ELEMENT"in n&&(s=n.BYTES_PER_ELEMENT);const o=wG(i)?i.byteOffset:0,a=(o+i.byteLength)/s,l=(o+e)/s,c=Math.floor(Math.max(0,Math.min(l,a))),u=Math.floor(Math.min(c+Math.max(t,0),a));return new n(r,c,u-c)}function EG(i){return i instanceof ArrayBuffer?i:i.buffer}function wG(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function bG(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const n=i.data.subarray(1).indexOf(0);if(n===-1)return;const r=Vi(Kv(i.data,1,n)),s=i.data[2+n],o=i.data.subarray(3+n).indexOf(0);if(o===-1)return;const a=Vi(Kv(i.data,3+n,o));let l;return r==="-->"?l=Vi(Kv(i.data,4+n+o)):l=xG(i.data.subarray(4+n+o)),e.mimeType=r,e.pictureType=s,e.description=a,e.data=l,e}function _G(i){if(i.size<2)return;const e=Vi(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function AG(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1;const n=Vi(i.data.subarray(t),!0);t+=n.length+1;const r=Vi(i.data.subarray(t));return{key:i.type,info:n,data:r}}const e=Vi(i.data.subarray(1));return{key:i.type,info:"",data:e}}function RG(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1;const n=Vi(i.data.subarray(t),!0);t+=n.length+1;const r=Vi(i.data.subarray(t));return{key:i.type,info:n,data:r}}const e=Vi(i.data);return{key:i.type,info:"",data:e}}function CG(i){return i.type==="PRIV"?_G(i):i.type[0]==="W"?RG(i):i.type==="APIC"?bG(i):AG(i)}function IG(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=oh(i,4),n=10;return{type:e,size:t,data:i.subarray(n,n+t)}}const lh=10,PG=10;function TI(i){let e=0;const t=[];for(;Wv(i,e);){const n=oh(i,e+6);i[e+5]>>6&1&&(e+=lh),e+=lh;const r=e+n;for(;e+PG<r;){const s=IG(i.subarray(e)),o=CG(s);o&&t.push(o),e+=s.size+lh}gI(i,e)&&(e+=lh)}return t}function EI(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function LG(i){if(i.data.byteLength===8){const e=new Uint8Array(i.data),t=e[3]&1;let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,t&&(n+=4772185884e-2),Math.round(n)}}function qv(i){const e=TI(i);for(let t=0;t<e.length;t++){const n=e[t];if(EI(n))return LG(n)}}let Ii=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function Kn(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Yv{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&(e=an(this.cachedData,e),this.cachedData=null);let n=oc(e,0),r=n?n.length:0,s;const o=this._audioTrack,a=this._id3Track,l=n?qv(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&pe(l))&&(this.basePTS=kG(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Ii.audioId3,duration:Number.POSITIVE_INFINITY});r<c;){if(this.canParse(e,r)){const u=this.appendFrame(o,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,s=r):r=c}else SG(e,r)?(n=oc(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Ii.audioId3,duration:Number.POSITIVE_INFINITY}),r+=n.length,s=r):r++;if(r===c&&s!==c){const u=e.slice(s);this.cachedData?this.cachedData=an(this.cachedData,u):this.cachedData=u}}return{audioTrack:o,videoTrack:Kn(),id3Track:a,textTrack:Kn()}}demuxSampleAes(e,t,n){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Kn(),id3Track:this._id3Track,textTrack:Kn()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const kG=(i,e,t)=>{if(pe(i))return i*90;const n=t?t.baseTime*9e4/t.timescale:0;return e*9e4+n};let ch=null;const DG=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],OG=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],MG=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],FG=[0,1,1,4];function wI(i,e,t,n,r){if(t+24>e.length)return;const s=bI(e,t);if(s&&t+s.frameLength<=e.length){const o=s.samplesPerFrame*9e4/s.sampleRate,a=n+r*o,l={unit:e.subarray(t,t+s.frameLength),pts:a,dts:a};return i.config=[],i.channelCount=s.channelCount,i.samplerate=s.sampleRate,i.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function bI(i,e){const t=i[e+1]>>3&3,n=i[e+1]>>1&3,r=i[e+2]>>4&15,s=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&s!==3){const o=i[e+2]>>1&1,a=i[e+3]>>6,l=t===3?3-n:n===3?3:4,c=DG[l*14+r-1]*1e3,d=OG[(t===3?0:t===2?1:2)*3+s],h=a===3?1:2,f=MG[t][n],p=FG[n],g=f*8*p,m=Math.floor(f*c/d+o)*p;if(ch===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ch=S?parseInt(S[1]):0}return!!ch&&ch<=87&&n===2&&c>=224e3&&a===0&&(i[e+3]=i[e+3]|128),{sampleRate:d,channelCount:h,frameLength:m,samplesPerFrame:g}}}function Xv(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function _I(i,e){return e+1<i.length&&Xv(i,e)}function NG(i,e){return Xv(i,e)&&4<=i.length-e}function AI(i,e){if(e+1<i.length&&Xv(i,e)){const n=bI(i,e);let r=4;n!=null&&n.frameLength&&(r=n.frameLength);const s=e+r;return s===i.length||_I(i,s)}return!1}class BG extends Yv{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const n=oc(e,0);let r=(n==null?void 0:n.length)||0;if(AI(e,r))return!1;for(let s=e.length;r<s;r++)if(vG(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return mG(e,t)}appendFrame(e,t,n){yI(e,this.observer,t,n,e.manifestCodec);const r=xI(e,t,n,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}}const RI=(i,e)=>{let t=0,n=5;e+=n;const r=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);for(;n>0;){o[0]=i[e];const a=Math.min(n,8),l=8-a;s[0]=4278190080>>>24+l<<l,r[0]=(o[0]&s[0])>>l,t=t?t<<a|r[0]:r[0],e+=1,n-=a}return t};class UG extends Yv{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){const r=CI(e,t,n,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=oc(e,0);if(!t)return!1;const n=t.length;return e[n]===11&&e[n+1]===119&&qv(t)!==void 0&&RI(e,n)<16}}function CI(i,e,t,n,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const s=e[t+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(t+u>e.length)return-1;const d=e[t+6]>>5;let h=0;d===2?h+=2:(d&1&&d!==1&&(h+=2),d&4&&(h+=2));const f=(e[t+6]<<8|e[t+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][d]+f,m=e[t+5]>>3,v=e[t+5]&7,y=new Uint8Array([s<<6|m<<1|v>>2,(v&3)<<6|d<<3|f<<2|l>>4,l<<4&224]),S=1536/a*9e4,x=n+r*S,E=e.subarray(t,t+u);return i.config=y,i.channelCount=g,i.samplerate=a,i.samples.push({unit:E,pts:x}),u}class $G extends Yv{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=oc(e,0);let n=(t==null?void 0:t.length)||0;if(t&&e[n]===11&&e[n+1]===119&&qv(t)!==void 0&&RI(e,n)<=16)return!1;for(let r=e.length;n<r;n++)if(AI(e,n))return st.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return NG(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return wI(e,t,n,this.basePTS,this.frameIndex)}}const HG=/\/emsg[-/]ID3/i;class zG{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,n,r){const s=this.videoTrack=Kn("video",1),o=this.audioTrack=Kn("audio",1),a=this.txtTrack=Kn("text",1);if(this.id3Track=Kn("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=tC(e);if(l.video){const{id:c,timescale:u,codec:d,supplemental:h}=l.video;s.id=c,s.timescale=a.timescale=u,s.codec=d,s.supplemental=h}if(l.audio){const{id:c,timescale:u,codec:d}=l.audio;o.id=c,o.timescale=u,o.codec=d}a.id=ZR.text,s.sampleDuration=0,s.duration=o.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return z5(e)}demux(e,t){this.timeOffset=t;let n=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=an(this.remainderData,e));const a=Y5(n);this.remainderData=a.remainder,r.samples=a.valid||new Uint8Array}else r.samples=n;const o=this.extractID3Track(r,t);return s.samples=rC(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return n.samples=rC(e,t),{videoTrack:t,audioTrack:Kn(),id3Track:r,textTrack:Kn()}}extractID3Track(e,t){const n=this.id3Track;if(e.samples.length){const r=We(e.samples,["emsg"]);r&&r.forEach(s=>{const o=Z5(s);if(HG.test(o.schemeIdUri)){const a=II(o,t);let l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=o.payload;n.samples.push({data:c,len:c.byteLength,dts:a,pts:a,type:Ii.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=II(o,t);n.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:Ii.misbklv,duration:Number.POSITIVE_INFINITY})}})}return n}demuxSampleAes(e,t,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function II(i,e){return pe(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class VG{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Lv(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,fs.cbc)}decryptAacSample(e,t,n){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),o=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(o).then(a=>{const l=new Uint8Array(a);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t);let r=0;for(let s=32;s<e.length-16;s+=160,r+=16)n.set(e.subarray(s,s+16),r);return n}getAvcDecryptedUnit(e,t){const n=new Uint8Array(t);let r=0;for(let s=32;s<e.length-16;s+=160,r+=16)e.set(n.subarray(r,r+16),s);return e}decryptAvcSample(e,t,n,r,s){const o=sC(s.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,n=0){if(t>=e.length){r();return}const s=e[t].units;for(;!(n>=s.length);n++){const o=s[n];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,n,r,o),!this.decrypter.isSync()))return}}}}class PI{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){const s=n.units;r=s[s.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const n=t.samples,r=n.length;if(r){const s=n[r-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){const r=t.byteLength;let s=e.naluState||0;const o=s,a=[];let l=0,c,u,d,h=-1,f=0;for(s===-1&&(h=0,f=this.getNALuType(t,0),s=0,l=1);l<r;){if(c=t[l++],!s){s=c?0:1;continue}if(s===1){s=c?0:2;continue}if(!c)s=3;else if(c===1){if(u=l-s-1,h>=0){const p={data:t.subarray(h,u),type:f};a.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(o&&l<=4-o&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-o)),u>0&&(p.data=an(p.data,t.subarray(0,u)),p.state=0))}l<r?(d=this.getNALuType(t,l),h=l,f=d,s=0):s=-1}else s=0}if(h>=0&&s>=0){const p={data:t.subarray(h,r),type:f,state:s};a.push(p)}if(a.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=an(p.data,t))}return e.naluState=s,a}}class ac{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");r.set(e.subarray(n,n+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const n=this.word>>>32-t;if(e>32&&st.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class GG extends PI{parsePES(e,t,n,r){const s=this.parseNALu(e,n.data,r);let o=this.VideoSample,a,l=!1;n.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),s.forEach(c=>{var u,d;switch(c.type){case 1:{let g=!1;a=!0;const m=c.data;if(l&&m.length>4){const v=this.readSliceType(m);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),o.frame=!0,o.key=g;break}case 5:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,Ev(c.data,1,n.pts,t.samples);break}case 7:{var f,p;a=!0,l=!0;const g=c.data,m=this.readSPS(g);if(!e.sps||e.width!==m.width||e.height!==m.height||((f=e.pixelRatio)==null?void 0:f[0])!==m.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==m.pixelRatio[1]){e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let y="avc1.";for(let S=0;S<3;S++){let x=v[S].toString(16);x.length<2&&(x="0"+x),y+=x}e.codec=y}break}case 8:a=!0,e.pps=[c.data];break;case 9:a=!0,e.audFound=!0,(d=o)!=null&&d.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(c)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new ac(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,s;for(let o=0;o<e;o++)r!==0&&(s=t.readEG(),r=(n+s+256)%256),n=r===0?n:r}readSPS(e){const t=new ac(e);let n=0,r=0,s=0,o=0,a,l,c;const u=t.readUByte.bind(t),d=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();const y=u();if(d(5),p(3),u(),m(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const I=h();if(I===3&&p(1),m(),m(),p(1),f())for(l=I!==3?8:12,c=0;c<l;c++)f()&&(c<6?v(16,t):v(64,t))}m();const S=h();if(S===0)h();else if(S===1)for(p(1),g(),g(),a=h(),c=0;c<a;c++)g();m(),p(1);const x=h(),E=h(),C=d(1);C===0&&p(1),p(1),f()&&(n=h(),r=h(),s=h(),o=h());let b=[1,1];if(f()&&f())switch(u()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:{b=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((x+1)*16-n*2-r*2),height:(2-C)*(E+1)*16-(C?2:4)*(s+o),pixelRatio:b}}}class WG extends PI{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,n,r){const s=this.parseNALu(e,n.data,r);let o=this.VideoSample,a,l=!1;n.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),s.forEach(c=>{var u,d;switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,Ev(c.data,2,n.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=at(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(c.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in f.params)e.params[p]=f.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(c.data);for(const p in f)e.params[p]=f[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(d=o)!=null&&d.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:a=!1;break}o&&a&&o.units.push(c)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let n=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ac(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){const t=new ac(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const n=t.readBits(3);t.readBoolean();const r=t.readBits(2),s=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),c=t.readUByte(),u=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),m=t.readUByte(),v=t.readUByte(),y=[],S=[];for(let De=0;De<n;De++)y.push(t.readBoolean()),S.push(t.readBoolean());if(n>0)for(let De=n;De<8;De++)t.readBits(2);for(let De=0;De<n;De++)y[De]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[De]&&t.readUByte();t.readUEG();const x=t.readUEG();x==3&&t.skipBits(1);const E=t.readUEG(),C=t.readUEG(),b=t.readBoolean();let I=0,D=0,P=0,k=0;b&&(I+=t.readUEG(),D+=t.readUEG(),P+=t.readUEG(),k+=t.readUEG());const N=t.readUEG(),B=t.readUEG(),K=t.readUEG(),q=t.readBoolean();for(let De=q?0:n;De<=n;De++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let w=0;w<4;w++)for(let O=0;O<(w===3?2:6);O++)if(!t.readBoolean())t.readUEG();else{const ie=Math.min(64,1<<4+(w<<1));w>1&&t.readEG();for(let te=0;te<ie;te++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let U=0;for(let De=0;De<F;De++){let w=!1;if(De!==0&&(w=t.readBoolean()),w){De===F&&t.readUEG(),t.readBoolean(),t.readUEG();let O=0;for(let z=0;z<=U;z++){const ie=t.readBoolean();let te=!1;ie||(te=t.readBoolean()),(ie||te)&&O++}U=O}else{const O=t.readUEG(),z=t.readUEG();U=O+z;for(let ie=0;ie<O;ie++)t.readUEG(),t.readBoolean();for(let ie=0;ie<z;ie++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const De=t.readUEG();for(let w=0;w<De;w++){for(let O=0;O<K+4;O++)t.readBits(1);t.readBits(1)}}let V=0,Z=1,Q=1,le=!0,re=1,ye=0;t.readBoolean(),t.readBoolean();let de=!1;if(t.readBoolean()){if(t.readBoolean()){const xe=t.readUByte(),he=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],$e=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];xe>0&&xe<16?(Z=he[xe-1],Q=$e[xe-1]):xe===255&&(Z=t.readBits(16),Q=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),de=t.readBoolean(),de&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(re=t.readBits(32),ye=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const $e=t.readBoolean(),ze=t.readBoolean();let ce=!1;($e||ze)&&(ce=t.readBoolean(),ce&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ce&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let fe=0;fe<=n;fe++){le=t.readBoolean();const He=le||t.readBoolean();let R=!1;He?t.readEG():R=t.readBoolean();const A=R?1:t.readUEG()+1;if($e)for(let L=0;L<A;L++)t.readUEG(),t.readUEG(),ce&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ze)for(let L=0;L<A;L++)t.readUEG(),t.readUEG(),ce&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),V=t.readUEG())}let qe=E,Le=C;if(b){let De=1,w=1;x===1?De=w=2:x==2&&(De=2),qe=E-De*D-De*I,Le=C-w*k-w*P}const Fe=r?["A","B","C"][r]:"",Ue=a<<24|l<<16|c<<8|u;let Xe=0;for(let De=0;De<32;De++)Xe=(Xe|(Ue>>De&1)<<31-De)>>>0;let it=Xe.toString(16);return o===1&&it==="2"&&(it="6"),{codecString:`hvc1.${Fe}${o}.${it}.${s?"H":"L"}${v}.B0`,params:{general_tier_flag:s,general_profile_idc:o,general_profile_space:r,general_profile_compatibility_flags:[a,l,c,u],general_constraint_indicator_flags:[d,h,f,p,g,m],general_level_idc:v,bit_depth:N+8,bit_depth_luma_minus8:N,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:V,chroma_format_idc:x,frame_rate:{fixed:le,fps:ye/re}},width:qe,height:Le,pixelRatio:[Z,Q]}}readPPS(e){const t=new ac(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const r=t.readBoolean(),s=t.readBoolean();let o=1;return s&&r?o=0:s?o=3:r&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Kt=188;class gs{constructor(e,t,n,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.logger=r,this.videoParser=null}static probe(e,t){const n=gs.syncOffset(e);return n>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(e){const t=e.length;let n=Math.min(Kt*5,t-Kt)+1,r=0;for(;r<n;){let s=!1,o=-1,a=0;for(let l=r;l<t;l+=Kt)if(e[l]===71&&(t-l===Kt||e[l+Kt]===71)){if(a++,o===-1&&(o=l,o!==0&&(n=Math.min(o+Kt*99,e.length-Kt)+1)),s||(s=Zv(e,l)===0),s&&a>1&&(o===0&&a>2||l+Kt>n))return o}else{if(a)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ZR[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,n,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=gs.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=gs.createTrack("audio",r),this._id3Track=gs.createTrack("id3"),this._txtTrack=gs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,n=!1,r=!1){n||(this.sampleAes=null);let s;const o=this._videoTrack,a=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=o.pid,d=o.pesData,h=a.pid,f=l.pid,p=a.pesData,g=l.pesData,m=null,v=this.pmtParsed,y=this._pmtId,S=e.length;if(this.remainderData&&(e=an(this.remainderData,e),S=e.length,this.remainderData=null),S<Kt&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};const x=Math.max(0,gs.syncOffset(e));S-=(S-x)%Kt,S<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let E=0;for(let b=x;b<S;b+=Kt)if(e[b]===71){const I=!!(e[b+1]&64),D=Zv(e,b),P=(e[b+3]&48)>>4;let k;if(P>1){if(k=b+5+e[b+4],k===b+Kt)continue}else k=b+4;switch(D){case u:I&&(d&&(s=xa(d,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,s,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(k,b+Kt)),d.size+=b+Kt-k);break;case h:if(I){if(p&&(s=xa(p,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s);break}p={data:[],size:0}}p&&(p.data.push(e.subarray(k,b+Kt)),p.size+=b+Kt-k);break;case f:I&&(g&&(s=xa(g,this.logger))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(k,b+Kt)),g.size+=b+Kt-k);break;case 0:I&&(k+=e[k]+1),y=this._pmtId=jG(e,k);break;case y:{I&&(k+=e[k]+1);const N=KG(e,k,this.typeSupported,n,this.observer,this.logger);u=N.videoPid,u>0&&(o.pid=u,o.segmentCodec=N.segmentVideoCodec),h=N.audioPid,h>0&&(a.pid=h,a.segmentCodec=N.segmentAudioCodec),f=N.id3Pid,f>0&&(l.pid=f),m!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${b} after unknown PID '${m}'. Backtracking to sync byte @${x} to parse all TS packets.`),m=null,b=x-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=D;break}}else E++;E>0&&Qv(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=d,a.pesData=p,l.pesData=g;const C={audioTrack:a,videoTrack:o,id3Track:l,textTrack:c};return r&&this.extractRemainingSamples(C),C}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:n,id3Track:r,textTrack:s}=e,o=n.pesData,a=t.pesData,l=r.pesData;let c;if(o&&(c=xa(o,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,s,c,!0),n.pesData=null)):n.pesData=o,a&&(c=xa(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(c=xa(l,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,n){const r=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new VG(this.observer,this.config,t);return this.decrypt(r,s)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new GG:e==="hevc"&&(this.videoParser=new WG))}decrypt(e,t){return new Promise(n=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{n(e)}):n(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let n=0;const r=this.aacOverFlow;let s=t.data;if(r){this.aacOverFlow=null;const d=r.missing,h=r.sample.unit.byteLength;if(d===-1)s=an(r.sample.unit,s);else{const f=h-d;r.sample.unit.set(s.subarray(0,d),f),e.samples.push(r.sample),n=r.missing}}let o,a;for(o=n,a=s.length;o<a-1&&!ah(s,o);o++);if(o!==n){let d;const h=o<a-1;if(h?d=`AAC PES did not start with ADTS header,offset:${o}`:d="No ADTS header found in AAC PES",Qv(this.observer,new Error(d),h,this.logger),!h)return}yI(e,this.observer,s,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){const d=SI(e.samplerate);l=r.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;o<a;)if(u=xI(e,s,o,l,c),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;o<a-1&&!ah(s,o);o++);}parseMPEGPES(e,t){const n=t.data,r=n.length;let s=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<r;)if(_I(n,o)){const l=wI(e,n,o,a,s);if(l)o+=l.length,s++;else break}else o++}parseAC3PES(e,t){{const n=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=n.length;let o=0,a=0,l;for(;a<s&&(l=CI(e,n,a,r,o++))>0;)a+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=at({},t,{type:this._videoTrack?Ii.emsg:Ii.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function Zv(i,e){return((i[e+1]&31)<<8)+i[e+2]}function jG(i,e){return(i[e+10]&31)<<8|i[e+11]}function KG(i,e,t,n,r,s){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(i[e+1]&15)<<8|i[e+2],l=e+3+a-4,c=(i[e+10]&15)<<8|i[e+11];for(e+=12+c;e<l;){const u=Zv(i,e),d=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!n){Jv("ADTS AAC",s);break}case 15:o.audioPid===-1&&(o.audioPid=u);break;case 21:o.id3Pid===-1&&(o.id3Pid=u);break;case 219:if(!n){Jv("H.264",s);break}case 27:o.videoPid===-1&&(o.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?s.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="mp3");break;case 193:if(!n){Jv("AC-3",s);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=u,o.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&d>0){let h=e+5,f=d;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=u,o.segmentAudioCodec="ac3");break}const g=i[h+1]+2;h+=g,f-=g}}break;case 194:case 135:return Qv(r,new Error("Unsupported EC-3 in M2TS found"),void 0,s),o;case 36:o.videoPid===-1&&(o.videoPid=u,o.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=d+5}return o}function Qv(i,e,t,n){n.warn(`parsing error: ${e.message}`),i.emit(_.ERROR,_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Jv(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function xa(i,e){let t=0,n,r,s,o,a;const l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=an(l[0],l[1]),l.splice(1,1);if(n=l[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(r=(n[4]<<8)+n[5],r&&r>i.size-6)return null;const u=n[7];u&192&&(o=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,u&64?(a=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,o-a>60*9e4&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),s=n[8];let d=s+9;if(i.size<=d)return null;i.size-=d;const h=new Uint8Array(i.size);for(let f=0,p=l.length;f<p;f++){n=l[f];let g=n.byteLength;if(d)if(d>g){d-=g;continue}else n=n.subarray(d),g-=d,d=0;h.set(n,t),t+=g}return r&&(r-=s+3),{data:h,pts:o,dts:a,len:r}}return null}class qG{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const ms=Math.pow(2,32)-1;class G{static init(){G.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in G.types)G.types.hasOwnProperty(e)&&(G.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);G.HDLR_TYPES={video:t,audio:n};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);G.STTS=G.STSC=G.STCO=s,G.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),G.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),G.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),G.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);G.FTYP=G.box(G.types.ftyp,o,l,o,a),G.DINF=G.box(G.types.dinf,G.box(G.types.dref,r))}static box(e,...t){let n=8,r=t.length;const s=r;for(;r--;)n+=t[r].byteLength;const o=new Uint8Array(n);for(o[0]=n>>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=n&255,o.set(e,4),r=0,n=8;r<s;r++)o.set(t[r],n),n+=t[r].byteLength;return o}static hdlr(e){return G.box(G.types.hdlr,G.HDLR_TYPES[e])}static mdat(e){return G.box(G.types.mdat,e)}static mdhd(e,t){t*=e;const n=Math.floor(t/(ms+1)),r=Math.floor(t%(ms+1));return G.box(G.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return G.box(G.types.mdia,G.mdhd(e.timescale||0,e.duration||0),G.hdlr(e.type),G.minf(e))}static mfhd(e){return G.box(G.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?G.box(G.types.minf,G.box(G.types.smhd,G.SMHD),G.DINF,G.stbl(e)):G.box(G.types.minf,G.box(G.types.vmhd,G.VMHD),G.DINF,G.stbl(e))}static moof(e,t,n){return G.box(G.types.moof,G.mfhd(e),G.traf(n,t))}static moov(e){let t=e.length;const n=[];for(;t--;)n[t]=G.trak(e[t]);return G.box.apply(null,[G.types.moov,G.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(G.mvex(e)))}static mvex(e){let t=e.length;const n=[];for(;t--;)n[t]=G.trex(e[t]);return G.box.apply(null,[G.types.mvex,...n])}static mvhd(e,t){t*=e;const n=Math.floor(t/(ms+1)),r=Math.floor(t%(ms+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return G.box(G.types.mvhd,s)}static sdtp(e){const t=e.samples||[],n=new Uint8Array(4+t.length);let r,s;for(r=0;r<t.length;r++)s=t[r].flags,n[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return G.box(G.types.sdtp,n)}static stbl(e){return G.box(G.types.stbl,G.stsd(e),G.box(G.types.stts,G.STTS),G.box(G.types.stsc,G.STSC),G.box(G.types.stsz,G.STSZ),G.box(G.types.stco,G.STCO))}static avc1(e){let t=[],n=[],r,s,o;for(r=0;r<e.sps.length;r++)s=e.sps[r],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));for(r=0;r<e.pps.length;r++)s=e.pps[r],o=s.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(s));const a=G.box(G.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(n))),l=e.width,c=e.height,u=e.pixelRatio[0],d=e.pixelRatio[1];return G.box(G.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return G.box(G.types.mp4a,G.audioStsd(e),G.box(G.types.esds,G.esds(e)))}static mp3(e){return G.box(G.types[".mp3"],G.audioStsd(e))}static ac3(e){return G.box(G.types["ac-3"],G.audioStsd(e),G.box(G.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return G.box(G.types.stsd,G.STSD,G.mp4a(e));if(t==="ac3"&&e.config)return G.box(G.types.stsd,G.STSD,G.ac3(e));if(t==="mp3"&&e.codec==="mp3")return G.box(G.types.stsd,G.STSD,G.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return G.box(G.types.stsd,G.STSD,G.avc1(e));if(t==="hevc"&&e.vps)return G.box(G.types.stsd,G.STSD,G.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,n=(e.duration||0)*(e.timescale||0),r=e.width||0,s=e.height||0,o=Math.floor(n/(ms+1)),a=Math.floor(n%(ms+1));return G.box(G.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,t){const n=G.sdtp(e),r=e.id,s=Math.floor(t/(ms+1)),o=Math.floor(t%(ms+1));return G.box(G.types.traf,G.box(G.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),G.box(G.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),G.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,G.box(G.types.trak,G.tkhd(e),G.mdia(e))}static trex(e){const t=e.id;return G.box(G.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const n=e.samples||[],r=n.length,s=12+16*r,o=new Uint8Array(s);let a,l,c,u,d,h;for(t+=8+s,o.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<r;a++)l=n[a],c=l.duration,u=l.size,d=l.flags,h=l.cts,o.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return G.box(G.types.trun,o)}static initSegment(e){G.types||G.init();const t=G.moov(e);return an(G.FTYP,t)}static hvc1(e){const t=e.params,n=[e.vps,e.sps,e.pps],r=4,s=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),n.length]);let o=s.length;for(let p=0;p<n.length;p+=1){o+=3;for(let g=0;g<n[p].length;g+=1)o+=2+n[p][g].length}const a=new Uint8Array(o);a.set(s,0),o=s.length;const l=n.length-1;for(let p=0;p<n.length;p+=1){a.set(new Uint8Array([32+p|(p===l?128:0),0,n[p].length]),o),o+=3;for(let g=0;g<n[p].length;g+=1)a.set(new Uint8Array([n[p][g].length>>8,n[p][g].length&255]),o),o+=2,a.set(n[p][g],o),o+=n[p][g].length}const c=G.box(G.types.hvcC,a),u=e.width,d=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return G.box(G.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,G.box(G.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),G.box(G.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}G.types=void 0,G.HDLR_TYPES=void 0,G.STTS=void 0,G.STSC=void 0,G.STCO=void 0,G.STSZ=void 0,G.VMHD=void 0,G.SMHD=void 0,G.STSD=void 0,G.FTYP=void 0,G.DINF=void 0;const LI=9e4;function e0(i,e,t=1,n=!1){const r=i*e*t;return n?Math.round(r):r}function YG(i,e,t=1,n=!1){return e0(i,e,1/t,n)}function lc(i,e=!1){return e0(i,1e3,1/LI,e)}function XG(i,e=1){return e0(i,LI,1/e)}function kI(i){const{baseTime:e,timescale:t,trackId:n}=i;return`${e/t} (${e}/${t}) trackId: ${n}`}const ZG=10*1e3,QG=1024,JG=1152,eW=1536;let Ta=null,t0=null;function DI(i,e,t,n){return{duration:e,size:t,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class uh extends on{constructor(e,t,n,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,Ta===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ta=o?parseInt(o[1]):0}if(t0===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);t0=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&kI(t)} > ${e&&kI(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const n=e[0].pts,r=e.reduce((s,o)=>{let a=o.pts,l=a-s;return l<-4294967296&&(t=!0,a=Gi(a,n),l=a-s),l>0?s:a},n);return t&&this.debug("PTS rollover detected"),r}remux(e,t,n,r,s,o,a,l){let c,u,d,h,f,p,g=s,m=s;const v=e.pid>-1,y=t.pid>-1,S=t.samples.length,x=e.samples.length>0,E=a&&S>0||S>1;if((!v||x)&&(!y||E)||this.ISGenerated||a){if(this.ISGenerated){var b,I,D,P;const K=this.videoTrackConfig;(K&&(t.width!==K.width||t.height!==K.height||((b=t.pixelRatio)==null?void 0:b[0])!==((I=K.pixelRatio)==null?void 0:I[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((P=K.pixelRatio)==null?void 0:P[1]))||!K&&E||this.nextAudioTs===null&&x)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,o));const k=this.isVideoContiguous;let N=-1,B;if(E&&(N=tW(t.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,N>0){this.warn(`Dropped ${N} out of ${S} video samples due to a missing keyframe`);const K=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(N),t.dropped+=N,m+=(t.samples[0].pts-K)/t.inputTimeScale,B=m}else N===-1&&(this.warn(`No keyframe found out of ${S} video samples`),p=!1);if(this.ISGenerated){if(x&&E){const K=this.getVideoStartPts(t.samples),H=(Gi(e.samples[0].pts,K)-K)/t.inputTimeScale;g+=Math.max(0,H),m+=Math.max(0,-H)}if(x){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,o)),u=this.remuxAudio(e,g,this.isAudioContiguous,o,y||E||l===ve.AUDIO?m:void 0),E){const K=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,o)),c=this.remuxVideo(t,m,k,K)}}else E&&(c=this.remuxVideo(t,m,k,0));c&&(c.firstKeyFrame=N,c.independent=N!==-1,c.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=OI(n,s,this._initPTS,this._initDTS)),r.samples.length&&(h=MI(r,s,this._initPTS))),{audio:u,video:c,initSegment:d,independent:p,text:h,id3:f}}computeInitPts(e,t,n,r){const s=Math.round(n*t);let o=Gi(e,s);if(o<s+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-o)/t} ${r}`);o<s+t;)o+=8589934592;return o-s}generateIS(e,t,n,r){const s=e.samples,o=t.samples,a=this.typeSupported,l={},c=this._initPTS;let u=!c||r,d="audio/mp4",h,f,p,g=-1;if(u&&(h=f=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(d="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):G.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,p=e.inputTimeScale,!c||p!==c.timescale?h=f=this.computeInitPts(s[0].pts,p,n,"audio"):u=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:G.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,p=t.inputTimeScale,!c||p!==c.timescale){const m=this.getVideoStartPts(o),v=Gi(o[0].dts,m),y=this.computeInitPts(v,p,n,"video"),S=this.computeInitPts(m,p,n,"video");f=Math.min(f,y),h=Math.min(h,S)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(c&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${n} ${h/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${h/p} (${h}/${p}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:p,trackId:g},this._initDTS={baseTime:f,timescale:p,trackId:g}):h=p=void 0,{tracks:l,initPTS:h,timescale:p,trackId:g}}remuxVideo(e,t,n,r){const s=e.inputTimeScale,o=e.samples,a=[],l=o.length,c=this._initPTS,u=c.baseTime*s/c.timescale;let d=this.nextVideoTs,h=8,f=this.videoSampleDuration,p,g,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!n||d===null){const V=u+t*s,Z=o[0].pts-Gi(o[0].dts,o[0].pts);Ta&&d!==null&&Math.abs(V-Z-(d+u))<15e3?n=!0:d=V-Z-u}const S=d+u;for(let V=0;V<l;V++){const Z=o[V];Z.pts=Gi(Z.pts,S),Z.dts=Gi(Z.dts,S),Z.dts<o[V>0?V-1:V].dts&&(y=!0)}y&&o.sort(function(V,Z){const Q=V.dts-Z.dts,le=V.pts-Z.pts;return Q||le}),p=o[0].dts,g=o[o.length-1].dts;const x=g-p,E=x?Math.round(x/(l-1)):f||e.inputTimeScale/30;if(n){const V=p-S,Z=V>E,Q=V<-1;if((Z||Q)&&(Z?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${lc(V,!0)} ms (${V}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${lc(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Q||S>=o[0].pts||Ta)){p=S;const le=o[0].pts-V;if(Z)o[0].dts=p,o[0].pts=le;else{let re=!0;for(let ye=0;ye<o.length&&!(o[ye].dts>le&&re);ye++){const de=o[ye].pts;if(o[ye].dts-=V,o[ye].pts-=V,ye<o.length-1){const Pe=o[ye+1].pts,qe=o[ye].pts,Le=Pe<=qe,Fe=Pe<=de;re=Le==Fe}}}this.log(`Video: Initial PTS/DTS adjusted: ${lc(le,!0)}/${lc(p,!0)}, delta: ${lc(V,!0)} ms`)}}p=Math.max(0,p);let C=0,b=0,I=p;for(let V=0;V<l;V++){const Z=o[V],Q=Z.units,le=Q.length;let re=0;for(let ye=0;ye<le;ye++)re+=Q[ye].data.length;b+=re,C+=le,Z.length=re,Z.dts<I?(Z.dts=I,I+=E/4|0||1):I=Z.dts,m=Math.min(Z.pts,m),v=Math.max(Z.pts,v)}g=o[l-1].dts;const D=b+4*C+8;let P;try{P=new Uint8Array(D)}catch(V){this.observer.emit(_.ERROR,_.ERROR,{type:we.MUX_ERROR,details:W.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:D,reason:`fail allocating video mdat ${D}`});return}const k=new DataView(P.buffer);k.setUint32(0,D),P.set(G.types.mdat,4);let N=!1,B=Number.POSITIVE_INFINITY,K=Number.POSITIVE_INFINITY,q=Number.NEGATIVE_INFINITY,H=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){const Z=o[V],Q=Z.units;let le=0;for(let de=0,Pe=Q.length;de<Pe;de++){const qe=Q[de],Le=qe.data,Fe=qe.data.byteLength;k.setUint32(h,Fe),h+=4,P.set(Le,h),h+=Fe,le+=4+Fe}let re;if(V<l-1)f=o[V+1].dts-Z.dts,re=o[V+1].pts-Z.pts;else{const de=this.config,Pe=V>0?Z.dts-o[V-1].dts:E;if(re=V>0?Z.pts-o[V-1].pts:E,de.stretchShortVideoTrack&&this.nextAudioTs!==null){const qe=Math.floor(de.maxBufferHole*s),Le=(r?m+r*s:this.nextAudioTs+u)-Z.pts;Le>qe?(f=Le-Pe,f<0?f=Pe:N=!0,this.log(`It is approximately ${Le/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Pe}else f=Pe}const ye=Math.round(Z.pts-Z.dts);B=Math.min(B,f),q=Math.max(q,f),K=Math.min(K,re),H=Math.max(H,re),a.push(DI(Z.key,f,le,ye))}if(a.length){if(Ta){if(Ta<70){const V=a[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(t0&&H-K<q-B&&E/q<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let V=p;for(let Z=0,Q=a.length;Z<Q;Z++){const le=V+a[Z].duration,re=V+a[Z].cts;if(Z<Q-1){const ye=le+a[Z+1].cts;a[Z].duration=ye-re}else a[Z].duration=Z?a[Z-1].duration:E;a[Z].cts=0,V=le}}}f=N||!f?E:f;const X=g+f;this.nextVideoTs=d=X-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const j={data1:G.moof(e.sequenceNumber++,p,at(e,{samples:a})),data2:P,startPTS:(m-u)/s,endPTS:(v+f-u)/s,startDTS:(p-u)/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,j}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return JG;case"ac3":return eW;default:return QG}}remuxAudio(e,t,n,r,s){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,c=this.getSamplesPerFrame(e),u=c*l,d=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=s!==void 0;let g=e.samples,m=h?0:8,v=this.nextAudioTs||-1;const y=d.baseTime*o/d.timescale,S=y+t*o;if(this.isAudioContiguous=n=n||g.length&&v>0&&(r&&Math.abs(S-(v+y))<9e3||Math.abs(Gi(g[0].pts,S)-(v+y))<20*u),g.forEach(function(H){H.pts=Gi(H.pts,S)}),!n||v<0){const H=g.length;if(g=g.filter(X=>X.pts>=0),H!==g.length&&this.warn(`Removed ${g.length-H} of ${H} samples (initPTS ${y} / ${o})`),!g.length)return;s===0?v=0:r&&!p?v=Math.max(0,S-y):v=g[0].pts-y}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let X=0,F=v+y;X<g.length;X++){const U=g[X],j=U.pts,V=j-F,Z=Math.abs(1e3*V/o);if(V<=-H*u&&p)X===0&&(this.warn(`Audio frame @ ${(j/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*V/o)} ms.`),this.nextAudioTs=v=j-y,F=j);else if(V>=H*u&&Z<ZG&&p){let Q=Math.round(V/u);for(F=j-Q*u;F<0&&Q&&u;)Q--,F+=u;X===0&&(this.nextAudioTs=v=F-y),this.warn(`Injecting ${Q} audio frames @ ${((F-y)/o).toFixed(3)}s due to ${Math.round(1e3*V/o)} ms gap.`);for(let le=0;le<Q;le++){let re=qG.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);re||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),re=U.unit.subarray()),g.splice(X,0,{unit:re,pts:F}),F+=u,X++}}U.pts=F,F+=u}}let x=null,E=null,C,b=0,I=g.length;for(;I--;)b+=g[I].unit.byteLength;for(let H=0,X=g.length;H<X;H++){const F=g[H],U=F.unit;let j=F.pts;if(E!==null){const Z=f[H-1];Z.duration=Math.round((j-E)/l)}else if(n&&e.segmentCodec==="aac"&&(j=v+y),x=j,b>0){b+=m;try{C=new Uint8Array(b)}catch(Z){this.observer.emit(_.ERROR,_.ERROR,{type:we.MUX_ERROR,details:W.REMUX_ALLOC_ERROR,fatal:!1,error:Z,bytes:b,reason:`fail allocating audio mdat ${b}`});return}h||(new DataView(C.buffer).setUint32(0,b),C.set(G.types.mdat,4))}else return;C.set(U,m);const V=U.byteLength;m+=V,f.push(DI(!0,c,V,0)),E=j}const D=f.length;if(!D)return;const P=f[f.length-1];v=E-y,this.nextAudioTs=v+l*P.duration;const k=h?new Uint8Array(0):G.moof(e.sequenceNumber++,x/l,at({},e,{samples:f}));e.samples=[];const N=(x-y)/o,B=v/o,q={data1:k,data2:C,startPTS:N,endPTS:B,startDTS:N,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,q}}function Gi(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function tW(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function OI(i,e,t,n){const r=i.samples.length;if(!r)return;const s=i.inputTimeScale;for(let a=0;a<r;a++){const l=i.samples[a];l.pts=Gi(l.pts-t.baseTime*s/t.timescale,e*s)/s,l.dts=Gi(l.dts-n.baseTime*s/n.timescale,e*s)/s}const o=i.samples;return i.samples=[],{samples:o}}function MI(i,e,t){const n=i.samples.length;if(!n)return;const r=i.inputTimeScale;for(let o=0;o<n;o++){const a=i.samples[o];a.pts=Gi(a.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((o,a)=>o.pts-a.pts);const s=i.samples;return i.samples=[],{samples:s}}class iW extends on{constructor(e,t,n,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:n,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:s,video:o}=this.initData=tC(e);if(t)j5(e,t);else{const l=s||o;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}s&&(n=FI(s,dt.AUDIO,this)),o&&(r=FI(o,dt.VIDEO,this));const a={};s&&o?a.audiovideo={container:"video/mp4",codec:n+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?a.audio={container:"audio/mp4",codec:n,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?a.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,n,r,s,o){var a,l;let{initPTS:c,lastEndTime:u}=this;const d={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};pe(u)||(u=this.lastEndTime=s||0);const h=t.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((a=p)!=null&&a.length||(this.generateInitSegment(h),p=this.initData),!((l=p)!=null&&l.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=q5(h,p,this),m=p.audio?g[p.audio.id]:null,v=p.video?g[p.video.id]:null,y=dh(v,1/0),S=dh(m,1/0),x=dh(v,0,!0),E=dh(m,0,!0);let C=s,b=0;const I=m&&(!v||!c&&S<y||c&&c.trackId===p.audio.id),D=I?m:v;if(D){const F=D.timescale,U=D.start-s*F,j=I?p.audio.id:p.video.id;C=D.start/F,b=I?E-S:x-y,(o||!c)&&(nW(c,C,s,b)||F!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${o?"":"~"}${s} ${U/F} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${C-s} (${U}/${F}) trackId: ${j}`),c=null,f.initPTS=U,f.timescale=F,f.trackId=j)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=C,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const P=C-c.baseTime/c.timescale,k=P+b;b>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const N=!!p.audio,B=!!p.video;let K="";N&&(K+="audio"),B&&(K+="video");const q=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),H={data1:h,startPTS:P,startDTS:P,endPTS:k,endDTS:k,type:K,hasAudio:N,hasVideo:B,nb:1,dropped:0,encrypted:q};d.audio=N&&!B?H:void 0,d.video=B?H:void 0;const X=v==null?void 0:v.sampleCount;if(X){const F=v.keyFrameIndex,U=F!==-1;H.nb=X,H.dropped=F===0||this.isVideoContiguous?0:U?F:X,H.independent=U,H.firstKeyFrame=F,U&&v.keyFrameStart&&(H.firstKeyFramePTS=(v.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(d.independent=U),this.isVideoContiguous||(this.isVideoContiguous=U),H.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${F}/${X} dropped: ${H.dropped} start: ${H.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=OI(n,s,c,c),r.samples.length&&(d.text=MI(r,s,c)),d}}function dh(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function nW(i,e,t,n){if(i===null)return!0;const r=Math.max(n,1),s=e-i.baseTime/i.timescale;return Math.abs(s-t)>r}function FI(i,e,t){const n=i.codec;return n&&n.length>4?n:e===dt.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?Wd(n,!1):(t.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(t.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let _r;try{_r=self.performance.now.bind(self.performance)}catch{_r=Date.now}const hh=[{demux:zG,remux:iW},{demux:gs,remux:uh},{demux:BG,remux:uh},{demux:$G,remux:uh}];hh.splice(2,0,{demux:UG,remux:uh});class NI{constructor(e,t,n,r,s,o){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.id=s,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){const s=n.transmuxing;s.executeStart=_r();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);const{contiguous:c,discontinuity:u,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:p}=r||a,{audioCodec:g,videoCodec:m,defaultInitPts:v,duration:y,initSegmentData:S}=l,x=rW(o,t);if(x&&ya(x.method)){const I=this.getDecrypter(),D=Ov(x.method);if(I.isSync()){let P=I.softwareDecrypt(o,x.key.buffer,x.iv.buffer,D);if(n.part>-1){const N=I.flush();P=N&&N.buffer}if(!P)return s.executeEnd=_r(),i0(n);o=new Uint8Array(P)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(o,x.key.buffer,x.iv.buffer,D).then(P=>{const k=this.push(P,null,n);return this.decryptionPromise=null,k}),this.decryptionPromise}const E=this.needsProbing(u,d);if(E){const I=this.configureTransmuxer(o);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(_.ERROR,_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),s.executeEnd=_r(),i0(n)}(u||d||p||E)&&this.resetInitSegment(S,g,m,y,t),(u||p||E)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const C=this.transmux(o,x,f,h,n);this.asyncResult=cc(C);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=_r(),C}flush(e){const t=e.transmuxing;t.executeStart=_r();const{decrypter:n,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const o=[],{timeOffset:a}=r;if(n){const d=n.flush();d&&o.push(this.push(d.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=_r();const d=[i0(e)];return this.asyncResult?Promise.resolve(d):d}const u=l.flush(a);return cc(u)?(this.asyncResult=!0,u.then(d=>(this.flushRemux(o,d,e),o))):(this.flushRemux(o,u,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,n){const{audioTrack:r,videoTrack:s,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===ve.MAIN?"level":"track"} ${n.level}`);const u=this.remuxer.remux(r,s,o,a,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:n}),n.transmuxing.executeEnd=_r()}resetInitialTimestamp(e){const{demuxer:t,remuxer:n}=this;!t||!n||(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,s){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,n,r),a.resetInitSegment(e,t,n,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,n,r,s){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,n,r,s):o=this.transmuxUnencrypted(e,n,r,s),o}transmuxUnencrypted(e,t,n,r){const{audioTrack:s,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,o,a,l,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,s){return this.demuxer.demuxSampleAes(e,t,n).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,n,r,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:n,typeSupported:r}=this;let s;for(let d=0,h=hh.length;d<h;d++){var o;if((o=hh[d].demux)!=null&&o.probe(e,this.logger)){s=hh[d];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,c=s.remux,u=s.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(n,t,r,this.logger)),(!a||!(a instanceof u))&&(this.demuxer=new u(n,t,r,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Lv(this.config)),e}}function rW(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const i0=i=>({remuxResult:{},chunkMeta:i});function cc(i){return"then"in i&&i.then instanceof Function}class sW{constructor(e,t,n,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=s||null}}class oW{constructor(e,t,n,r,s,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=o}}let BI=0;class UI{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=BI++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,u=this.hls;if(!(!u||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var d;const h=(d=this.workerContext)==null?void 0:d.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{u.logger[c.data.logType]&&u.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,u.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;const o=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===_.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new Gv,this.observer.on(_.FRAG_DECRYPTED,o),this.observer.on(_.ERROR,o);const a=cC(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||uG()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=hG(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=dG());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ht(s)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new NI(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new NI(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=BI++;const t=this.hls.config,n=cC(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:ht(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),fG(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,s,o,a,l,c,u){var d,h;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:p}=this,g=o?o.start:s.start,m=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),S=!(v&&c.level===v.level),x=v?c.sn-v.sn:-1,E=this.part?c.part-this.part.index:-1,C=x===0&&c.id>1&&c.id===(v==null?void 0:v.stats.chunkCount),b=!S&&(x===1||x===0&&(E===1||C&&E<=0)),I=self.performance.now();(S||x||s.stats.parsing.start===0)&&(s.stats.parsing.start=I),o&&(E||!b)&&(o.stats.parsing.start=I);const D=!(v&&((d=s.initSegment)==null?void 0:d.url)===((h=v.initSegment)==null?void 0:h.url)),P=new oW(y,b,l,S,g,D);if(!b||y||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===ve.MAIN?"level":"track"}: ${c.level} id: ${c.id}
|
|
214
|
+
discontinuity: ${y}
|
|
215
|
+
trackSwitch: ${S}
|
|
216
|
+
contiguous: ${b}
|
|
217
|
+
accurateTimeOffset: ${l}
|
|
218
|
+
timeOffset: ${g}
|
|
219
|
+
initSegmentChange: ${D}`);const k=new sW(n,r,t,a,u);this.configureTransmuxer(k)}if(this.frag=s,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:P},e instanceof ArrayBuffer?[e]:[]);else if(p){const k=p.push(e,m,c,P);cc(k)?k.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(k)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(n){const r=n.flush(e);cc(r)?r.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const $I=100;class HI extends sh{constructor(e,t,n){super(e,t,n,"audio-stream-controller",ve.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(_.BUFFER_RESET,this.onBufferReset,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(_.BUFFER_RESET,this.onBufferReset,this),e.off(_.BUFFER_CREATED,this.onBufferCreated,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s,trackId:o}){if(n===ve.MAIN){const a=t.cc,l=this.fragCurrent;if(this.initPTS[a]={baseTime:r,timescale:s,trackId:o},this.log(`InitPTS for cc: ${a} found from main: ${r/s} (${r}/${s}) trackId: ${o}`),this.mainAnchor=t,this.state===J.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==a)&&this.syncWithAnchor(t,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==a?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===J.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var n;const r=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(t&&(r==null?void 0:r.cc)===t.cc)return;const s=(r||e).cc,o=this.getLevelDetails(),a=this.getLoadPosition(),l=EC(o,s,a);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===J.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=J.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval($I),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=J.IDLE):this.state=J.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case J.IDLE:this.doTickIdle();break;case J.WAITING_TRACK:{const{levels:e,trackId:t}=this,n=e==null?void 0:e[t],r=n==null?void 0:n.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=J.WAITING_INIT_PTS}break}case J.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case J.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:n,cache:r,complete:s}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=J.FRAG_LOADING;const a=r.flush().buffer,l={frag:t,part:n,payload:a,networkDetails:null};this._handleFragmentLoadProgress(l),s&&super._handleFragmentLoadComplete(l)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag)}else this.state=J.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:n,media:r,trackId:s}=this,o=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(n!=null&&n[s]))return;const a=n[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=J.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,dt.AUDIO,ve.AUDIO));const u=this.getFwdBufferInfo(c,ve.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(_.BUFFER_EOS,{type:"audio"}),this.state=J.ENDED;return}const d=u.len,h=t.maxBufferLength,f=l.fragments,p=f[0].start,g=this.getLoadPosition(),m=this.flushing?g:u.end;if(this.switchingTrack&&r){const S=g;l.PTSKnown&&S<p&&(u.end>p||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=p+.05)}if(d>=h&&!this.switchingTrack&&m<f[f.length-1].start)return;let v=this.getNextFragment(m,l);if(v&&this.isLoopLoading(v,m)&&(v=this.getNextFragmentLoopLoading(v,l,u,ve.MAIN,h)),!v){this.bufferFlushed=!0;return}let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Ft(v)&&!v.endList&&(!l.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===Ht.OK&&(this.mainFragLoading=y=null),y&&Ft(y))){if(v.start>y.end){const x=this.fragmentTracker.getFragAtPos(m,ve.MAIN);x&&x.end>y.end&&(y=x,this.mainFragLoading={frag:x,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(n=>new ga(n))}onAudioTrackSwitching(e,t){const n=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==J.STOPPED&&(this.setInterval($I),this.state=J.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(_.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;const{levels:r}=this,{details:s,id:o,groupId:a,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}const c=this.mainDetails;if(!c||s.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==J.STOPPED&&(this.state=J.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=r[o];let d=0;if(s.live||(n=u.details)!=null&&n.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;d=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(dI(s,c),s.alignedSliding||rh(s,c),d=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(c,d),this.hls.trigger(_.AUDIO_TRACK_UPDATED,{details:s,id:o,groupId:t.groupId}),this.state===J.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=J.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const n=e.frag,{part:r,payload:s}=e,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const c=l[a];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const d=o.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new UI(this.hls,ve.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[n.cc],p=(t=n.initSegment)==null?void 0:t.data;if(f!==void 0){const m=r?r.index:-1,v=m!==-1,y=new Qd(n.level,n.sn,n.stats.chunkCount,s.byteLength,m,v);h.push(s,p,d,"",n,r,u.totalduration,!1,y,f)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:n,part:r,cache:new fI,complete:!1};g.push(new Uint8Array(s)),this.state!==J.STOPPED&&(this.state=J.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===ve.MAIN&&Ft(t.frag)&&(this.mainFragLoading=t,this.state===J.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:n,part:r}=t;if(n.type!==ve.AUDIO){!this.audioOnly&&n.type===ve.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ft(n)){this.fragPrevious=n;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(_.AUDIO_TRACK_SWITCHED,rt({},s)))}this.fragBufferedComplete(n,r),this.media&&this.tick()}onError(e,t){var n;if(t.fatal){this.state=J.ERROR;return}switch(t.details){case W.FRAG_GAP:case W.FRAG_PARSING_ERROR:case W.FRAG_DECRYPT_ERROR:case W.FRAG_LOAD_ERROR:case W.FRAG_LOAD_TIMEOUT:case W.KEY_LOAD_ERROR:case W.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ve.AUDIO,t);break;case W.AUDIO_TRACK_LOAD_ERROR:case W.AUDIO_TRACK_LOAD_TIMEOUT:case W.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===J.WAITING_TRACK&&((n=t.context)==null?void 0:n.type)===Ke.AUDIO_TRACK&&(this.state=J.IDLE);break;case W.BUFFER_ADD_CODEC_ERROR:case W.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case W.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case W.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==dt.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==dt.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===J.ENDED&&(this.state=J.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,t,ve.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const n="audio",{hls:r}=this,{remuxResult:s,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:l,part:c,level:u}=a,{details:d}=u,{audio:h,text:f,id3:p,initSegment:g}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=J.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const m=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(u,g.tracks,m,o),r.trigger(_.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:n,tracks:g.tracks})}if(h){const{startPTS:m,endPTS:v,startDTS:y,endDTS:S}=h;c&&(c.elementaryStreams[dt.AUDIO]={startPTS:m,endPTS:v,startDTS:y,endDTS:S}),l.setElementaryStreamInfo(dt.AUDIO,m,v,y,S),this.bufferFragmentData(h,l,c,o)}if(p!=null&&(t=p.samples)!=null&&t.length){const m=at({id:n,frag:l,details:d},p);r.trigger(_.FRAG_PARSING_METADATA,m)}if(f){const m=at({id:n,frag:l,details:d},f);r.trigger(_.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,t,n,r){if(this.state!==J.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=ve.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${o}/${s.codec}]`),o&&o.split(",").length===1&&(s.levelCodec=o),this.hls.trigger(_.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:n,part:null,chunkMeta:r,parent:n.type,data:a};this.hls.trigger(_.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Ht.NOT_LOADED||r===Ht.PARTIAL){var s;if(!Ft(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=J.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&rh(t.details,o)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:n,assocLang:r,characteristics:s,audioCodec:o,channels:a}=this.bufferedTrack;no({name:t,lang:n,assocLang:r,characteristics:s,audioCodec:o,channels:a},e,ro)||(qd(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(_.AUDIO_TRACK_SWITCHED,rt({},e))}}class fh extends on{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,n){const r=t==null?void 0:t.renditionReports;if(r){let s=-1;for(let o=0;o<r.length;o++){const a=r[o];let l;try{l=new self.URL(a.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=a.URI||""}if(l===e){s=o;break}else l===e.substring(0,l.length)&&(s=o)}if(s!==-1){const o=r[s],a=parseInt(o["LAST-MSN"])||t.lastPartSn;let l=parseInt(o["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}const c=n&&pC(n);return new Cv(a,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return e}playlistLoaded(e,t,n){const{details:r,stats:s}=t,o=self.performance.now(),a=s.loading.first?Math.max(0,o-s.loading.first):0;r.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){const u=Math.max(l||0,0);r.appliedTimelineOffset=u,r.fragments.forEach(d=>{d.setStart(d.playlistOffset+u)})}if(r.live||n!=null&&n.live){const u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(n),n&&r.fragments.length>0){JV(n,r,this);const y=r.playlistParsingError;if(y){this.warn(y);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var c;const{networkDetails:x}=t;S.trigger(_.ERROR,{type:we.NETWORK_ERROR,details:W.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:y,reason:y.message,level:t.level||void 0,parent:(c=r.fragments[0])==null?void 0:c.type,networkDetails:x,stats:s});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=s.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=(r.edge-h)*1e3,p=nI(r,f);if(r.requestScheduled+p<o?r.requestScheduled=o:r.requestScheduled+=p,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let g,m,v;if(r.canBlockReload&&r.endSN&&r.advanced){const y=this.hls.config.lowLatencyMode,S=r.lastPartSn,x=r.endSN,E=r.lastPartIndex,C=E!==-1,b=S===x;C?b?(m=x+1,v=y?0:E):(m=S,v=y?E+1:r.maxPartIndex):m=x+1;const I=r.age,D=I+r.ageHeader;let P=Math.min(D-r.partTarget,r.targetduration*1.5);if(P>0){if(D>r.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(n!=null&&n.tuneInGoal&&D-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${P} with playlist age: ${r.age}`),P=0;else{const k=Math.floor(P/r.targetduration);if(m+=k,v!==void 0){const N=Math.round(P%r.targetduration/r.partTarget);v+=N}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${P} skip sn ${k} to part ${v}`)}r.tuneInGoal=P}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,m,v),y||!b){r.requestScheduled=o,this.loadingPlaylist(u,g);return}}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,m,v));g&&m!==void 0&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(p-a*2,p/2)),this.scheduleLoading(u,g,r)}else this.clearTimer()}scheduleLoading(e,t,n){const r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}const s=self.performance.now(),o=r.requestScheduled;if(s>=o){this.loadingPlaylist(e,t);return}const a=o-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,n,r){let s=pC(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,s=ic.No),new Cv(n,r,s)}checkRetry(e){const t=e.details,n=Yd(e),r=e.errorAction,{action:s,retryCount:o=0,retryConfig:a}=r||{},l=!!r&&!!a&&(s===Wt.RetryRequest||!r.resolved&&s===Wt.SendAlternateToPenaltyBox);if(l){var c;if(o>=a.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=Iv(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}function zI(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!uc(i[t].attrs,e[t].attrs))return!1;return!0}function uc(i,e,t){const n=i["STABLE-RENDITION-ID"];return n&&!t?n===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function n0(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}class VI extends fh{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(_.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:n,groupId:r,details:s}=t,o=this.tracksInGroup[n];if(!o||o.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${n} "${o.name}" lang:${o.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const n=t.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!n||(r==null?void 0:r.length)!==(n==null?void 0:n.length)||n!=null&&n.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!n||n.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,f)=>{h.id=f});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=jn(l,a,ro);if(h>-1)s=a[h];else{const f=jn(l,this.tracks);s=this.tracks[f]}}let c=this.findTrackId(s);c===-1&&s&&(c=this.findTrackId(null));const u={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(_.AUDIO_TRACKS_UPDATED,u);const d=this.trackId;if(c!==-1&&d===-1)this.setAudioTrack(c);else if(a.length&&d===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Ke.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const r=this.currentTrack;if(r&&no(e,r,ro))return r;const s=jn(e,this.tracksInGroup,ro);if(s>-1){const o=this.tracksInGroup[s];return this.setAudioTrack(s),o}else if(r){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=wV(e,t.levels,n,o,ro);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=jn(e,n);if(o>-1)return n[o]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===n&&s||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(_.AUDIO_TRACK_SWITCHING,rt({},r)),s))return;const o=this.switchParams(r.url,n==null?void 0:n.details,r.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if(!(this.selectDefaultTrack&&!r.default)&&(!e||no(e,r,ro)))return n}if(e){const{name:n,lang:r,assocLang:s,characteristics:o,audioCodec:a,channels:l}=e;for(let c=0;c<t.length;c++){const u=t[c];if(no({name:n,lang:r,assocLang:s,characteristics:o,audioCodec:a,channels:l},u,ro))return c}for(let c=0;c<t.length;c++){const u=t[c];if(uc(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const u=t[c];if(uc(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&qd(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const n=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(_.AUDIO_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:t||null,track:e})}}class aW{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,n){if(this.queues===null||this.tracks===null)return;const r=this.queues[t];r.push(e),r.length===1&&!n&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const n={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const n={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const n=(t=e[0])==null?void 0:t.label;(n==="async-blocker"||n==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(s){var n;if(r.onError(s),this.queues===null||this.tracks===null)return;const o=(n=this.tracks[e])==null?void 0:n.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
|
|
220
|
+
${this.list("video")}
|
|
221
|
+
${this.list("audio")}
|
|
222
|
+
${this.list("audiovideo")}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const n=(t=this.tracks)==null?void 0:t[e],r=n==null?void 0:n.buffer;return r?`SourceBuffer${r.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(n=>n.label).join(", "))||""}}const GI=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,WI="HlsJsTrackRemovedError";class lW extends Error{constructor(e){super(e),this.name=WI}}class jI extends on{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=n=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:r,mediaSource:s}=this;n&&this.log("Media source opened"),!(!r||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(_.MEDIA_ATTACHED,{media:r,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:r}=this;n!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${n})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=N5(Er(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.BUFFER_RESET,this.onBufferReset,this),e.on(_.BUFFER_APPENDING,this.onBufferAppending,this),e.on(_.BUFFER_CODECS,this.onBufferCodecs,this),e.on(_.BUFFER_EOS,this.onBufferEos,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.FRAG_PARSED,this.onFragParsed,this),e.on(_.FRAG_CHANGED,this.onFragChanged,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.BUFFER_RESET,this.onBufferReset,this),e.off(_.BUFFER_APPENDING,this.onBufferAppending,this),e.off(_.BUFFER_CODECS,this.onBufferCodecs,this),e.off(_.BUFFER_EOS,this.onBufferEos,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.FRAG_PARSED,this.onFragParsed,this),e.off(_.FRAG_CHANGED,this.onFragChanged,this),e.off(_.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const n={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const o=this.isQueued();(s||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?at(n,r.tracks):this.sourceBuffers.forEach(s=>{const[o]=s;o&&(n[o]=at({},this.tracks[o]),this.removeBuffer(o)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:n}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var n;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){const n=this.media=t.media;this.transferData=this.overrides=void 0;const r=Er(this.appendSource);if(r){const s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(o),s)this._objectUrl=n.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{n.removeAttribute("src");const l=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||l&&o instanceof l,KI(n),cW(n,a),n.load()}catch{n.src=a}else n.src=a}n.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,n;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(n=e.constructor)==null?void 0:n.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const n=this.tracks,r=t.tracks,s=r?Object.keys(r):null,o=s?s.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&s&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
223
|
+
required tracks: ${ht(n,(l,c)=>l==="initSegment"?void 0:c)};
|
|
224
|
+
transfer tracks: ${ht(r,(l,c)=>l==="initSegment"?void 0:c)}}`),!WR(r,n)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,c=this.details,u=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(_.MEDIA_DETACHING,{}),this.onMediaAttaching(_.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const c=l,u=r[c];if(u){const d=u.buffer;if(d){const h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){const m=Be.getBuffered(d);h.detectEvictedFragments(c,m,f,null,!0)}const p=r0(c),g=[c,d];this.sourceBuffers[p]=g,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const n=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:s,_objectUrl:o}=this;if(s){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let c=l.length;c--;)a&&l[c].abort(),s.removeSourceBuffer(l[c]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),n||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(r.removeAttribute("src"),this.appendSource&&KI(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(_.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const n=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),n)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[r0(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new aW(this.tracks)}onBufferCodecs(e,t){var n;const r=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!o&&this.sourceBufferCount&&this.media&&s.some(l=>!r[l]);if(o||a){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${s}" SourceBuffers`);return}s.forEach(l=>{var c,u;const d=t[l],{id:h,codec:f,levelCodec:p,container:g,metadata:m,supplemental:v}=d;let y=r[l];const S=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],x=S!=null&&S.buffer?S:y,E=(x==null?void 0:x.pendingCodec)||(x==null?void 0:x.codec),C=x==null?void 0:x.levelCodec;y||(y=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:g,levelCodec:p,metadata:m,id:h});const b=jd(E,C),I=b==null?void 0:b.replace(GI,"$1");let D=jd(f,p);const P=(u=D)==null?void 0:u.replace(GI,"$1");D&&b&&I!==P&&(l.slice(0,5)==="audio"&&(D=Wd(D,this.appendSource)),this.log(`switching codec ${E} to ${D}`),D!==(y.pendingCodec||y.codec)&&(y.pendingCodec=D),y.container=g,this.appendChangeType(l,g,D))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((n=t.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){const r=`${t};codecs=${n}`,s={label:`change-type=${r}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),o.codec=n,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const n=e.start,r=n+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(n,ve.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&Be.isBuffered(l.buffer,r)||((a=this.fragmentTracker.getAppendedFrag(r,ve.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:n}=this,{data:r,type:s,parent:o,frag:a,part:l,chunkMeta:c,offset:u}=t,d=c.buffering[s],{sn:h,cc:f}=a,p=self.performance.now();d.start=p;const g=a.stats.buffering,m=l?l.stats.buffering:null;g.start===0&&(g.start=p),m&&m.start===0&&(m.start=p);const v=n.audio;let y=!1;s==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const S=n.video,x=S==null?void 0:S.buffer;if(x&&h!=="initSegment"){const b=l||a,I=this.blockedAudioAppend;if(s==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const P=b.start+b.duration*.05,k=x.buffered,N=this.currentOp("video");!k.length&&!N?this.blockAudio(b):!N&&!Be.isBuffered(x,P)&&this.lastVideoAppendEnd<P&&this.blockAudio(b)}else if(s==="video"){const D=b.end;if(I){const P=I.frag.start;(D>P||D<this.lastVideoAppendEnd||Be.isBuffered(x,P))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const E=(l||a).start,C={label:`append-${s}`,execute:()=>{var b;d.executeStart=self.performance.now();const I=(b=this.tracks[s])==null?void 0:b.buffer;I&&(y?this.updateTimestampOffset(I,E,.1,s,h,f):u!==void 0&&pe(u)&&this.updateTimestampOffset(I,u,1e-6,s,h,f)),this.appendExecutor(r,s)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();d.executeEnd=d.end=b,g.first===0&&(g.first=b),m&&m.first===0&&(m.first=b);const I={};this.sourceBuffers.forEach(([D,P])=>{D&&(I[D]=Be.getBuffered(P))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(_.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:c,parent:a.type,timeRanges:I})},onError:b=>{var I;const D={type:we.MEDIA_ERROR,parent:a.type,details:W.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:c,error:b,err:b,fatal:!1},P=(I=this.media)==null?void 0:I.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)D.details=W.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!P)D.errorAction=ma(!0);else if(b.name===WI&&this.sourceBufferCount===0)D.errorAction=ma(!0);else{const k=++this.appendErrors[s];this.warn(`Failed ${k}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${P||"no media error"})`),(k>=this.hls.config.appendErrorMaxRetry||P)&&(D.fatal=!0)}this.hls.trigger(_.ERROR,D)}};this.log(`queuing "${s}" append sn: ${h}${l?" p: "+l.index:""} of ${a.type===ve.MAIN?"level":"track"} ${a.level} cc: ${f}`),this.append(C,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(_.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:n,startOffset:r,endOffset:s}=t;n?this.append(this.getFlushOp(n,r,s),n):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,r,s),o)})}onFragParsed(e,t){const{frag:n,part:r}=t,s=[],o=r?r.elementaryStreams:n.elementaryStreams;o[dt.AUDIOVIDEO]?s.push("audiovideo"):(o[dt.AUDIO]&&s.push("audio"),o[dt.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();n.stats.buffering.end=l,r&&(r.stats.buffering.end=l);const c=r?r.stats:n.stats;this.hls.trigger(_.FRAG_BUFFERED,{frag:n,part:r,stats:c,id:n.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var n;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const r=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(_.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(_.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===W.BUFFER_APPEND_ERROR&&t.frag){var n;const r=(n=t.errorAction)==null?void 0:n.nextAutoLevel;pe(r)&&r!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:n}=this;if(!n||t===null||!this.sourceBufferCount)return;const r=e.config,s=n.currentTime,o=t.levelTargetDuration,a=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(pe(a)&&a>=0){const c=Math.max(a,o),u=Math.floor(s/o)*o-c;this.flushBackBuffer(s,o,u)}const l=r.frontBufferFlushThreshold;if(pe(l)&&l>0){const c=Math.max(r.maxBufferLength,l),u=Math.max(c,o),d=Math.floor(s/o)*o+u;this.flushFrontBuffer(s,o,d)}}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([r,s])=>{if(s){const a=Be.getBuffered(s);if(a.length>0&&n>a.start(0)){var o;this.hls.trigger(_.BACK_BUFFER_REACHED,{bufferEnd:n});const l=this.tracks[r];if((o=this.details)!=null&&o.live)this.hls.trigger(_.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(_.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:r})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([r,s])=>{if(s){const o=Be.getBuffered(s),a=o.length;if(a<2)return;const l=o.start(a-1),c=o.end(a-1);if(n>l||e>=l&&e<=c)return;this.hls.trigger(_.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;const{details:t,mediaSource:n}=this;if(!t||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&n.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart),u=Math.max(c,r);return{duration:1/0,start:c,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return pe(s)?{duration:s}:null;const o=this.media.duration,a=pe(n.duration)?n.duration:0;return r>a&&r>o||!pe(o)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:n}){const r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(pe(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ht(n)}`),this.tracksReady){var r;const s=(r=this.transferData)==null?void 0:r.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,n])=>{if(t){const r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(_.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const o=s,a=e[o];if(this.isPending(a)){const l=this.getTrackCodec(a,o),c=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(o)?" Queued":""} ${ht(a)}`);try{const u=n.addSourceBuffer(c),d=r0(o),h=[o,u];t[d]=h,a.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(o),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[o],this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:o,mimeType:c,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const n=e.supplemental;let r=e.codec;n&&(t==="video"||t==="audiovideo")&&ec(n,"video")&&(r=rV(r,n));const s=jd(r,e.levelCodec);return s?t.slice(0,5)==="audio"?Wd(s,this.appendSource):s:""}trackSourceBuffer(e,t){const n=t.buffer;if(!n)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(s,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(_.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const n=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const n=this.currentOp(e);n&&(n.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var n;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${r}`,t),this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const s=this.currentOp(e);s&&s.onError(r)}updateTimestampOffset(e,t,n,r,s,o){const a=t-e.timestampOffset;Math.abs(a)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,n){const{media:r,mediaSource:s}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!r||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=pe(r.duration)?r.duration:1/0,c=pe(s.duration)?s.duration:1/0,u=Math.max(0,t),d=Math.min(n,l,c);d>u&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),a.remove(u,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const n=this.tracks[t],r=n==null?void 0:n.buffer;if(!r)throw new lW(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:n}=this,r=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(o=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var n;const r=(n=this.tracks[t])==null?void 0:n.buffer;!r||r.updating||this.shiftAndExecuteNext(t)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){const r=this.tracks[e];if(!r)return;const s=r.buffer;if(!s)return;const o=n.bind(this,e);r.listeners.push({event:t,listener:o}),s.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const n=t.buffer;n&&(t.listeners.forEach(r=>{n.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}}function KI(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function cW(i,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function r0(i){return i==="audio"?1:0}class ph{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(_.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.BUFFER_CODECS,this.onBufferCodecs,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(_.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.BUFFER_CODECS,this.onBufferCodecs,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&pe(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const n=t.filter((r,s)=>this.isLevelAllowed(r)&&s<=e);return this.clientRect=null,ph.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;const r=(a,l)=>l?a.width!==l.width||a.height!==l.height:!0;let s=e.length-1;const o=Math.max(t,n);for(let a=0;a<e.length;a+=1){const l=e[a];if((l.width>=o||l.height>=o)&&r(l,e[a+1])){s=a;break}}return s}}const Pi={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},uW={HLS:"h"};class qn{constructor(e,t){Array.isArray(e)&&(e=e.map(n=>n instanceof qn?n:new qn(n))),this.value=e,this.params=t}}const dW="Dict";function hW(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function fW(i,e,t,n){return new Error(`failed to ${i} "${hW(e)}" as ${t}`,{cause:n})}function Yn(i,e,t){return fW("serialize",i,e,t)}class qI{constructor(e){this.description=e}}const YI="Bare Item",pW="Boolean";function gW(i){if(typeof i!="boolean")throw Yn(i,pW);return i?"?1":"?0"}function mW(i){return btoa(String.fromCharCode(...i))}const vW="Byte Sequence";function yW(i){if(ArrayBuffer.isView(i)===!1)throw Yn(i,vW);return`:${mW(i)}:`}const SW="Integer";function xW(i){return i<-999999999999999||999999999999999<i}function XI(i){if(xW(i))throw Yn(i,SW);return i.toString()}function TW(i){return`@${XI(i.getTime()/1e3)}`}function ZI(i,e){if(i<0)return-ZI(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const r=Math.floor(i*t);return(r%2===0?r:r+1)/t}else return Math.round(i*t)/t}const EW="Decimal";function wW(i){const e=ZI(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Yn(i,EW);const t=e.toString();return t.includes(".")?t:`${t}.0`}const bW="String",_W=/[\x00-\x1f\x7f]+/;function AW(i){if(_W.test(i))throw Yn(i,bW);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function RW(i){return i.description||i.toString().slice(7,-1)}const CW="Token";function QI(i){const e=RW(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Yn(e,CW);return e}function s0(i){switch(typeof i){case"number":if(!pe(i))throw Yn(i,YI);return Number.isInteger(i)?XI(i):wW(i);case"string":return AW(i);case"symbol":return QI(i);case"boolean":return gW(i);case"object":if(i instanceof Date)return TW(i);if(i instanceof Uint8Array)return yW(i);if(i instanceof qI)return QI(i);default:throw Yn(i,YI)}}const IW="Key";function o0(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw Yn(i,IW);return i}function a0(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${o0(e)}`:`;${o0(e)}=${s0(t)}`).join("")}function JI(i){return i instanceof qn?`${s0(i.value)}${a0(i.params)}`:s0(i)}function PW(i){return`(${i.value.map(JI).join(" ")})${a0(i.params)}`}function LW(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw Yn(i,dW);const t=i instanceof Map?i.entries():Object.entries(i),n=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,s])=>{s instanceof qn||(s=new qn(s));let o=o0(r);return s.value===!0?o+=a0(s.params):(o+="=",Array.isArray(s.value)?o+=PW(s):o+=JI(s)),o}).join(`,${n}`)}function eP(i,e){return LW(i,e)}const Xn="CMCD-Object",Pt="CMCD-Request",oo="CMCD-Session",vs="CMCD-Status",kW={br:Xn,ab:Xn,d:Xn,ot:Xn,tb:Xn,tpb:Xn,lb:Xn,tab:Xn,lab:Xn,url:Xn,pb:Pt,bl:Pt,tbl:Pt,dl:Pt,ltc:Pt,mtp:Pt,nor:Pt,nrr:Pt,rc:Pt,sn:Pt,sta:Pt,su:Pt,ttfb:Pt,ttfbb:Pt,ttlb:Pt,cmsdd:Pt,cmsds:Pt,smrt:Pt,df:Pt,cs:Pt,ts:Pt,cid:oo,pr:oo,sf:oo,sid:oo,st:oo,v:oo,msd:oo,bs:vs,bsd:vs,cdn:vs,rtp:vs,bg:vs,pt:vs,ec:vs,e:vs},DW={REQUEST:Pt};function OW(i){return Object.keys(i).reduce((e,t)=>{var n;return(n=i[t])===null||n===void 0||n.forEach(r=>e[r]=t),e},{})}function MW(i,e){const t={};if(!i)return t;const n=Object.keys(i),r=e?OW(e):{};return n.reduce((s,o)=>{var a;const l=kW[o]||r[o]||DW.REQUEST,c=(a=s[l])!==null&&a!==void 0?a:s[l]={};return c[o]=i[o],s},t)}function FW(i){return["ot","sf","st","e","sta"].includes(i)}function NW(i){return typeof i=="number"?pe(i):i!=null&&i!==""&&i!==!1}const tP="event";function BW(i,e){const t=new URL(i),n=new URL(e);if(t.origin!==n.origin)return i;const r=t.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;r[0]===s[0];)r.shift(),s.shift();for(;s.length;)s.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}const gh=i=>Math.round(i),l0=(i,e)=>Array.isArray(i)?i.map(t=>l0(t,e)):i instanceof qn&&typeof i.value=="string"?new qn(l0(i.value,e),i.params):(e.baseUrl&&(i=BW(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),mh=i=>gh(i/100)*100,UW={br:gh,d:gh,bl:mh,dl:mh,mtp:mh,nor:(i,e)=>{let t=i;return e.version>=2&&(i instanceof qn&&typeof i.value=="string"?t=new qn([i]):typeof i=="string"&&(t=[i])),l0(t,e)},rtp:mh,tb:gh},iP="request",nP="response",c0=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],$W=["e"],HW=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function vh(i){return HW.test(i)}function zW(i){return c0.includes(i)||$W.includes(i)||vh(i)}const rP=["d","dl","nor","ot","rtp","su"];function VW(i){return c0.includes(i)||rP.includes(i)||vh(i)}const GW=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function WW(i){return c0.includes(i)||rP.includes(i)||GW.includes(i)||vh(i)}const jW=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function KW(i){return jW.includes(i)||vh(i)}const qW={[nP]:WW,[tP]:zW,[iP]:VW};function sP(i,e={}){const t={};if(i==null||typeof i!="object")return t;const n=e.version||i.v||1,r=e.reportingMode||iP,s=n===1?KW:qW[r];let o=Object.keys(i).filter(s);const a=e.filter;typeof a=="function"&&(o=o.filter(a));const l=r===nP||r===tP;l&&!o.includes("ts")&&o.push("ts"),n>1&&!o.includes("v")&&o.push("v");const c=at({},UW,e.formatters),u={version:n,reportingMode:r,baseUrl:e.baseUrl};return o.sort().forEach(d=>{let h=i[d];const f=c[d];if(typeof f=="function"&&(h=f(h,u)),d==="v"){if(n===1)return;h=n}d=="pr"&&h===1||(l&&d==="ts"&&!pe(h)&&(h=Date.now()),NW(h)&&(FW(d)&&typeof h=="string"&&(h=new qI(h)),t[d]=h))}),t}function YW(i,e={}){const t={};if(!i)return t;const n=sP(i,e),r=MW(n,e==null?void 0:e.customHeaderMap);return Object.entries(r).reduce((s,[o,a])=>{const l=eP(a,{whitespace:!1});return l&&(s[o]=l),s},t)}function XW(i,e,t){return at(i,YW(e,t))}const ZW="CMCD";function QW(i,e={}){return i?eP(sP(i,e),{whitespace:!1}):""}function JW(i,e={}){if(!i)return"";const t=QW(i,e);return encodeURIComponent(t)}function ej(i,e={}){if(!i)return"";const t=JW(i,e);return`${ZW}=${t}`}const oP=/CMCD=[^&#]+/;function tj(i,e,t){const n=ej(e,t);if(!n)return i;if(oP.test(i))return i.replace(oP,n);const r=i.includes("?")?"&":"?";return`${i}${r}${n}`}class aP{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Pi.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=r=>{try{const{frag:s,part:o}=r,a=this.hls.levels[s.level],l=this.getObjectType(s),c={d:(o||s).duration*1e3,ot:l};(l===Pi.VIDEO||l===Pi.AUDIO||l==Pi.MUXED)&&(c.br=a.bitrate/1e3,c.tb=this.getTopBandwidth(l)/1e3,c.bl=this.getBufferLength(l));const u=o?this.getNextPart(o):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(c.nor=u.url),this.apply(r,c)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHED,this.onMediaDetached,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHED,this.onMediaDetached,this),e.off(_.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var n,r;this.audioBuffer=(n=t.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:uW.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){at(t,this.createData());const n=t.ot===Pi.INIT||t.ot===Pi.VIDEO||t.ot===Pi.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((o,a)=>(r.includes(a)&&(o[a]=t[a]),o),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),XW(e.headers,t,s)):e.url=tj(e.url,t,s)}getNextFrag(e){var t;const n=(t=this.hls.levels[e.level])==null?void 0:t.details;if(n){const r=e.sn-n.startSN;return n.fragments[r+1]}}getNextPart(e){var t;const{index:n,fragment:r}=e,s=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(s){const{sn:o}=r;for(let a=s.length-1;a>=0;a--){const l=s[a];if(l.index===n&&l.fragment.sn===o)return s[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Pi.TIMED_TEXT;if(e.sn==="initSegment")return Pi.INIT;if(t==="audio")return Pi.AUDIO;if(t==="main")return this.hls.audioTracks.length?Pi.VIDEO:Pi.MUXED}getTopBandwidth(e){let t=0,n;const r=this.hls;if(e===Pi.AUDIO)n=r.audioTracks;else{const s=r.maxAutoLevel,o=s>-1?s+1:r.levels.length;n=r.levels.slice(0,o)}return n.forEach(s=>{s.bitrate>t&&(t=s.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,n=e===Pi.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!t?NaN:Be.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,o,a){t(s),this.loader.load(s,o,a)}}}}const ij=3e5;class lP extends on{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(n=>n!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:n}=t;if((n==null?void 0:n.action)===Wt.SendAlternateToPenaltyBox&&n.flags===Ri.MoveAllAlternatesMatchingHost){const r=this.levels;let s=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:c}=t.context;a&&r?o=this.getPathwayForGroupId(a,c,o):l&&(o=l)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!s&&r&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),n.resolved=this.pathwayId!==o),t.details===W.BUFFER_APPEND_ERROR&&!t.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${r&&r.length} priorities: ${ht(s)} penalized: ${ht(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(s=>{r-n[s]>ij&&delete n[s]});for(let s=0;s<e.length;s++){const o=e[s];if(o in n)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,aI(t),this.hls.trigger(_.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[a];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){const r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let s=0;s<r.length;s++)if(t===Ke.AUDIO_TRACK&&r[s].hasAudioGroup(e)||t===Ke.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return n}clonePathways(e){const t=this.levels;if(!t)return;const n={},r={};e.forEach(s=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(u=>u.pathwayId===o))return;const c=this.getLevelsForPathway(a).map(u=>{const d=new xt(u.attrs);d["PATHWAY-ID"]=o;const h=d.AUDIO&&`${d.AUDIO}_clone_${o}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${o}`;h&&(n[d.AUDIO]=h,d.AUDIO=h),f&&(r[d.SUBTITLES]=f,d.SUBTITLES=f);const p=uP(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new ga({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:p,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let m=1;m<u.audioGroups.length;m++)g.addGroupId("audio",`${u.audioGroups[m]}_clone_${o}`);if(u.subtitleGroups)for(let m=1;m<u.subtitleGroups.length;m++)g.addGroupId("text",`${u.subtitleGroups[m]}_clone_${o}`);return g});t.push(...c),cP(this.audioTracks,n,l,o),cP(this.subtitleTracks,r,l,o)})}loadSteeringManifest(e){const t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:r.href},o=t.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(u,d,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);const p=u.data;if((p==null?void 0:p.VERSION)!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":v}=p;if(g)try{this.uri=new self.URL(g,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),m&&this.clonePathways(m);const y={steeringManifest:p,url:r.toString()};this.hls.trigger(_.STEERING_MANIFEST_LOADED,y),v&&this.updatePathwayPriority(v)},onError:(u,d,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let p=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const m=g.getResponseHeader("Retry-After");m&&(p=parseFloat(m)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,p)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const r=(n=this.hls)==null?void 0:n.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function cP(i,e,t,n){i&&Object.keys(e).forEach(r=>{const s=i.filter(o=>o.groupId===r).map(o=>{const a=at({},o);return a.details=void 0,a.attrs=new xt(a.attrs),a.url=a.attrs.URI=uP(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[r],a.attrs["PATHWAY-ID"]=n,a});i.push(...s)})}function uP(i,e,t,n){const{HOST:r,PARAMS:s,[t]:o}=n;let a;e&&(a=o==null?void 0:o[e],a&&(i=a));const l=new self.URL(i);return r&&!a&&(l.host=r),s&&Object.keys(s).sort().forEach(c=>{c&&l.searchParams.set(c,s[c])}),l.href}class ao extends on{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=ao.CDMCleanupPromise?[ao.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:n,initData:r}=t,s=`"${t.type}" event: init data type: "${n}"`;if(this.debug(s),r!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=nc(this.config));const a=o.map(Nv).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=ih(o);if(n!=="sinf"||a!==Tt.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${n}" for selected key-system ${a}`);return}let l;try{const f=$t(new Uint8Array(r)),p=Mv(JSON.parse(f).sinf),g=nC(p);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(g.subarray(8,24))}catch(f){this.warn(`${s} Failed to parse sinf: ${f}`);return}const c=gi(l),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let h=u[c];for(let f=0;f<d.length;f++){const p=d[f],g=p.decryptdata;if(!g.keyId)continue;const m=gi(g.keyId);if(eh(l,g.keyId)||g.uri.replace(/-/g,"").indexOf(c)!==-1){if(h=u[m],!h)continue;if(g.pssh)break;delete u[m],g.pssh=new Uint8Array(r),g.keyId=l,h=u[c]=h.then(()=>this.generateRequestWithPreferredKeySession(p,n,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(_.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(_.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(_.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(_.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(_.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(_.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t==null?void 0:t[e];if(r)return r.licenseUrl;if(e===Tt.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,n=t==null?void 0:t[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,n=(o,a,l)=>!!o&&l.indexOf(o)===a,r=t.map(o=>o.audioCodec).filter(n),s=t.map(o=>o.videoCodec).filter(n);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((o,a)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,r,s).then(d=>o({keySystem:u,mediaKeys:d})).catch(d=>{c.length?l(c):d instanceof Wi?a(d):a(new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${n}`;return Bv===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return n(e,t)}getMediaKeysPromise(e,t,n){var r;const s=GV(e,t,n,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],a=(r=o)==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ht(s)}`),a=this.requestMediaKeySystemAccess(e,s);const l=o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),a.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=l.mediaKeys=c.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return d.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),d})}return a.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${gi(e.keyId||[])} keyUri: ${e.uri}`);const r=n.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const n=this.createMediaKeySessionContext(e),r=yh(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,s,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${gi(e.decryptdata.keyId||[])}
|
|
225
|
+
} (data length: ${t.byteLength})`),n.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Nv(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:n})=>this.attemptSetMediaKeys(t,n))}selectKeySystem(e){return new Promise((t,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{const s=Nv(r);s?t(s):n(new Error(`Unable to find format for key-system "${r}"`))}).catch(n)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=nc(this.config),n=e.map(ih).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){const r=nj(e,t[n]);if(r)return r}}loadKey(e){const t=e.keyInfo.decryptdata,n=yh(t),r=this.bannedKeyIds[n];if(r||this.getKeyStatus(t)==="internal-error"){const a=dP(r||"internal-error",t);return this.handleError(a,e.frag),Promise.reject(a)}const s=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);const o=this.keyIdToKeySessionPromise[n];if(!o){const a=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(l,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:c,decryptdata:t}))))).then(l=>{const c="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,c,u,"playlist-key")});return a.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[n]=a,a}return o.catch(a=>{if(a instanceof Wi){const l=rt({},a.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);const c=new Wi(l,a.message);this.handleError(c,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Wi){t&&(e.data.frag=t);const n=e.data.decryptdata;this.error(`${e.message}${n?` (${gi(n.keyId||[])})`:""}`),this.hls.trigger(_.ERROR,e.data)}else this.error(e.message),this.hls.trigger(_.ERROR,{type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=yh(e),n=this.keyIdToKeySessionPromise[t];if(!n){const r=ih(e.keyFormat),s=r?[r]:nc(this.config);return this.attemptKeySystemAccess(s)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=nc(this.config)),e.length===0)throw new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ht({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(n).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>n.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,t,n,r){var s;const o=(s=this.config.drmSystems)==null||(s=s[e.keySystem])==null?void 0:s.generateRequest;if(o)try{const p=o.call(this.hls,t,n,e);if(!p)throw new Error("Invalid response from configured generateRequest filter");t=p.initDataType,n=p.initData?p.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(p){if(this.warn(p.message),this.hls&&this.hls.config.debug)throw p}if(n===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const a=yh(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${a} URI: ${l} (init data type: ${t} length: ${n.byteLength})`);const c=new Gv,u=e._onmessage=p=>{const g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}const{messageType:m,message:v}=p;this.log(`"${m}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),m==="license-request"||m==="license-renewal"?this.renewLicense(e,v).catch(y=>{c.eventNames().length?c.emit("error",y):this.handleError(y)}):m==="license-release"?e.keySystem===Tt.FAIRPLAY&&this.updateKeySession(e,Fv("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${m}"`)},d=(p,g)=>{g.keyStatus=p;let m;p.startsWith("usable")?c.emit("resolved"):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?m=dP(p,g.decryptdata):p==="expired"?m=new Error(`key expired (keyId: ${a})`):p==="released"?m=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${a})`),m&&(c.eventNames().length?c.emit("error",m):this.handleError(m))},h=e._onkeystatuseschange=p=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const m=this.getKeyStatuses(e);if(!Object.keys(m).some(x=>m[x]!=="status-pending"))return;if(m[a]==="expired"){this.log(`Expired key ${ht(m)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let y=m[a];if(y)d(y,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[a]||(S[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const E=this.getKeyStatus(e.decryptdata);if(E&&E!=="status-pending")return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${E} from other session.`),d(E,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",d(y,e)},1e3)),this.log(`No status for keyId ${a} (${ht(m)}).`)}};mi(e.mediaKeysSession,"message",u),mi(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((p,g)=>{c.on("error",g),c.on("resolved",p)});return e.mediaKeysSession.generateRequest(t,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${l}`)}).catch(p=>{throw new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>f).catch(p=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw p}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((n,r)=>{if(typeof r=="string"&&typeof n=="object"){const a=r;r=n,n=a}const s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===Tt.PLAYREADY&&s.length===16&&$C(s);const o=gi(s);n==="internal-error"&&(this.bannedKeyIds[o]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=n}),t}fetchServerCertificate(e){const t=this.config,n=t.loader,r=new n(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{const l={responseType:"arraybuffer",url:s},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,g)=>{o(h.data)},onError:(h,f,p,g)=>{a(new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:rt({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,p)=>{a(new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,f,p)=>{a(new Error("aborted"))}};r.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise((r,s)=>{e.setServerCertificate(n).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${n.byteLength}) on "${t}"`),r(e)}).catch(o=>{s(new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(r=>{throw new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){const n=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(n,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let u;for(let d=0,h=s.length;d<h;d++){var o,a;u=s[d];const f=(o=u.querySelector("name"))==null?void 0:o.textContent,p=(a=u.querySelector("value"))==null?void 0:a.textContent;f&&p&&e.setRequestHeader(f,p)}}const l=r.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Fv(atob(c))}setupLicenseXHR(e,t,n,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,n,r)}).catch(o=>{if(!n.decryptdata)throw o;return e.open("POST",t,!0),s.call(this.hls,e,t,n,r)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const n=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,a,o,e)}catch(u){this.error(u)}r(l)}else{const l=n.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||a.status>=400&&a.status<500)s(new Wi({type:we.KEY_SYSTEM_ERROR,details:W.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==Tt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const n=t.media;this.media=n,mi(n,"encrypted",this.onMediaEncrypted),mi(n,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(Ci(e,"encrypted",this.onMediaEncrypted),Ci(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ps.clearKeyUriToKeyIdMap();const r=n.length;ao.CDMCleanupPromise=Promise.all(n.map(s=>this.removeSession(s)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(s=>{this.log(`Could not clear media keys: ${s}`),this.hls&&this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${s}`)})}))||Promise.resolve())).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}`),this.hls&&this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${s}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=t.reduce((r,s)=>(r.indexOf(s.keyFormat)===-1&&r.push(s.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:n,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${gi((r==null?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(c=>self.clearTimeout(o[c]));const{drmSystemOptions:a}=this.config;return(jV(a)?new Promise((c,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(c).catch(u)}):Promise.resolve()).catch(c=>{this.log(`Could not remove session: ${c}`),this.hls&&this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${c}`)})}).then(()=>t.close()).catch(c=>{this.log(`Could not close session: ${c}`),this.hls&&this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}ao.CDMCleanupPromise=void 0;function yh(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return gi(i.keyId)}function nj(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}class Wi extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function dP(i,e){const t=i==="output-restricted",n=t?W.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:W.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wi({type:we.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}class hP{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(_.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(_.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const n=this.hls.config;if(n.capLevelOnFPSDrop){const r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){const r=performance.now();if(t){if(this.lastTime){const s=r-this.lastTime,o=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/s,c=this.hls;if(c.trigger(_.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:n}),l>0&&o>c.config.fpsDroppedMonitoringThreshold*a){let u=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(_.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function fP(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function pP(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){st.debug(`[texttrack-utils]: ${n}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){st.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Ea(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let n=i.cues.length;n--;)e&&i.cues[n].removeEventListener("enter",e),i.removeCue(i.cues[n]);t==="disabled"&&(i.mode=t)}function u0(i,e,t,n){const r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const s=sj(i.cues,e,t);for(let o=0;o<s.length;o++)(!n||n(s[o]))&&i.removeCue(s[o])}r==="disabled"&&(i.mode=r)}function rj(i,e){if(e<=i[0].startTime)return 0;const t=i.length-1;if(e>i[t].endTime)return-1;let n=0,r=t,s;for(;n<=r;)if(s=Math.floor((r+n)/2),e<i[s].startTime)r=s-1;else if(e>i[s].startTime&&n<t)n=s+1;else return s;return i[n].startTime-e<e-i[r].startTime?n:r}function sj(i,e,t){const n=[],r=rj(i,e);if(r>-1)for(let s=r,o=i.length;s<o;s++){const a=i[s];if(a.startTime>=e&&a.endTime<=t)n.push(a);else if(a.startTime>t)return n}return n}function Sh(i){const e=[];for(let t=0;t<i.length;t++){const n=i[t];(n.kind==="subtitles"||n.kind==="captions")&&n.label&&e.push(i[t])}return e}class gP extends fh{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const n=Sh(this.media.textTracks);for(let s=0;s<n.length;s++)if(n[s].mode==="hidden")t=n[s];else if(n[s].mode==="showing"){t=n[s];break}const r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(_.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(_.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const n=this.media;if(!n)return;const r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Sh(n.textTracks).forEach(o=>{Ea(o)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:n,groupId:r,details:s}=t,o=this.tracksInGroup[n];if(!o||o.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Subtitle track ${n} "${o.name}" lang:${o.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const n=t.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!n||(r==null?void 0:r.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!n||n.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,d)=>{u.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;const u=jn(a,o);if(u>-1)s=o[u];else{const d=jn(a,this.tracks);s=this.tracks[d]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const c={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(_.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const s=t[r];if(!(n&&!s.default||!n&&!e)&&(!e||no(s,e)))return r}if(e){for(let r=0;r<t.length;r++){const s=t[r];if(uc(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const s=t[r];if(uc(e.attrs,s.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let n=0;n<t.length;n++){const r=t[n];if(n0(r,e))return n}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Ke.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const n=this.currentTrack;if(n&&no(e,n))return n;const r=jn(e,this.tracksInGroup);if(r>-1){const s=this.tracksInGroup[r];return this.setSubtitleTrack(r),s}else{if(n)return null;{const s=jn(e,t);if(s>-1)return t[s]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const n=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(_.SUBTITLE_TRACK_LOADING,{url:s,id:n,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Sh(e.textTracks),n=this.currentTrack;let r;if(n&&(r=t.filter(s=>n0(n,s))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(t).forEach(s=>{s.mode!=="disabled"&&s!==r&&(s.mode="disabled")}),r){const s=this.subtitleDisplay?"showing":"hidden";r.mode!==s&&(r.mode=s)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!pe(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(_.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!r.details&&!r.details.live;if(e===this.trackId&&r===n&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:a="",name:l,type:c,url:u}=r;this.hls.trigger(_.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:c,url:u});const d=this.switchParams(r.url,n==null?void 0:n.details,r.details);this.loadPlaylist(d)}}function oj(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const s=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?s:s&3|8).toString(16)})}}}function dc(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}const wa=.025;let xh=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function aj(i,e,t){return`${i.identifier}-${t+1}-${dc(e)}`}class lj{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const n=this.playoutLimit;return e<=0||isNaN(n)?!1:n===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>n}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return d0(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,n=d0(t,e);return t-n<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=pe(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return d0(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<wa))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?xh.Range:xh.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return cj(this)}}function d0(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<wa)?e.start:e.start+e.duration}function mP(i,e,t){const n=new self.URL(i,t);return n.protocol!=="data:"&&n.searchParams.set("_HLS_primary_id",e),n}function h0(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function cj(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function ba(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class uj{constructor(e,t,n,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(_.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=n,this.assetItem=r;const o=()=>{this.hasDetails=!0};s.once(_.LEVEL_LOADED,o),s.once(_.AUDIO_TRACK_LOADED,o),s.once(_.SUBTITLE_TRACK_LOADED,o),s.on(_.MEDIA_ATTACHING,(a,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(_.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,s.trigger(_.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=mP(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=Be.bufferInfo(e,r,0);return this.getAssetTime(s.end)>=n-.02}reachedPlayout(e){const n=this.interstitial.playoutLimit;return this.startOffset+e>=n}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Be.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const n=t-this.startOffset;if(n>0&&n<e)return n}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=n=>delete n.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ba(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const vP=.033;class dj extends on{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);const r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(s=r[n])!=null&&s.event;){var s;n--}return n}findItemIndexAtTime(e,t){const n=this.items;if(n)for(let r=0;r<n.length;r++){let s=n[r];if(t&&t!=="primary"&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return-1}findJumpRestrictedIndex(e,t){const n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){const s=n[r].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var n;if(((n=t[r].event)==null?void 0:n.identifier)===e)return r}return-1}findAssetIndex(e,t){const n=e.assetList,r=n.length;if(r>1)for(let s=0;s<r;s++){const o=n[s];if(!o.error){const a=o.timelineStart;if(t===a||t>a&&(t<a+(o.duration||0)||s===r-1))return s}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const n=t.assetList,r=n[n.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const n=e.main.details,{dateRanges:r}=n,s=this.events,o=this.parseDateRanges(r,{url:n.url},t),a=Object.keys(r),l=s?s.filter(c=>!a.includes(c.identifier)):[];o.length&&o.sort((c,u)=>{const d=c.cue.pre,h=c.cue.post,f=u.cue.pre,p=u.cue.post;if(d&&!f)return-1;if(f&&!d||h&&!p)return 1;if(p&&!h)return-1;if(!d&&!f&&!h&&!p){const g=c.startTime,m=u.startTime;if(g!==m)return g-m}return c.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,l.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],n=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const s=this.items,o=this.parseSchedule(r,e);(n||t.length||(s==null?void 0:s.length)!==o.length||o.some((l,c)=>Math.abs(l.playout.start-s[c].playout.start)>.005||Math.abs(l.playout.end-s[c].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,n){const r=[],s=Object.keys(e);for(let o=0;o<s.length;o++){const a=s[o],l=e[a];if(l.isInterstitial){let c=this.eventMap[a];c?c.setDateRange(l):(c=new lj(l,t),this.eventMap[a]=c,n===!1&&(c.appendInPlace=n)),r.push(c)}}return r}parseSchedule(e,t){const n=[],r=t.main.details,s=r.live?1/0:r.edge;let o=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,c=0;if(e.forEach((u,d)=>{const h=u.cue.pre,f=u.cue.post,p=e[d-1]||null,g=u.appendInPlace,m=f?s:u.startOffset,v=u.duration,y=u.timelineOccupancy===xh.Range?v:0,S=u.resumptionOffset,x=(p==null?void 0:p.startTime)===m,E=m+u.cumulativeDuration;let C=g?E+v:m+S;if(h||!f&&m<=0){const I=c;c+=y,u.timelineStart=E;const D=o;o+=v,n.push({event:u,start:E,end:C,playout:{start:D,end:o},integrated:{start:I,end:c}})}else if(m<=s){if(!x){const P=m-l;if(P>vP){const k=l,N=c;c+=P;const B=o;o+=P;const K={previousEvent:e[d-1]||null,nextEvent:u,start:k,end:k+P,playout:{start:B,end:o},integrated:{start:N,end:c}};n.push(K)}else P>0&&p&&(p.cumulativeDuration+=P,n[n.length-1].end=m)}f&&(C=E),u.timelineStart=E;const I=c;c+=y;const D=o;o+=v,n.push({event:u,start:E,end:C,playout:{start:D,end:o},integrated:{start:I,end:c}})}else return;const b=u.resumeTime;f||b>s?l=s:l=b}),l<s){var a;const u=l,d=c,h=s-l;c+=h;const f=o;o+=h,n.push({previousEvent:((a=n[n.length-1])==null?void 0:a.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:o},integrated:{start:d,end:c}})}this.setDurations(s,o,c)}else n.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return n}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){const n=t.main.details,r=n.live?1/0:n.edge;let s=0,o=-1;e.forEach((a,l)=>{const c=a.cue.pre,u=a.cue.post,d=c?0:u?r:a.startTime;this.updateAssetDurations(a),o===d?a.cumulativeDuration=s:(s=0,o=d),!u&&a.snapOptions.in&&(a.resumeAnchor=so(null,n.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<vP&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const f=pe(a.resumeOffset)?a.resumeOffset:a.duration;s+=f})}primaryCanResumeInPlaceAt(e,t){const n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>wa?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(o=>{const a=t[o].details,l=a.edge;if(n>=l)return this.log(`"${e.identifier}" resumption ${n} past ${o} playlist end ${l}`),!1;const c=so(null,a.fragments,n);if(!c)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const u=o==="audio"?.175:0;return Math.abs(c.start-n)<wa+u||Math.abs(c.end-n)<wa+u?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${o} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let n=0,r=!1,s=!1;for(let o=0;o<e.assetList.length;o++){const a=e.assetList[o],l=t+n;a.startOffset=n,a.timelineStart=l,r||(r=a.duration===null),s||(s=!!a.error);const c=a.error?0:a.duration||0;n+=c}r&&!s?e.duration=Math.max(n,e.duration):e.duration=n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function _n(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class hj{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const n=e.assetListUrl;let r;try{r=mP(n,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,W.ASSET_LIST_LOAD_ERROR,h,n);this.hls.trigger(_.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,o=s.loader,a=new o(s),l={responseType:"json",url:r.href},c=s.interstitialAssetListLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,g)=>{const m=h.data,v=m==null?void 0:m.ASSETS;if(!Array.isArray(v)){const y=this.assignAssetListError(e,W.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),p.url,f,g);this.hls.trigger(_.ERROR,y);return}e.assetListResponse=m,this.hls.trigger(_.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:g})},onError:(h,f,p,g)=>{const m=this.assignAssetListError(e,W.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,g,p);this.hls.trigger(_.ERROR,m)},onTimeout:(h,f,p)=>{const g=this.assignAssetListError(e,W.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,p);this.hls.trigger(_.ERROR,g)}};return a.load(l,u,d),this.hls.trigger(_.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,n,r,s,o){return e.error=n,{type:we.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:o,stats:s}}}function yP(i){i==null||i.play().catch(()=>{})}function Th(i,e){return`[${i}] Advancing timeline position to ${e}`}class fj extends on{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const r=n-this.timelinePos;if(Math.abs(r)<1/7056e5)return;const o=r<=-.01;this.timelinePos=n,this.bufferedPos=n;const a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(n,n-r)&&this.updateSchedule(!0),this.checkBuffer(),o&&n<a.start||n>=a.end){var l;const f=this.findItemIndex(a);let p=this.schedule.findItemIndexAtTime(n);if(p===-1&&(p=f+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${n} (resolving from ${f} to ${p})`)),!this.isInterstitial(a)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!o&&p>f){const g=this.schedule.findJumpRestrictedIndex(f+1,p);if(g>f){this.setSchedulePosition(g);return}}this.setSchedulePosition(p);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(a)){const f=a.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,f))}return}const u=c.timelineStart,d=c.duration||0;if(o&&n<u||n>=u+d){var h;(h=a.event)!=null&&h.appendInPlace&&(this.clearInterstitial(a.event,a),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,c)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const r=this.playingItem;if(!r||this.playingLastItem)return;if(n>=r.end){this.timelinePos=r.end;const a=this.findItemIndex(r);this.setSchedulePosition(a+1)}const s=this.playingAsset;if(!s)return;const o=s.timelineStart+(s.duration||0);n>=o&&this.setScheduleToAssetAtTime(n,s)},this.onScheduleUpdate=(n,r)=>{const s=this.schedule;if(!s)return;const o=this.playingItem,a=s.events||[],l=s.items||[],c=s.durations,u=n.map(g=>g.identifier),d=!!(a.length||u.length);(d||r)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
|
|
226
|
+
Schedule: ${l.map(g=>_n(g))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;o&&(h=this.updateItem(o,this.timelinePos),this.itemsMatch(o,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),n.forEach(g=>{g.assetList.forEach(m=>{this.clearAssetPlayer(m.identifier,null)})}),this.playerQueue.forEach(g=>{if(g.interstitial.appendInPlace){const m=g.assetItem.timelineStart,v=g.timelineOffset-m;if(v)try{g.timelineOffset=m}catch(y){Math.abs(v)>wa&&this.warn(`${y} ("${g.assetId}" ${g.timelineOffset}->${m})`)}}}),d||r){if(this.hls.trigger(_.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:l.slice(0),durations:c,removedIds:u}),this.isInterstitial(o)&&u.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(h,o),p&&f!==h&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new hj(e),this.schedule=new dj(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(_.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(_.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(_.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(_.MEDIA_ENDED,this.onMediaEnded,this),e.on(_.ERROR,this.onError,this),e.on(_.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(_.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(_.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(_.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(_.BUFFER_CODECS,this.onBufferCodecs,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(_.MEDIA_ENDED,this.onMediaEnded,this),e.off(_.ERROR,this.onError,this),e.off(_.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ci(e,"play",this.onPlay),Ci(e,"pause",this.onPause),Ci(e,"seeking",this.onSeeking),Ci(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const n=this.media=t.media;mi(n,"seeking",this.onSeeking),mi(n,"timeupdate",this.onTimeupdate),mi(n,"play",this.onPlay),mi(n,"pause",this.onPause)}onMediaAttached(e,t){const n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();const s=this.findItemIndex(n);this.setSchedulePosition(s)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.log(`Removing schedule state for detachedData and ${s}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,n=d=>d&&e.getAssetPlayer(d.identifier),r=(d,h,f,p,g)=>{if(d){let m=d[h].start;const v=d.event;if(v){if(h==="playout"||v.timelineOccupancy!==xh.Point){const y=n(f);(y==null?void 0:y.interstitial)===v&&(m+=y.assetItem.startOffset+y[g])}}else{const y=p==="bufferedPos"?o():e[p];m+=y-d.start}return m}return 0},s=(d,h)=>{var f;if(d!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var p;const g=e.schedule.findItemIndexAtTime(d),m=(p=e.schedule.items)==null?void 0:p[g];if(m){const v=m[h].start-m.start;return d+v}}return d},o=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?a("primary"):Math.max(d,0)},a=d=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},l=(d,h)=>{var f,p;const g=e.effectivePlayingItem;if(g!=null&&(f=g.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const m=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(d,h),y=(p=e.schedule.items)==null?void 0:p[v],S=e.getBufferingPlayer(),x=S==null?void 0:S.interstitial,E=x==null?void 0:x.appendInPlace,C=m&&e.itemsMatch(m,y);if(m&&(E||C)){const b=n(e.playingAsset),I=(b==null?void 0:b.media)||e.primaryMedia;if(I){const D=h==="primary"?I.currentTime:r(m,h,e.playingAsset,"timelinePos","currentTime"),P=d-D,k=(E?D:I.currentTime)+P;if(k>=0&&(!b||E||k<=b.duration)){I.currentTime=k;return}}}if(y){let b=d;if(h!=="primary"){const D=y[h].start,P=d-D;b=y.start+P}const I=!e.isInterstitial(y);if((!e.isInterstitial(m)||m.event.appendInPlace)&&(I||y.event.appendInPlace)){const D=e.media||(E?S==null?void 0:S.media:null);D&&(D.currentTime=b)}else if(m){const D=e.findItemIndex(m);if(v>D){const k=e.schedule.findJumpRestrictedIndex(D+1,v);if(k>D){e.setSchedulePosition(k);return}}let P=0;if(I)e.timelinePos=b,e.checkBuffer();else{const k=y.event.assetList,N=d-(y[h]||y).start;for(let B=k.length;B--;){const K=k[B];if(K.duration&&N>=K.startOffset&&N<K.startOffset+K.duration){P=B;break}}}e.setSchedulePosition(v,P)}}},c=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){const d=t(),h=e.bufferingItem;if(h&&h===d){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const d=c(),h=e.effectivePlayingItem;return h&&h===d?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(d){const h=c(),f=e.effectivePlayingItem;f&&f===h&&l(d+f.playout.start,"playout")},get duration(){const d=c();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const h=(d=c())==null?void 0:d.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;const h=(d=c())==null?void 0:d.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return c()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return o()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){l(d,"primary")},get duration(){return a("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){l(d,"integrated")},get duration(){return a("integrated")},get seekableStart(){var d;return s(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,h=d==null?void 0:d.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(d);if(h.appendInPlace){const p=d.playout.start+d.event.duration;l(p+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,n=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!n?!1:this.findItemIndex(t)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);const s=(t=r)==null?void 0:t.currentTime;if(!(s===void 0||!pe(s)))return s}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){const n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ht(s)}`),this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var n,r;if(e.media===t)return;let s=null;const o=this.hls,a=e!==o,l=a&&e.interstitial.appendInPlace,c=(n=this.detachedData)==null?void 0:n.mediaSource;let u;if(o.media)l&&(s=o.transferMedia(),this.detachedData=s),u="Primary";else if(c){const p=this.getBufferingPlayer();p?(s=p.transferMedia(),u=`${p}`):u="detached MediaSource"}else u="detached media";if(!s){if(c)s=this.detachedData,this.log(`using detachedData: MediaSource ${ht(s)}`);else if(!this.detachedData||o.media===t){const p=this.playerQueue;p.length>1&&p.forEach(g=>{if(a&&g.interstitial.appendInPlace!==l){const m=g.interstitial;this.clearInterstitial(g.interstitial,null),m.appendInPlace=!1,m.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${m}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=s&&"mediaSource"in s&&((r=s.mediaSource)==null?void 0:r.readyState)!=="closed",h=d&&s?s:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(h===s&&f){const p=a&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!a||p,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,r=this.effectivePlayingItem;if(n===-1){const s=this.hls.startPosition;if(this.log(Th("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(s>=0||!this.primaryLive){const o=this.timelinePos=s>0?s:0,a=e.findItemIndexAtTime(o);this.setSchedulePosition(a)}}else if(r&&!this.playingItem){const s=e.findItemIndex(r);this.setSchedulePosition(s)}}advanceAssetBuffering(e,t){const n=e.event,r=n.findAssetIndex(t),s=h0(n,r);if(!n.isAssetPastPlayoutLimit(s))this.bufferedToEvent(e,s);else if(this.schedule){var o;const a=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}advanceAfterAssetEnded(e,t,n){const r=h0(e,n);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){const s=this.schedule.items;if(s){const o=t+1,a=s.length;if(o>=a){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(Th("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const s=e.assetList[r];s&&this.advanceInPlace(s.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){const n=this.schedule;if(!n)return;const r=t.parentIdentifier,s=n.getEvent(r);if(s){const o=n.findEventIndex(r),a=n.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,o,a-1)}}setSchedulePosition(e,t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r||this.playbackDisabled)return;const s=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${s&&_n(s)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(o)){const u=o.event,d=this.playingAsset,h=d==null?void 0:d.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(o,s)||t!==void 0&&h!==u.assetList[t].identifier)){var l;const p=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${u.assetList.length} ${ba(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(_.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:p,event:u,schedule:r.slice(0),scheduleIndex:e,player:f}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(h,s),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(o,s)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${_n(o)}`),u.hasPlayed=!0,this.hls.trigger(_.INTERSTITIAL_ENDED,{event:u,schedule:r.slice(0),scheduleIndex:e}),u.cue.once)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(s&&p){const g=this.findItemIndex(s);this.advanceSchedule(g,p,t,o,a)}return}}this.advanceSchedule(e,r,t,o,a)}advanceSchedule(e,t,n,r,s){const o=this.schedule;if(!o)return;const a=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(u=>{const d=u.interstitial,h=o.findEventIndex(d.identifier);(h<e||h>e+1)&&this.clearInterstitial(d,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const u=a.event;if(n===void 0){n=o.findAssetIndex(u,this.timelinePos);const p=h0(u,n-1);if(u.isAssetPastPlayoutLimit(p)||u.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(u,e,n);return}n=p}const d=this.waitingItem;this.assetsBuffered(a,l)||this.setBufferingItem(a);let h=this.preloadAssets(u,n);if(this.eventItemsMatch(a,d||r)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${_n(a)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(_.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const f=u.assetList[n];if(!f){this.advanceAfterAssetEnded(u,e,n||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const p=u.assetList.length;this.warn(`asset ${n+1}/${p} player destroyed ${u}`),h=this.createAssetPlayer(u,f,n),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,n,t,e,l),this.shouldPlay&&yP(h.media)}else a?(this.resumePrimary(a,e,r),this.shouldPlay&&yP(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(o.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${_n(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Th("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!n)return;const o=(s=this.schedule)==null?void 0:s.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${_n(e)}`),this.hls.trigger(_.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const n=e.start;if(this.primaryLive){const r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(n<r.fragmentStart||n>r.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Be.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(Th("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){var n;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((n=r.mainForwardBufferInfo)==null?void 0:n.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(_.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(_.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const n=this.hls.levels[t.level];if(!n.details)return;const r=rt(rt({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=rt(rt({},this.altSelection),{},{audio:n});return}const s=rt(rt({},r),{},{audio:n});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=rt(rt({},this.altSelection),{},{subtitles:n});return}const s=rt(rt({},r),{},{subtitles:n});this.mediaSelection=s}onAudioTrackSwitching(e,t){const n=vC(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){const n=vC(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(n)))}onBufferCodecs(e,t){const n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){const s=t[r];if(s.cue.post){var n;const o=this.schedule.findEventIndex(s.identifier),a=(n=this.schedule.items)==null?void 0:n[o];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const n=this.findItemIndex(t);this.setSchedulePosition(n+1)}else this.shouldPlay=!1}updateItem(e,t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(e&&r){const s=this.findItemIndex(e,t);return r[s]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((s,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(s.identifier,null)});const n=e.end+.25,r=Be.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${_n(e)} (was ${_n(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var n;return!!t&&(e===t||e.event.identifier===((n=t.event)==null?void 0:n.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const n=this.mediaSelection;n&&((t=this.schedule)==null||t.updateSchedule(n,[],e))}checkBuffer(e){var t;const n=(t=this.schedule)==null?void 0:t.items;if(!n)return;const r=Be.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,n,e)}updateBufferedPos(e,t,n){const r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}const o=this.playingItem,a=this.findItemIndex(o);let l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const u=this.findItemIndex(s),d=Math.min(u+1,t.length-1),h=t[d];if((l===-1&&s&&e>=s.end||(c=h.event)!=null&&c.appendInPlace&&e+.01>=h.start)&&(l=d),this.isInterstitial(s)){const f=s.event;if(d-a>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>a)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else n&&o&&!this.itemsMatch(o,s)&&(l===a?this.bufferedToItem(o):l===a+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{const s=this.getAssetPlayer(r.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){const{items:r,events:s}=n;if(!r||!s)return t;const o=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${_n(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const c=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,d)=>{const h=this.getAssetPlayer(u.identifier);h&&(d===c&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(_.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;const r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),n=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(n)}bufferedToEvent(e,t){const n=e.event,r=n.assetList.length===0&&!n.assetListLoader,s=n.cue.once;if(r||!s){const o=this.preloadAssets(n,t);if(o!=null&&o.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(o,a)}}}preloadAssets(e,t){const n=e.assetUrl,r=e.assetList.length,s=r===0&&!e.assetListLoader,o=e.cue.once;if(s){const l=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const h=u-l;h>0&&(c=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${c?` live-start: ${u} start-offset: ${c}`:""}`),n)return this.createAsset(e,0,0,l,e.duration,n);const d=this.assetListLoader.loadAssetList(e,c);d&&(e.assetListLoader=d)}else if(!o&&r){for(let c=t;c<r;c++){const u=e.assetList[c],d=this.getAssetPlayerQueueIndex(u.identifier);(d===-1||this.playerQueue[d].destroyed)&&!u.error&&this.createAssetPlayer(e,u,c)}const l=e.assetList[t];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(_.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,s,o){const a={parentIdentifier:e.identifier,identifier:aj(e,o,t),duration:s,startOffset:n,timelineStart:r,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,n){const r=this.hls,s=r.userConfig;let o=s.videoPreference;const a=r.loadLevelObj||r.levels[r.currentLevel];(o||a)&&(o=at({},o),a.videoCodec&&(o.videoCodec=a.videoCodec),a.videoRange&&(o.allowedVideoRanges=[a.videoRange]));const l=r.audioTracks[r.audioTrack],c=r.subtitleTracks[r.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const x=this.timelinePos-t.timelineStart;if(x>1){const E=t.duration;E&&x<E&&(u=x)}}const d=t.identifier,h=rt(rt({},s),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||s.audioPreference,subtitlePreference:c||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=at({},f,{contentId:dc(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const p=new uj(this.HlsPlayerClass,h,e,t);this.playerQueue.push(p),e.assetList[n]=t;let g=!0;const m=x=>{if(x.live){var E;const I=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:we.OTHER_ERROR,details:W.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},P=((E=this.schedule)==null?void 0:E.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,P,n,I.message);return}const C=x.edge-x.fragmentStart,b=t.duration;(g||b===null||C>b)&&(g=!1,this.log(`Interstitial asset "${d}" duration change ${b} > ${C}`),t.duration=C,this.updateSchedule())};p.on(_.LEVEL_UPDATED,(x,{details:E})=>m(E)),p.on(_.LEVEL_PTS_UPDATED,(x,{details:E})=>m(E)),p.on(_.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(x,E)=>{const C=this.getAssetPlayer(d);if(C&&E.tracks){C.off(_.BUFFER_CODECS,v),C.tracks=E.tracks;const b=this.primaryMedia;this.bufferingAsset===C.assetItem&&b&&!C.media&&this.bufferAssetPlayer(C,b)}};p.on(_.BUFFER_CODECS,v);const y=()=>{var x;const E=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${E}`),!E||!this.schedule)return;const C=this.schedule.findEventIndex(e.identifier),b=(x=this.schedule.items)==null?void 0:x[C];this.isInterstitial(b)&&this.advanceAssetBuffering(b,t)};p.on(_.BUFFERED_TO_END,y);const S=x=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const C=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,C,x)};return p.once(_.MEDIA_ENDED,S(n)),p.once(_.PLAYOUT_LIMIT_REACHED,S(1/0)),p.on(_.ERROR,(x,E)=>{if(!this.schedule)return;const C=this.getAssetPlayer(d);if(E.details===W.BUFFER_STALLED_ERROR){if(C!=null&&C.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(E,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${E.error} ${e}`)}),p.on(_.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const E=new Error(`Asset player destroyed unexpectedly ${d}`),C={fatal:!0,type:we.OTHER_ERROR,details:W.INTERSTITIAL_ASSET_ITEM_ERROR,error:E};this.handleAssetItemError(C,e,this.schedule.findEventIndex(e.identifier),n,E.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ba(t)}`),this.hls.trigger(_.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:p}),p}clearInterstitial(e,t){e.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,t)}),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){const n=this.getAssetPlayerQueueIndex(e);if(n!==-1){const r=this.playerQueue[n];this.log(`clear ${r} toSegment: ${t&&_n(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(n,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,s){const{interstitial:o,assetItem:a,assetId:l}=e,c=o.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,n[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${ba(a)}`),this.hls.trigger(_.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var n,r;if(!this.schedule)return;const{interstitial:s,assetItem:o}=e,a=this.schedule.findEventIndex(s.identifier),l=(n=this.schedule.items)==null?void 0:n[a];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=o;const c=this.getBufferingPlayer();if(c===e)return;const u=s.appendInPlace;if(u&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const d=(c==null?void 0:c.tracks)||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(u&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!WR(d,e.tracks)){const h=new Error(`Asset ${ba(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:we.OTHER_ERROR,details:W.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},p=s.findAssetIndex(o);this.handleAssetItemError(f,s,a,p,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,n=this.primaryMedia;if(!t||!n)return;const r=n.currentTime,s=t.findAssetIndex(e,r),o=e.assetList[s];if(o){const a=this.getAssetPlayer(o.identifier);if(a){const l=a.currentTime||r-o.timelineStart,c=a.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${a} ${e} (media.currentTime: ${r})`),l&&(c/n.playbackRate<.5||a.bufferedInPlaceToEnd(n))&&a.hls){const u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,s)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,n,r,s){if(e.details===W.BUFFER_STALLED_ERROR)return;const o=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o&&ba(o)} ${e.error}`),!this.schedule)return;const a=(o==null?void 0:o.identifier)||"",l=this.getAssetPlayerQueueIndex(a),c=this.playerQueue[l]||null,u=this.schedule.items,d=at({},e,{fatal:!1,errorAction:ma(!0),asset:o,assetListIndex:r,event:t,schedule:u,scheduleIndex:n,player:c});if(this.hls.trigger(_.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,p=new Error(s);if(o&&(this.clearAssetPlayer(a,null),o.error=p),!t.assetList.some(g=>!g.error))t.error=p;else for(let g=r;g<t.assetList.length;g++)this.resetAssetPlayer(t.assetList[g].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,n,r):f&&f.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,n=this.effectivePlayingItem;if(n){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${_n(n)} error: ${e.error}`);let r=this.timelinePos;r===-1&&(r=this.hls.startPosition);const s=this.updateItem(n,r);if(this.itemsMatch(n,s)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const o=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(o)}else this.checkStart()}onAssetListLoaded(e,t){var n,r;const s=t.event,o=s.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(o)))return;const l=s.timelineStart,c=s.duration;let u=0;a.forEach((g,m)=>{const v=parseFloat(g.DURATION);this.createAsset(s,m,u,l+u,v,g.URI),u+=v}),s.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${c}) ${s}`);const d=this.waitingItem,h=(d==null?void 0:d.event.identifier)===o;this.updateSchedule();const f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var p;const g=this.schedule.findEventIndex(o),m=(p=this.schedule.items)==null?void 0:p[g];if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){s.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${s}`),this.updateSchedule(!0),this.primaryFallback(s);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if((f==null?void 0:f.identifier)===o){const g=s.assetList[0];if(g){const m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){const v=this.primaryMedia;m&&v&&this.bufferAssetPlayer(m,v)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case W.ASSET_LIST_PARSING_ERROR:case W.ASSET_LIST_LOAD_ERROR:case W.ASSET_LIST_LOAD_TIMEOUT:{const n=t.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case W.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const SP=500;class xP extends sh{constructor(e,t,n){super(e,t,n,"subtitle-stream-controller",ve.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(_.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(_.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(_.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(_.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=J.IDLE,this.setInterval(SP),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:n,success:r}=t;if(this.fragContextChanged(n)||(Ft(n)&&(this.fragPrevious=n),this.state=J.IDLE),!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let o;const a=n.start;for(let c=0;c<s.length;c++)if(a>=s[c].start&&a<=s[c].end){o=s[c];break}const l=n.start+n.duration;o?o.end=l:(o={start:a,end:l},s.push(o)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:n,endOffset:r}=t;if(n===0&&r!==Number.POSITIVE_INFINITY){const s=r-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=s){o.shift();continue}else if(o[a].start<s)o[a].start=s;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(n,s,ve.SUBTITLE)}}onError(e,t){const n=t.frag;(n==null?void 0:n.type)===ve.SUBTITLE&&(t.details===W.FRAG_GAP&&this.fragmentTracker.fragBuffered(n,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==J.STOPPED&&(this.state=J.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&zI(this.levels,t)){this.levels=t.map(n=>new ga(n));return}this.tracksBuffered=[],this.levels=t.map(n=>{const r=new ga(n);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ve.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==J.STOPPED&&this.setInterval(SP)}onSubtitleTrackLoaded(e,t){var n;const{currentTrackId:r,levels:s}=this,{details:o,id:a}=t;if(!s){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=s[a];if(a>=s.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(o.live||(n=l.details)!=null&&n.live){if(o.deltaUpdateFailed)return;const d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const h=d.fragments[0];if(!l.details)o.hasProgramDateTime&&d.hasProgramDateTime?(rh(o,d),c=o.fragmentStart):h&&(c=h.start,zv(o,c));else{var u;c=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&h&&(c=h.start,zv(o,c))}d&&!this.startFragRequested&&this.setStartPosition(d,c)}l.details=o,this.levelLastLoaded=l,a===r&&(this.hls.trigger(_.SUBTITLE_TRACK_UPDATED,{details:o,id:a,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===J.IDLE&&(so(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:n}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r!=null&&r.key&&r.iv&&ya(r.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,Ov(r.method)).catch(a=>{throw s.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const l=performance.now();s.trigger(_.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=J.IDLE})}}doTick(){if(!this.media){this.state=J.IDLE;return}if(this.state===J.IDLE){const{currentTrackId:e,levels:t}=this,n=t==null?void 0:t[e];if(!n||!t.length||!n.details||this.waitForLive(n))return;const{config:r}=this,s=this.getLoadPosition(),o=Be.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:l}=o,c=n.details,u=this.hls.maxBufferLength+c.levelTargetDuration;if(l>u)return;const d=c.fragments,h=d.length,f=c.edge;let p=null;const g=this.fragPrevious;if(a<f){const y=r.maxFragLookUpTolerance,S=a>f-y?0:y;p=so(g,d,Math.max(d[0].start,a),S),!p&&g&&g.start<d[0].start&&(p=d[0])}else p=d[h-1];if(p=this.filterReplacedPrimary(p,n.details),!p)return;const m=p.sn-c.startSN,v=d[m-1];if(v&&v.cc===p.cc&&this.fragmentTracker.getState(v)===Ht.NOT_LOADED&&(p=v),this.fragmentTracker.getState(p)===Ht.NOT_LOADED){const y=this.mapToInitFragWhenRequired(p);y&&this.loadFragment(y,n,a)}}}loadFragment(e,t,n){Ft(e)?super.loadFragment(e,t,n):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new pj(this.tracksBuffered[this.currentTrackId]||[])}}class pj{constructor(e){this.buffered=void 0;const t=(n,r,s)=>{if(r=r>>>0,r>s-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${s})`);return e[r][n]};this.buffered={get length(){return e.length},end(n){return t("end",n,e.length)},start(n){return t("start",n,e.length)}}}}const gj={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},TP=i=>String.fromCharCode(gj[i]||i),An=15,Ar=100,mj={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},vj={17:2,18:4,21:6,22:8,23:10,19:13,20:15},yj={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sj={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xj=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Tj{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const n=typeof t=="function"?t():t;st.log(`${this.time} [${e}] ${n}`)}}}const lo=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t};class EP{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let n=0;n<t.length;n++){const r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ej{constructor(){this.uchar=" ",this.penState=new EP}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class wj{constructor(e){this.chars=[],this.pos=0,this.currPenState=new EP,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ar;t++)this.chars.push(new Ej);this.logger=e}equals(e){for(let t=0;t<Ar;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ar;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ar;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ar&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ar)}moveCursor(e){const t=this.pos+e;if(e>1)for(let n=this.pos+1;n<t+1;n++)this.chars[n].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=TP(e);if(this.pos>=Ar){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Ar;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let n=0;n<Ar;n++){const r=this.chars[n].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class f0{constructor(e){this.rows=[],this.currRow=An-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<An;t++)this.rows.push(new wj(e));this.logger=e}reset(){for(let e=0;e<An;e++)this.rows[e].clear();this.currRow=An-1}equals(e){let t=!0;for(let n=0;n<An;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<An;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<An;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ht(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<An;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[s].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(o.rows[s+c])}}this.currRow=t;const n=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,o=Math.max(s-1,0);n.setCursor(e.indent),e.color=n.chars[o].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ht(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let n="",r=-1;for(let s=0;s<An;s++){const o=this.rows[s].getTextString();o&&(r=s+1,e?t.push("Row "+r+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?n="["+t.join(" | ")+"]":n=t.join(`
|
|
227
|
+
`)),n}getTextAndFormat(){return this.rows}}class wP{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new f0(n),this.nonDisplayedMemory=new f0(n),this.lastOutputScreen=new f0(n),this.currRollUpRow=this.displayedMemory.rows[An-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[An-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let n=0;n<e.length;n++)this.writeScreen.insertChar(e[n]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const n=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[n]}this.logger.log(2,"MIDROW: "+ht(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class bP{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=_j(),this.logger=void 0;const r=this.logger=new Tj;this.channels=[null,new wP(e,t,r),new wP(e+1,n,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let n=0;n<t.length;n+=2){const r=t[n]&127,s=t[n+1]&127;let o=!1,a=null;if(r===0&&s===0)continue;this.logger.log(3,()=>"["+lo([t[n],t[n+1]])+"] -> ("+lo([r,s])+")");const l=this.cmdHistory;if(r>=16&&r<=31){if(bj(r,s,l)){Eh(null,null,l),this.logger.log(3,()=>"Repeated command ("+lo([r,s])+") is dropped");continue}Eh(r,s,this.cmdHistory),o=this.parseCmd(r,s),o||(o=this.parseMidrow(r,s)),o||(o=this.parsePAC(r,s)),o||(o=this.parseBackgroundAttributes(r,s))}else Eh(null,null,l);if(!o&&(a=this.parseChars(r,s),a)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+lo([r,s])+" orig: "+lo([t[n],t[n+1]]))}}parseCmd(e,t){const n=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(n||r))return!1;const s=e===20||e===21||e===23?1:2,o=this.channels[s];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+lo([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let n;const r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(e===16||e===24)&&t>=64&&t<=95;if(!(r||s))return!1;const o=e<=23?1:2;t>=64&&t<=95?n=o===1?mj[e]:yj[e]:n=o===1?vj[e]:Sj[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(n,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let n;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?n=t-96:n=t-64,r.underline=(n&1)===1,n<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,s=null;if(e>=25?(n=2,s=e-8):(n=1,s=e),s>=17&&s<=19){let o;s===17?o=t+80:s===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+TP(o)+"' in channel "+n),r=[o]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+lo(r).join(",")),r}parseBackgroundAttributes(e,t){const n=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(n||r))return!1;let s;const o={};e===16||e===24?(s=Math.floor((t-32)/2),o.background=xj[s],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Eh(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const n=this.channels[t];n&&n.cueSplitAtTime(e)}}}function Eh(i,e,t){t.a=i,t.b=e}function bj(i,e,t){return t.a===i&&t.b===e}function _j(){return{a:null,b:null}}var p0=function(){if(th!=null&&th.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,l){if(typeof l!="string"||!Array.isArray(a))return!1;const c=l.toLowerCase();return~a.indexOf(c)?c:!1}function n(a){return t(i,a)}function r(a){return t(e,a)}function s(a,...l){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const d in u)a[d]=u[d]}return a}function o(a,l,c){const u=this,d={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,p=a,g=l,m=c,v=null,y="",S=!0,x="auto",E="start",C=50,b="middle",I=50,D="middle";Object.defineProperty(u,"id",s({},d,{get:function(){return h},set:function(P){h=""+P}})),Object.defineProperty(u,"pauseOnExit",s({},d,{get:function(){return f},set:function(P){f=!!P}})),Object.defineProperty(u,"startTime",s({},d,{get:function(){return p},set:function(P){if(typeof P!="number")throw new TypeError("Start time must be set to a number.");p=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",s({},d,{get:function(){return g},set:function(P){if(typeof P!="number")throw new TypeError("End time must be set to a number.");g=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",s({},d,{get:function(){return m},set:function(P){m=""+P,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},d,{get:function(){return v},set:function(P){v=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},d,{get:function(){return y},set:function(P){const k=n(P);if(k===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},d,{get:function(){return S},set:function(P){S=!!P,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},d,{get:function(){return x},set:function(P){if(typeof P!="number"&&P!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",s({},d,{get:function(){return E},set:function(P){const k=r(P);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");E=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",s({},d,{get:function(){return C},set:function(P){if(P<0||P>100)throw new Error("Position must be between 0 and 100.");C=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},d,{get:function(){return b},set:function(P){const k=r(P);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");b=k,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",s({},d,{get:function(){return I},set:function(P){if(P<0||P>100)throw new Error("Size must be between 0 and 100.");I=P,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",s({},d,{get:function(){return D},set:function(P){const k=r(P);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");D=k,this.hasBeenReset=!0}})),u.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class Aj{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function _P(i){function e(n,r,s,o){return(n|0)*3600+(r|0)*60+(s|0)+parseFloat(o||0)}const t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Rj{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}}function AP(i,e,t,n){const r=n?i.split(n):[i];for(const s in r){if(typeof r[s]!="string")continue;const o=r[s].split(t);if(o.length!==2)continue;const a=o[0],l=o[1];e(a,l)}}const g0=new p0(0,0,""),wh=g0.align==="middle"?"middle":"center";function Cj(i,e,t){const n=i;function r(){const a=_P(i);if(a===null)throw new Error("Malformed timestamp: "+n);return i=i.replace(/^[^\sa-zA-Z-]+/,""),a}function s(a,l){const c=new Rj;AP(a,function(h,f){let p;switch(h){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===f){c.set(h,t[g].region);break}break;case"vertical":c.alt(h,f,["rl","lr"]);break;case"line":p=f.split(","),c.integer(h,p[0]),c.percent(h,p[0])&&c.set("snapToLines",!1),c.alt(h,p[0],["auto"]),p.length===2&&c.alt("lineAlign",p[1],["start",wh,"end"]);break;case"position":p=f.split(","),c.percent(h,p[0]),p.length===2&&c.alt("positionAlign",p[1],["start",wh,"end","line-left","line-right","auto"]);break;case"size":c.percent(h,f);break;case"align":c.alt(h,f,["start",wh,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&g0.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",wh);let d=c.get("position","auto");d==="auto"&&g0.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function o(){i=i.replace(/^\s+/,"")}if(o(),e.startTime=r(),o(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);i=i.slice(3),o(),e.endTime=r(),o(),s(i,e)}function RP(i){return i.replace(/<br(?: \/)?>/gi,`
|
|
228
|
+
`)}class Ij{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Aj,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function n(){let s=t.buffer,o=0;for(s=RP(s);o<s.length&&s[o]!=="\r"&&s[o]!==`
|
|
229
|
+
`;)++o;const a=s.slice(0,o);return s[o]==="\r"&&++o,s[o]===`
|
|
230
|
+
`&&++o,t.buffer=s.slice(o),a}function r(s){AP(s,function(o,a){},/:/)}try{let s="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;s=n();const a=s.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:s=n(),t.state){case"HEADER":/:/.test(s)?r(s):s||(t.state="ID");continue;case"NOTE":s||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){t.state="NOTE";break}if(!s)continue;if(t.cue=new p0(0,0,""),t.state="CUE",s.indexOf("-->")===-1){t.cue.id=s;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Cj(s,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=s.indexOf("-->")!==-1;if(!s||a&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
|
|
231
|
+
`),t.cue.text+=s}continue;case"BADCUE":s||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
|
|
232
|
+
|
|
233
|
+
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Pj=/\r\n|\n\r|\n|\r/g,m0=function(e,t,n=0){return e.slice(n,n+t.length)===t},Lj=function(e){let t=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!pe(t)||!pe(n)||!pe(r)||!pe(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=60*1e3*r,t+=60*60*1e3*s,t};function v0(i,e,t){return dc(i.toString())+dc(e.toString())+dc(t)}const kj=function(e,t,n){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(o=s)!=null&&o.new;){var o;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=n};function Dj(i,e,t,n,r,s,o){const a=new Ij,l=Vi(new Uint8Array(i)).trim().replace(Pj,`
|
|
234
|
+
`).split(`
|
|
235
|
+
`),c=[],u=e?XG(e.baseTime,e.timescale):0;let d="00:00.000",h=0,f=0,p,g=!0;a.oncue=function(m){const v=t[n];let y=t.ccOffset;const S=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?y=t.ccOffset=v.start:kj(t,n,S)),S){if(!e){p=new Error("Missing initPTS for VTT MPEGTS");return}y=S-t.presentationOffset}const x=m.endTime-m.startTime,E=Gi((m.startTime+y-f)*9e4,r*9e4)/9e4;m.startTime=Math.max(E,0),m.endTime=Math.max(E+x,0);const C=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(C)),m.id||(m.id=v0(m.startTime,m.endTime,C)),m.endTime>0&&c.push(m)},a.onparsingerror=function(m){p=m},a.onflush=function(){if(p){o(p);return}s(c)},l.forEach(m=>{if(g)if(m0(m,"X-TIMESTAMP-MAP=")){g=!1,m.slice(16).split(",").forEach(v=>{m0(v,"LOCAL:")?d=v.slice(6):m0(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=Lj(d)/1e3}catch(v){p=v}return}else m===""&&(g=!1);a.parse(m+`
|
|
236
|
+
`)}),a.flush()}const y0="stpp.ttml.im1t",CP=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,IP=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oj={left:"start",center:"center",right:"end",start:"start",end:"end"};function PP(i,e,t,n){const r=We(new Uint8Array(i),["mdat"]);if(r.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const s=r.map(a=>Vi(a)),o=YG(e.baseTime,1,e.timescale);try{s.forEach(a=>t(Mj(a,o)))}catch(a){n(a)}}function Mj(i,e){const r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(s).reduce((d,h)=>(d[h]=r.getAttribute(`ttp:${h}`)||s[h],d),{}),a=r.getAttribute("xml:space")!=="preserve",l=LP(S0(r,"styling","style")),c=LP(S0(r,"layout","region")),u=S0(r,"body","[begin]");return[].map.call(u,d=>{const h=kP(d,a);if(!h||!d.hasAttribute("begin"))return null;const f=T0(d.getAttribute("begin"),o),p=T0(d.getAttribute("dur"),o);let g=T0(d.getAttribute("end"),o);if(f===null)throw DP(d);if(g===null){if(p===null)throw DP(d);g=f+p}const m=new p0(f-e,g-e,h);m.id=v0(m.startTime,m.endTime,m.text);const v=c[d.getAttribute("region")],y=l[d.getAttribute("style")],S=Fj(v,y,l),{textAlign:x}=S;if(x){const E=Oj[x];E&&(m.lineAlign=E),m.align=x}return at(m,S),m}).filter(d=>d!==null)}function S0(i,e,t){const n=i.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(t)):[]}function LP(i){return i.reduce((e,t)=>{const n=t.getAttribute("xml:id");return n&&(e[n]=t),e},{})}function kP(i,e){return[].slice.call(i.childNodes).reduce((t,n,r)=>{var s;return n.nodeName==="br"&&r?t+`
|
|
237
|
+
`:(s=n.childNodes)!=null&&s.length?kP(n,e):e?t+n.textContent.trim().replace(/\s+/g," "):t+n.textContent},"")}function Fj(i,e,t){const n="http://www.w3.org/ns/ttml#styling";let r=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(r=t[o]),s.reduce((a,l)=>{const c=x0(e,n,l)||x0(i,n,l)||x0(r,n,l);return c&&(a[l]=c),a},{})}function x0(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function DP(i){return new Error(`Could not parse ttml timestamp ${i}`)}function T0(i,e){if(!i)return null;let t=_P(i);return t===null&&(CP.test(i)?t=Nj(i,e):IP.test(i)&&(t=Bj(i,e))),t}function Nj(i,e){const t=CP.exec(i),n=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+n/e.frameRate}function Bj(i,e){const t=IP.exec(i),n=Number(t[1]);switch(t[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}class bh{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class OP{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=NP(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(_.FRAG_LOADING,this.onFragLoading,this),e.on(_.FRAG_LOADED,this.onFragLoaded,this),e.on(_.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(_.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(_.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(_.FRAG_LOADING,this.onFragLoading,this),e.off(_.FRAG_LOADED,this.onFragLoaded,this),e.off(_.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(_.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(_.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(_.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new bh(this,"textTrack1"),t=new bh(this,"textTrack2"),n=new bh(this,"textTrack3"),r=new bh(this,"textTrack4");this.cea608Parser1=new bP(1,e,t),this.cea608Parser2=new bP(3,n,r)}addCues(e,t,n,r,s){let o=!1;for(let a=s.length;a--;){const l=s[a],c=Uj(l[0],l[1],t,n);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],n),o=!0,c/(n-t)>.5))return}if(o||s.push([t,n]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,n,r)}else{const a=this.Cues.newCue(null,t,n,r);this.hls.trigger(_.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:s,trackId:o}){const{unparsedVttFrags:a}=this;n===ve.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:s,trackId:o}),a.length&&(this.unparsedVttFrags=[],a.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(_.FRAG_LOADED,l):this.hls.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:n}=this;if(n)for(let r=0;r<n.textTracks.length;r++){const s=n.textTracks[r];if(FP(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:n,media:r}=this,{label:s,languageCode:o}=t[e],a=this.getExistingTrack(s,o);if(a)n[e]=a,Ea(n[e]),fP(n[e],r);else{const l=this.createTextTrack("captions",s,o);l&&(l[e]=!0,n[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const n=t.label,r={_id:e,label:n,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(_.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,n){const r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const n=!!t.transferMedia;if(this.media=null,n)return;const{captionsTracks:r}=this;Object.keys(r).forEach(s=>{Ea(r[s]),delete r[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=NP(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let n=0;n<t.length;n++)Ea(t[n])}onSubtitleTracksUpdated(e,t){const n=t.subtitleTracks||[],r=n.some(s=>s.textCodec===y0);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(zI(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const o=this.media,a=o?Sh(o.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(a){let d=null;for(let h=0;h<a.length;h++)if(a[h]&&FP(a[h],l)){d=a[h],a[h]=null;break}d&&(u=d)}if(u)Ea(u);else{const d=MP(l);u=this.createTextTrack(d,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),a!=null&&a.length){const l=a.filter(c=>c!==null).map(c=>c.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(_.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(n=>{const r=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!r)return;const s=`textTrack${r[1]}`,o=this.captionsProperties[s];o&&(o.label=n.name,n.lang&&(o.languageCode=n.lang),o.media=n)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ve.MAIN){var n,r;const{cea608Parser1:s,cea608Parser2:o,lastSn:a}=this,{cc:l,sn:c}=t.frag,u=(n=(r=t.part)==null?void 0:r.index)!=null?n:-1;s&&o&&(c!==a+1||c===a&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),o.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:n,payload:r}=t;if(n.type===ve.SUBTITLE)if(r.byteLength){const s=n.decryptdata,o="stats"in t;if(s==null||!s.encrypted||o){const a=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),a&&a.textCodec===y0?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const n=this.hls;PP(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),n.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{n.logger.log(`Failed to parse IMSC1: ${r}`),n.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;const{frag:n,payload:r}=e,{initPTS:s,unparsedVttFrags:o}=this,a=s.length-1;if(!s[n.cc]&&a===-1){o.push(e);return}const l=this.hls,c=(t=n.initSegment)!=null&&t.data?an(n.initSegment.data,new Uint8Array(r)).buffer:r;Dj(c,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,u=>{this._appendCues(u,n.level),l.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},u=>{const d=u.message==="Missing initPTS for VTT MPEGTS";d?o.push(e):this._fallbackToIMSC1(n,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(d&&a>n.cc)&&l.trigger(_.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:u})})}_fallbackToIMSC1(e,t){const n=this.tracks[e.level];n.textCodec||PP(t,this.initPTS[e.cc],()=>{n.textCodec=y0,this._parseIMSC1(e,t)},()=>{n.textCodec="wvtt"})}_appendCues(e,t){const n=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(s=>pP(r,s))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;n.trigger(_.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:n}=t;n.type===ve.SUBTITLE&&this.onFragLoaded(_.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:r}=t;if(!(n.type===ve.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let s=0;s<r.length;s++){const o=r[s].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(o);this.cea608Parser1.addData(r[s].pts,a[0]),this.cea608Parser2.addData(r[s].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:s}){const{media:o}=this;if(!(!o||o.currentTime<n)){if(!s||s==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>u0(a[l],t,n))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>u0(a[l],t,r))}}}extractCea608Data(e){const t=[[],[]],n=e[0]&31;let r=2;for(let s=0;s<n;s++){const o=e[r++],a=127&e[r++],l=127&e[r++];if(a===0&&l===0)continue;if((4&o)!==0){const u=3&o;(u===0||u===1)&&(t[u].push(a),t[u].push(l))}}return t}}function MP(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function FP(i,e){return!!i&&i.kind===MP(e)&&n0(e,i)}function Uj(i,e,t,n){return Math.min(e,n)-Math.max(i,t)}function NP(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const $j=/\s/,BP={newCue(i,e,t,n){const r=[];let s,o,a,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(s=n.rows[h],a=!0,l=0,c="",!s.isEmpty()){var d;for(let g=0;g<s.chars.length;g++)$j.test(s.chars[g].uchar)&&a?l++:(c+=s.chars[g].uchar,a=!1);s.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=RP(c.trim()),p=v0(e,t,f);i!=null&&(d=i.cues)!=null&&d.getCueById(p)||(o=new u(e,t,f),o.id=p,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(o))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>pP(i,h))),r}};function UP(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Hj=/(\d+)-(\d+)\/(\d+)/;class E0{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Wj,this.controller=new self.AbortController,this.stats=new Ud}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=zj(e,this.controller.signal),o=e.responseType==="arraybuffer",a=o?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&pe(l)?l:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(cc(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var h;this.response=this.loader=d;const f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},c-(f-r.loading.start)),!d.ok){const{status:g,statusText:m}=d;throw new jj(m||"fetch, bad network response",g,d)}r.loading.first=f,r.total=Gj(d.headers)||r.total;const p=(h=this.callbacks)==null?void 0:h.onProgress;return p&&pe(t.highWaterMark)?this.loadProgressively(d,r,e,t.highWaterMark,p):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,f;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=d[a];g&&(r.loaded=r.total=g);const m={url:p.url,data:d,code:p.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!pe(t.highWaterMark)&&v(r,e,d,p),(f=this.callbacks)==null||f.onSuccess(m,r,e,p)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const f=d&&d.code||0,p=d?d.message:null;(h=this.callbacks)==null||h.onError({code:f,text:p},e,d?d.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,s){const o=new fI,a=e.body.getReader(),l=()=>a.read().then(c=>{if(c.done)return o.dataLength&&s(t,n,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=c.value,d=u.length;return t.loaded+=d,d<r||o.dataLength?(o.push(u),o.dataLength>=r&&s(t,n,o.flush().buffer,e)):s(t,n,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function zj(i,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(at({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function Vj(i){const e=Hj.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Gj(i){const e=i.get("Content-Range");if(e){const n=Vj(e);if(pe(n))return n}const t=i.get("Content-Length");if(t)return parseInt(t)}function Wj(i,e){return new self.Request(i.url,e)}class jj extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}}const Kj=/^age:\s*[\d.]+\s*$/im;class w0{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ud,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return s(n,t.url)}).catch(o=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",t.url,!0),s(n,t.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(o=>{var a;(a=this.callbacks)==null||a.onError({code:n.status,text:o.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:o}=n.loadPolicy;if(r)for(const a in r)e.setRequestHeader(a,r[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=s&&pe(s)?s:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:n}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const c=t.status,u=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){const p=u??t.response;if(p!=null){var o,a;n.loading.end=Math.max(self.performance.now(),n.loading.first);const g=t.responseType==="arraybuffer"?p.byteLength:p.length;n.loaded=n.total=g,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const m=(o=this.callbacks)==null?void 0:o.onProgress;m&&m(n,e,p,t);const v={url:t.responseURL,data:p,code:c};(a=this.callbacks)==null||a.onSuccess(v,n,e,t);return}}const d=s.loadPolicy.errorRetry,h=n.retry,f={url:e.url,data:void 0,code:c};if(Xd(d,h,!1,f))this.retry(d);else{var l;st.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,n)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Xd(e,t,!0))this.retry(e);else{var n;st.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:n}=this;this.retryDelay=Iv(e,n.retry),n.retry++,st.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Kj.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const qj={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Yj=rt(rt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:w0,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:SC,bufferController:jI,capLevelController:ph,errorController:RC,fpsController:hP,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Bv,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:qj},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Xj()),{},{subtitleStreamController:xP,subtitleTrackController:gP,timelineController:OP,audioStreamController:HI,audioTrackController:VI,emeController:ao,cmcdController:aP,contentSteeringController:lP,interstitialsController:fj});function Xj(){return{cueHandler:BP,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Zj(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=b0(i),r=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(o=>{const a=`${o==="level"?"playlist":o}LoadPolicy`,l=e[a]===void 0,c=[];s.forEach(u=>{const d=`${o}Loading${u}`,h=e[d];if(h!==void 0&&l){c.push(d);const f=n[a].default;switch(e[a]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${a}": ${ht(e[a])}`)}),rt(rt({},n),e)}function b0(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(b0):Object.keys(i).reduce((e,t)=>(e[t]=b0(i[t]),e),{}):i}function Qj(i,e){const t=i.loader;t!==E0&&t!==w0?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):UP()&&(i.loader=E0,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const _h=2,Jj=.1,e9=.05,t9=100;class i9 extends kC{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(t9),this.mediaSource=t.mediaSource;const n=this.media=t.media;mi(n,"playing",this.onMediaPlaying),mi(n,"waiting",this.onMediaWaiting),mi(n,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:n}=this;n&&(Ci(n,"playing",this.onMediaPlaying),Ci(n,"waiting",this.onMediaWaiting),Ci(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var n,r;const s=(n=this.hls)==null?void 0:n.config;if(!s)return;const o=this.media;if(!o)return;const{seeking:a}=o,l=this.seeking&&!a,c=!this.seeking&&a,u=o.paused&&!a||o.ended||o.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!1}));return}if(!Be.getBuffered(o).length){this.nudgeRetry=0;return}const d=Be.bufferInfo(o,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){const C=$P(this.hls.inFlightFragments,e),b=d.len>_h,I=!h||C||h-e>_h&&!f.getPartialFragment(e);if(b||I)return;this.moved=!1}const p=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;const b=Math.max(h,d.start||0)-e,D=!!(p!=null&&p.live)?p.targetduration*2:_h,P=Ah(e,f);if(b>0&&(b<=D||P)){o.paused||this._trySkipBufferHole(P);return}}const g=s.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;let y=this.stalled;if(y===null)if(v>0&&m-v<g)y=this.stalled=v;else{this.stalled=m;return}const S=m-y;if(!a&&(S>=g||v)&&this.hls){var x;if(((x=this.mediaSource)==null?void 0:x.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-((p==null?void 0:p.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(_.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const E=Be.bufferInfo(o,e,s.maxBufferHole);this._tryFixBufferStall(E,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(_.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){const s=Be.bufferedInfo(Be.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const o=Be.timeRangesToArray(r),a=Be.bufferedInfo(o,t,0).bufferedIndex;if(a>-1&&a<o.length-1){const l=Be.bufferedInfo(o,e,0).bufferedIndex,c=o[a].end,u=o[a+1].start;if((l===-1||l>a)&&u-c<1&&e-c<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${u} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=Ah(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=Be.bufferInfo(this.media,e,0);this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,n){var r,s;const{fragmentTracker:o,media:a}=this,l=(r=this.hls)==null?void 0:r.config;if(!a||!o||!l)return;const c=(s=this.hls)==null?void 0:s.latestLevelDetails,u=Ah(n,o);if((u||c!=null&&c.live&&n<c.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const d=e.buffered,h=this.adjacentTraversal(e,n);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-n<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const n=this.fragmentTracker,r=e.nextStart;if(n&&r){const s=n.getFragAtPos(t,ve.MAIN),o=n.getFragAtPos(r,ve.MAIN);if(s&&o)return o.sn-s.sn<2}return!1}_reportStall(e){const{hls:t,media:n,stallReported:r,stalled:s}=this;if(!r&&s!==null&&n&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${ht(e)})`);this.warn(o.message),t.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:n,media:r}=this,s=(t=this.hls)==null?void 0:t.config;if(!r||!n||!s)return 0;const o=r.currentTime,a=Be.bufferInfo(r,o,0),l=o<a.start?a.start:a.nextStart;if(l&&this.hls){const u=a.len<=s.maxBufferHole,d=a.len>0&&a.len<1&&r.readyState<3,h=l-o;if(h>0&&(u||d)){if(h>s.maxBufferHole){let p=!1;if(o===0){const g=n.getAppendedFrag(0,ve.MAIN);g&&l<g.end&&(p=!0)}if(!p&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||$P(this.hls.inFlightFragments,l))return 0;let m=!1,v=e.end;for(;v<l;){const y=Ah(v,n);if(y)v+=y.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(l+e9,o+Jj);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${f}`),g={type:we.MEDIA_ERROR,details:W.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?g.part=e:g.frag=e),this.hls.trigger(_.ERROR,g)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:n,nudgeRetry:r}=this,s=t==null?void 0:t.config;if(!n||!s)return 0;const o=n.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){const a=o+(r+1)*s.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${o} to ${a}`);this.warn(l.message),n.currentTime=a,t.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${o} after ${s.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}}function $P(i,e){const t=HP(i.main);if(t&&t.start<=e)return t;const n=HP(i.audio);return n&&n.start<=e?n:null}function HP(i){if(!i)return null;switch(i.state){case J.IDLE:case J.STOPPED:case J.ENDED:case J.ERROR:return null}return i.frag}function Ah(i,e){return e.getAppendedFrag(i,ve.MAIN)||e.getPartialFragment(i)}const n9=.25;function _0(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function A0(i,e,t,n,r){let s=new i(e,t,"");try{s.value=n,r&&(s.type=r)}catch{s=new i(e,t,ht(r?rt({type:r},n):n))}return s}const Rh=(()=>{const i=_0();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class r9{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(_.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(_.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var n;this.media=t.media,((n=t.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Ea(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const n=e[t];if(n.kind==="metadata"&&n.label==="id3")return fP(n,this.media),n}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=_0();if(o)for(let a=0;a<s.length;a++){const l=s[a].type;if(l===Ii.emsg&&!n||!r)continue;const c=TI(s[a].data),u=s[a].pts;let d=u+s[a].duration;d>Rh&&(d=Rh),d-u<=0&&(d=u+n9);for(let f=0;f<c.length;f++){const p=c[f];if(!EI(p)){this.updateId3CueEnds(u,l);const g=A0(o,u,d,p,l);g&&this.id3Track.addCue(g)}}}}updateId3CueEnds(e,t){var n;const r=(n=this.id3Track)==null?void 0:n.cues;if(r)for(let s=r.length;s--;){const o=r[s];o.type===t&&o.startTime<e&&o.endTime===Rh&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){const{id3Track:s,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(s&&(a||l)){let c;r==="audio"?c=u=>u.type===Ii.audioId3&&l:r==="video"?c=u=>u.type===Ii.emsg&&a:c=u=>u.type===Ii.audioId3&&l||u.type===Ii.emsg&&a,u0(s,t,n,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:r,enableDateRangeMetadataCues:s,interstitialsController:o}=this.hls.config;if(!s)return;const a=_0();if(n&&r&&!o){const{fragmentStart:g,fragmentEnd:m}=e;let v=this.assetCue;v?(v.startTime=g,v.endTime=m):a&&(v=this.assetCue=A0(a,g,m,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,u=Object.keys(c);let d=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){const g=Object.keys(d).filter(m=>!u.includes(m));for(let m=g.length;m--;){var f;const v=g[m],y=(f=d[v])==null?void 0:f.cues;delete d[v],y&&Object.keys(y).forEach(S=>{const x=y[S];if(x){x.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(x)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(u.length===0||!pe(p==null?void 0:p.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let g=0;g<u.length;g++){const m=u[g],v=c[m],y=v.startTime,S=d[m],x=(S==null?void 0:S.cues)||{};let E=(S==null?void 0:S.durationKnown)||!1,C=Rh;const{duration:b,endDate:I}=v;if(I&&b!==null)C=y+b,E=!0;else if(v.endOnNext&&!E){const P=u.reduce((k,N)=>{if(N!==v.id){const B=c[N];if(B.class===v.class&&B.startDate>v.startDate&&(!k||v.startDate<k.startDate))return B}return k},null);P&&(C=P.startTime,E=!0)}const D=Object.keys(v.attr);for(let P=0;P<D.length;P++){const k=D[P];if(!$V(k))continue;const N=x[k];if(N)E&&!(S!=null&&S.durationKnown)?N.endTime=C:Math.abs(N.startTime-y)>.01&&(N.startTime=y,N.endTime=C);else if(a){let B=v.attr[k];HV(k)&&(B=jR(B));const q=A0(a,y,C,{key:k,data:B},Ii.dateRange);q&&(q.id=m,this.id3Track.addCue(q),x[k]=q,o&&(k==="X-ASSET-LIST"||k==="X-ASSET-URL")&&q.addEventListener("enter",this.onEventCueEnter))}}d[m]={cues:x,dateRange:v,durationKnown:E}}}}}class s9{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,n=this.levelDetails;if(!t||!n)return;this.currentTime=t.currentTime;const r=this.computeLatency();if(r===null)return;this._latency=r;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:o}=this.config;if(!s||o===1||!n.live)return;const a=this.targetLatency;if(a===null)return;const l=r-a,c=Math.min(this.maxLatency,a+n.targetduration);if(l<c&&l>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,o)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let c=a&&n||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=s!==void 0?s:o*r);const u=r;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const n=this.levelDetails;if(n===null)return null;const r=n.edge,s=e-t-this.edgeStalled,o=r-n.totalduration,a=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(o,s),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(_.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(_.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(_.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(_.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var n;t.details===W.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var n,r;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class o9 extends fh{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this),e.on(_.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this),e.off(_.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const n=this.hls.config.preferManagedMediaSource,r=[],s={},o={};let a=!1,l=!1,c=!1;t.levels.forEach(u=>{const d=u.attrs;let{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=Wd(h,n)||void 0),f&&(f=u.videoCodec=sV(f));const{width:p,height:g,unknownCodecs:m}=u,v=(m==null?void 0:m.length)||0;if(a||(a=!!(p&&g)),l||(l=!!f),c||(c=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:y,"FRAME-RATE":S,"HDCP-LEVEL":x,"PATHWAY-ID":E,RESOLUTION:C,"VIDEO-RANGE":b}=d,D=`${`${E||"."}-`}${u.bitrate}-${C}-${S}-${y}-${b}-${x}`;if(s[D])if(s[D].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const P=o[D]+=1;u.attrs["PATHWAY-ID"]=new Array(P+1).join(".");const k=this.createLevel(u);s[D]=k,r.push(k)}else s[D].addGroupId("audio",d.AUDIO),s[D].addGroupId("text",d.SUBTITLES);else{const P=this.createLevel(u);s[D]=P,o[D]=1,r.push(P)}}),this.filterAndSortMediaOptions(r,t,a,l,c)}createLevel(e){const t=new ga(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const r=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(r.message),t.supportedResult=dC(r,[])}return t}isAudioSupported(e){return ec(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ec(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,n,r,s){var o;let a=[],l=[],c=e;const u=((o=t.stats)==null?void 0:o.parsing)||{};if((n||r)&&s&&(c=c.filter(({videoCodec:y,videoRange:S,width:x,height:E})=>(!!y||!!(x&&E))&&gV(S))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",S=y;t.levels.length&&(S=`one or more CODECS in variant not supported: ${ht(t.levels.map(E=>E.attrs.CODECS).filter((E,C,b)=>b.indexOf(E)===C))}`,this.warn(S),y+=` (${S})`);const x=new Error(y);this.hls.trigger(_.ERROR,{type:we.MEDIA_ERROR,details:W.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:x,reason:S})}}),u.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),zP(a)),t.subtitles&&(l=t.subtitles,zP(l));const d=c.slice(0);c.sort((y,S)=>{if(y.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&y.height!==S.height)return y.height-S.height;if(y.frameRate!==S.frameRate)return y.frameRate-S.frameRate;if(y.videoRange!==S.videoRange)return Kd.indexOf(y.videoRange)-Kd.indexOf(S.videoRange);if(y.videoCodec!==S.videoCodec){const x=aC(y.videoCodec),E=aC(S.videoCodec);if(x!==E)return E-x}if(y.uri===S.uri&&y.codecSet!==S.codecSet){const x=Gd(y.codecSet),E=Gd(S.codecSet);if(x!==E)return E-x}return y.averageBitrate!==S.averageBitrate?y.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let y=0;y<d.length;y++)if(d[y].pathwayId===c[0].pathwayId){h=d[y];break}}this._levels=c;for(let y=0;y<c.length;y++)if(c[y]===h){var f;this._firstLevel=y;const S=h.bitrate,x=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const E=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);E>x&&x===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const p=s&&!r,g=this.hls.config,m=!!(g.audioStreamController&&g.audioTrackController),v={levels:c,audioTracks:a,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:m&&!p&&a.some(y=>!!y.url)};u.end=performance.now(),this.hls.trigger(_.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:u,reason:u.message}),d)return;e=Math.min(e,t.length-1)}const n=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n===e&&r&&s===a)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${n}${s?" with Pathway "+s:""}`);const l={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(_.LEVEL_SWITCHING,l);const c=o.details;if(!c||c.live){const u=this.switchParams(o.uri,r==null?void 0:r.details,c);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),n=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){t.fatal||!t.context||t.context.type===Ke.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===ve.MAIN){const n=t.elementaryStreams;if(!Object.keys(n).some(s=>!!n[s]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var n;const{level:r,details:s}=t,o=t.levelInfo;if(!o){var a;this.warn(`Invalid level index ${r}`),(a=t.deliveryDirectives)!=null&&a.skip&&(s.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let l=o.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(n=t.deliveryDirectives)!=null&&n.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],o=e.details,a=o==null?void 0:o.age;this.log(`Loading level index ${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${n}`),this.hls.trigger(_.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const n=this._levels.filter((s,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));aI(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(_.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(_.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function zP(i){const e={};i.forEach(t=>{const n=t.groupId||"";t.id=e[n]=e[n]||0,e[n]++})}function VP(){return self.SourceBuffer||self.WebKitSourceBuffer}function R0(){if(!Er())return!1;const e=VP();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function GP(){if(!R0())return!1;const i=Er();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported(tc(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported(tc(e,"audio"))))}function a9(){var i;const e=VP();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}const l9=100;class c9 extends sh{constructor(e,t,n){super(e,t,n,"stream-controller",ve.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const r=this.media,s=r?r.currentTime:null;if(s===null||!pe(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const o=this.getFwdBufferInfoAtPos(r,s,ve.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(_.MANIFEST_PARSED,this.onManifestParsed,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.LEVEL_LOADED,this.onLevelLoaded,this),e.on(_.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(_.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(_.BUFFER_CREATED,this.onBufferCreated,this),e.on(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(_.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(_.MANIFEST_PARSED,this.onManifestParsed,this),e.off(_.LEVEL_LOADED,this.onLevelLoaded,this),e.off(_.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(_.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(_.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(_.BUFFER_CREATED,this.onBufferCreated,this),e.off(_.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(_.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(l9),this.level=-1,!this.startFragRequested){let s=r.startLevel;s===-1&&(r.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=r.firstAutoLevel),r.nextLoadLevel=s,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=J.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=J.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case J.WAITING_LEVEL:{const{levels:e,level:t}=this,n=e==null?void 0:e[t],r=n==null?void 0:n.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=J.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=J.IDLE;break}break}case J.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===J.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[s]))return;const o=n[s],a=this.getMainFwdBufferInfo();if(a===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(_.BUFFER_EOS,g),this.state=J.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const c=o.details;if(!c||this.state===J.WAITING_LEVEL||this.waitForLive(o)){this.level=s,this.state=J.WAITING_LEVEL,this.startFragRequested=!1;return}const u=a.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ft(f)&&this.fragmentTracker.getState(f)!==Ht.OK){var p;const m=((p=this.backtrackFragment)!=null?p:f).sn-c.startSN,v=c.fragments[m-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?dt.AUDIO:dt.VIDEO,v=(m===dt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,m,ve.MAIN)}f=this.getNextFragmentLoopLoading(f,c,a,ve.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,o,h))}loadFragment(e,t,n){const r=this.fragmentTracker.getState(e);r===Ht.NOT_LOADED||r===Ht.PARTIAL?Ft(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,n):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ve.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let n;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<s.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,l=e[a],c=this.fragLastKbps;c&&this.fragCurrent?n=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:n=0}else n=0;const o=this.getBufferedFrag(t.currentTime+n);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,c=a.duration,u=Math.max(o.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case J.KEY_LOADING:case J.FRAG_LOADING:case J.FRAG_LOADING_WAITING_RETRY:case J.PARSING:case J.PARSED:this.state=J.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const n=t.media;mi(n,"playing",this.onMediaPlaying),mi(n,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:n}=this;n&&(Ci(n,"playing",this.onMediaPlaying),Ci(n,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(_.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,r=!1;for(let s=0;s<t.levels.length;s++){const o=t.levels[s].audioCodec;o&&(n=n||o.indexOf("mp4a.40.2")!==-1,r=r||o.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=n&&r&&!a9(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:n}=this;if(!n||this.state!==J.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=J.WAITING_LEVEL)}onLevelLoaded(e,t){var n;const{levels:r,startFragRequested:s}=this,o=t.level,a=t.details,l=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${l}`);const c=t.levelInfo,u=this.fragCurrent;u&&(this.state===J.FRAG_LOADING||this.state===J.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let d=0;if(a.live||(n=c.details)!=null&&n.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,c.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(c.details=a,this.levelLastLoaded=c,s||this.setStartPosition(a,d),this.hls.trigger(_.LEVEL_UPDATED,{details:a,level:o}),this.state===J.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=J.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:n}=this;if(!n)return;const r=this.hls.liveSyncPosition,s=this.getLoadPosition(),o=e.fragmentStart,a=e.edge,l=s>=o-t.maxFragLookUpTolerance&&s<=a;if(r!==null&&n.duration>r&&(s<r||!l)){const u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&n.readyState<4||s<a-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const d=Be.bufferInfo(n,r,0);if(!((c=d.buffered)!=null&&c.length)){n.currentTime=r;return}if(d.start<=s){n.currentTime=r;return}const{nextStart:f}=Be.bufferedInfo(d.buffered,s,0);f&&(n.currentTime=f)}else n.currentTime=r}}_handleFragmentLoadProgress(e){var t;const n=e.frag,{part:r,payload:s}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const a=o[n.level];if(!a){this.warn(`Level ${n.level} not found on progress`);return}const l=a.details;if(!l){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}const c=a.videoCodec,u=l.PTSKnown||!l.live,d=(t=n.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new UI(this.hls,ve.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=r?r.index:-1,g=p!==-1,m=new Qd(n.level,n.sn,n.stats.chunkCount,s.byteLength,p,g),v=this.initPTS[n.cc];f.push(s,d,h,c,n,r,l.totalduration,u,m,v)}onAudioTrackSwitching(e,t){const n=this.hls,r=this.altAudio===2;if(qd(t.url,n))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.fragmentTracker.removeAllFragments(),n.once(_.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(_.AUDIO_TRACK_SWITCHED,t)}),n.trigger(_.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(_.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const n=qd(t.url,this.hls);if(n){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=n?2:0,this.tick()}onBufferCreated(e,t){const n=t.tracks;let r,s,o=!1;for(const a in n){const l=n[a];if(l.id==="main"){if(s=a,r=l,a==="video"){const c=n[a];c&&(this.videoBuffer=c.buffer)}}else o=!0}o&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:n,part:r}=t,s=n.type===ve.MAIN;if(s){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?" p: "+r.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===J.PARSED&&(this.state=J.IDLE);return}const a=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Ft(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}const o=this.media;o&&(!this._hasEnoughToStart&&Be.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var n;if(t.fatal){this.state=J.ERROR;return}switch(t.details){case W.FRAG_GAP:case W.FRAG_PARSING_ERROR:case W.FRAG_DECRYPT_ERROR:case W.FRAG_LOAD_ERROR:case W.FRAG_LOAD_TIMEOUT:case W.KEY_LOAD_ERROR:case W.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ve.MAIN,t);break;case W.LEVEL_LOAD_ERROR:case W.LEVEL_LOAD_TIMEOUT:case W.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===J.WAITING_LEVEL&&((n=t.context)==null?void 0:n.type)===Ke.LEVEL&&(this.state=J.IDLE);break;case W.BUFFER_ADD_CODEC_ERROR:case W.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case W.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case W.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=J.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==dt.AUDIO||!this.altAudio){const n=(t===dt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,t,ve.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}const r=this.timelineOffset;r&&n&&(n+=r);const s=this.getLevelDetails(),o=Be.getBuffered(e),a=o.length?o.start(0):0,l=a-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((s==null?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),n+=l,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${a}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(n=>{const{hls:r}=this,s=n==null?void 0:n.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=J.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=s.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),r.trigger(_.FRAG_LOADED,n),s.bitrateTest=!1}).catch(n=>{this.state===J.STOPPED||this.state===J.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:s}=e,o=this.getCurrentContext(s);if(!o){this.resetWhenMissingContext(s);return}const{frag:a,part:l,level:c}=o,{video:u,text:d,id3:h,initSegment:f}=r,{details:p}=c,g=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=J.PARSING,f){const m=f.tracks;if(m){const x=a.initSegment||a;if(this.unhandledEncryptionError(f,a))return;this._bufferInitSegment(c,m,x,s),n.trigger(_.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:t,tracks:m})}const v=f.initPTS,y=f.timescale,S=this.initPTS[a.cc];if(pe(v)&&(!S||S.baseTime!==v||S.timescale!==y)){const x=f.trackId;this.initPTS[a.cc]={baseTime:v,timescale:y,trackId:x},n.trigger(_.INIT_PTS_FOUND,{frag:a,id:t,initPTS:v,timescale:y,trackId:x})}}if(u&&p){g&&u.type==="audiovideo"&&this.logMuxedErr(a);const m=p.fragments[a.sn-1-p.startSN],v=a.sn===p.startSN,y=!m||a.cc>m.cc;if(r.independent!==!1){const{startPTS:S,endPTS:x,startDTS:E,endDTS:C}=u;if(l)l.elementaryStreams[u.type]={startPTS:S,endPTS:x,startDTS:E,endDTS:C};else if(u.firstKeyFrame&&u.independent&&s.id===1&&!y&&(this.couldBacktrack=!0),u.dropped&&u.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!v&&I<D-this.config.maxBufferHole&&!y){this.backtrack(a);return}else y&&(a.gap=!0);a.setElementaryStreamInfo(u.type,a.start,x,a.start,C,!0)}else v&&S-(p.appliedTimelineOffset||0)>_h&&(a.gap=!0);a.setElementaryStreamInfo(u.type,S,x,E,C),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,l,s,v||y)}else if(v||y)a.gap=!0;else{this.backtrack(a);return}}if(g){const{startPTS:m,endPTS:v,startDTS:y,endDTS:S}=g;l&&(l.elementaryStreams[dt.AUDIO]={startPTS:m,endPTS:v,startDTS:y,endDTS:S}),a.setElementaryStreamInfo(dt.AUDIO,m,v,y,S),this.bufferFragmentData(g,a,l,s)}if(p&&h!=null&&h.samples.length){const m={id:t,frag:a,details:p,samples:h.samples};n.trigger(_.FRAG_PARSING_METADATA,m)}if(p&&d){const m={id:t,frag:a,details:p,samples:d.samples};n.trigger(_.FRAG_PARSING_USERDATA,m)}}logMuxedErr(e){this.warn(`${Ft(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==J.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));const{audio:s,video:o,audiovideo:a}=t;if(s){const c=e.audioCodec;let u=jd(s.codec,c);u==="mp4a"&&(u="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=s.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),c&&c!==u&&this.log(`Swapping manifest audio codec "${c}" for "${u}"`),s.levelCodec=u,s.id=ve.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${u||""}/${c||""}/${s.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=ve.MAIN;const c=o.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${o.codec!==c?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const l=Object.keys(t);if(l.length){if(this.hls.trigger(_.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{const d=t[c].initSegment;d!=null&&d.byteLength&&this.hls.trigger(_.BUFFER_APPENDING,{type:c,data:d,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,ve.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,n=e==null?void 0:e[t];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=J.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(Be.isBuffered(e,n)?t=this.getAppendedFrag(n):Be.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,s=t.level;(!r||t.sn!==r.sn||r.level!==s)&&(this.fragPlaying=t,this.hls.trigger(_.FRAG_CHANGED,{frag:t}),(!r||r.level!==s)&&this.hls.trigger(_.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return pe(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(pe(t)){const n=this.getLevelDetails(),r=this.currentFrag||(n?so(null,n.fragments,t):null);if(r){const s=r.programDateTime;if(s!==null){const o=s+(t-r.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class u9 extends on{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[n].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=W.KEY_LOAD_ERROR,n,r,s){return new wr({type:we.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:n,networkDetails:r})}loadClear(e,t,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,s=t.length;r<s;r++){const o=t[r];if(e.cc<=o.cc&&(!Ft(e)||!Ft(o)||e.sn<o.sn)||!n&&r==s-1)return this.emeController.selectKeySystemFormat(o).then(a=>{if(!this.emeController)return;o.setKeyFormat(a);const l=ih(a);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const r=nc(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var n,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,W.KEY_LOAD_ERROR,c))}const o=s.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,W.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const a=C0(s);let l=this.keyIdToKeyInfo[a];if((n=l)!=null&&n.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{const{keyInfo:d}=u;return s.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+gi(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,W.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){const o=K5(t.initSegment.data);if(o.length){const a=o[0];a.some(l=>l!==0)&&(this.log(`Using keyId found in init segment ${gi(a)}`),e.decryptdata.keyId=a,ps.setKeyIdForUri(e.decryptdata.uri,a))}}const s=this.emeController.loadKey(n);return(e.keyLoadPromise=s.then(o=>(e.mediaKeySessionContext=o,n))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(n)}loadKeyHTTP(e,t){const n=this.config,r=n.loader,s=new r(n);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((o,a)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=n.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,g)=>{const{frag:m,keyInfo:v}=p,y=C0(v.decryptdata);if(!m.decryptdata||v!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(m,W.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=m.decryptdata.key=new Uint8Array(h.data),m.keyLoader=null,v.loader=null,o({frag:m,keyInfo:v})},onError:(h,f,p,g)=>{this.resetLoader(f),a(this.createKeyLoadError(t,W.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),p,rt({url:l.url,data:void 0},h)))},onTimeout:(h,f,p)=>{this.resetLoader(f),a(this.createKeyLoadError(t,W.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(h,f,p)=>{this.resetLoader(f),a(this.createKeyLoadError(t,W.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};s.load(l,u,d)})}resetLoader(e){const{frag:t,keyInfo:n,url:r}=e,s=n.loader;t.keyLoader===s&&(t.keyLoader=null,n.loader=null);const o=C0(n.decryptdata)||r;delete this.keyIdToKeyInfo[o],s&&s.destroy()}}function C0(i){if(i.keyFormat!==jt.FAIRPLAY){const e=i.keyId;if(e)return gi(e)}return i.uri}function WP(i){const{type:e}=i;switch(e){case Ke.AUDIO_TRACK:return ve.AUDIO;case Ke.SUBTITLE_TRACK:return ve.SUBTITLE;default:return ve.MAIN}}function I0(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class d9{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(_.MANIFEST_LOADING,this.onManifestLoading,this),e.on(_.LEVEL_LOADING,this.onLevelLoading,this),e.on(_.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(_.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(_.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(_.MANIFEST_LOADING,this.onManifestLoading,this),e.off(_.LEVEL_LOADING,this.onLevelLoading,this),e.off(_.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(_.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(_.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,n=t.pLoader,r=t.loader,s=n||r,o=new s(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ke.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:n,level:r,pathwayId:s,url:o,deliveryDirectives:a,levelInfo:l}=t;this.load({id:n,level:r,pathwayId:s,responseType:"text",type:Ke.LEVEL,url:o,deliveryDirectives:a,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:o,track:a}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:Ke.AUDIO_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:n,groupId:r,url:s,deliveryDirectives:o,track:a}=t;this.load({id:n,groupId:r,level:null,responseType:"text",type:Ke.SUBTITLE_TRACK,url:s,deliveryDirectives:o,levelOrTrack:a})}onLevelsUpdated(e,t){const n=this.loaders[Ke.LEVEL];if(n){const r=n.context;r&&!t.levels.some(s=>s===r.levelOrTrack)&&(n.abort(),delete this.loaders[Ke.LEVEL])}}load(e){var t;const n=this.hls.config;let r=this.getInternalLoader(e);if(r){const c=this.hls.logger,u=r.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let s;if(e.type===Ke.MANIFEST?s=n.manifestLoadPolicy.default:s=at({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),pe((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===Ke.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===Ke.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===Ke.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,d=c.targetduration;if(u&&d){const h=Math.max(u*3,d*.8)*1e3;s=at({},s,{maxTimeToFirstByteMs:Math.min(h,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,s.maxTimeToFirstByteMs)})}}}const o=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(c,u,d,h)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const p=c.data;u.parsing.start=performance.now(),bn.isMediaPlaylist(p)||d.type!==Ke.MANIFEST?this.handleTrackOrLevelPlaylist(c,u,d,h||null,f):this.handleMasterPlaylist(c,u,d,h)},onError:(c,u,d,h)=>{this.handleNetworkError(u,d,!1,c,h)},onTimeout:(c,u,d)=>{this.handleNetworkError(u,d,!0,void 0,c)}};r.load(e,a,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){const s=this.hls,o=e.data,a=I0(e,n),l=bn.parseMasterPlaylist(o,a);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,l.playlistParsingError,r,t);return}const{contentSteering:c,levels:u,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p}=l;this.variableList=p,u.forEach(y=>{const{unknownCodecs:S}=y;if(S){const{preferManagedMediaSource:x}=this.hls.config;let{audioCodec:E,videoCodec:C}=y;for(let b=S.length;b--;){const I=S[b];ec(I,"audio",x)?(y.audioCodec=E=E?`${E},${I}`:I,pa.audio[E.substring(0,4)]=2,S.splice(b,1)):ec(I,"video",x)&&(y.videoCodec=C=C?`${C},${I}`:I,pa.video[C.substring(0,4)]=2,S.splice(b,1))}}});const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=bn.parseMasterPlaylistMedia(o,a,l);g.length&&!g.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new xt({}),bitrate:0,url:""})),s.trigger(_.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:m,captions:v,contentSteering:c,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,n,r,s){const o=this.hls,{id:a,level:l,type:c}=n,u=I0(e,n),d=pe(l)?l:pe(a)?a:0,h=WP(n),f=bn.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(c===Ke.MANIFEST){const p={attrs:new xt({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+nI(f,0),o.trigger(_.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,s)}handleManifestParsingError(e,t,n,r,s){this.hls.trigger(_.ERROR,{type:we.NETWORK_ERROR,details:W.MANIFEST_PARSING_ERROR,fatal:t.type===Ke.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,n=!1,r,s){let o=`A network ${n?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Ke.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Ke.AUDIO_TRACK||e.type===Ke.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let l=W.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case Ke.MANIFEST:l=n?W.MANIFEST_LOAD_TIMEOUT:W.MANIFEST_LOAD_ERROR,c=!0;break;case Ke.LEVEL:l=n?W.LEVEL_LOAD_TIMEOUT:W.LEVEL_LOAD_ERROR,c=!1;break;case Ke.AUDIO_TRACK:l=n?W.AUDIO_TRACK_LOAD_TIMEOUT:W.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Ke.SUBTITLE_TRACK:l=n?W.SUBTITLE_TRACK_LOAD_TIMEOUT:W.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const d={type:we.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:s};if(r){const h=(t==null?void 0:t.url)||e.url;d.response=rt({url:h,data:void 0},r)}this.hls.trigger(_.ERROR,d)}handlePlaylistLoaded(e,t,n,r,s,o){const a=this.hls,{type:l,level:c,levelOrTrack:u,id:d,groupId:h,deliveryDirectives:f}=r,p=I0(t,r),g=WP(r);let m=typeof r.level=="number"&&g===ve.MAIN?c:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(_.ERROR,{type:we.NETWORK_ERROR,details:W.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:v,reason:v.message,response:t,context:r,level:m,parent:g,networkDetails:s,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(_.ERROR,{type:we.NETWORK_ERROR,details:W.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:y,reason:y.message,response:t,context:r,level:m,parent:g,networkDetails:s,stats:n});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Ke.MANIFEST:case Ke.LEVEL:if(m){if(!u)m=0;else if(u!==a.levels[m]){const y=a.levels.indexOf(u);y>-1&&(m=y)}}a.trigger(_.LEVEL_LOADED,{details:e,levelInfo:u||a.levels[0],level:m||0,id:d||0,stats:n,networkDetails:s,deliveryDirectives:f,withoutMultiVariant:l===Ke.MANIFEST});break;case Ke.AUDIO_TRACK:a.trigger(_.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:n,networkDetails:s,deliveryDirectives:f});break;case Ke.SUBTITLE_TRACK:a.trigger(_.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:n,networkDetails:s,deliveryDirectives:f});break}}}class Rr{static get version(){return sc}static isMSESupported(){return R0()}static isSupported(){return GP()}static getMediaSource(){return Er()}static get Events(){return _}static get MetadataSchema(){return Ii}static get ErrorTypes(){return we}static get ErrorDetails(){return W}static get DefaultConfig(){return Rr.defaultConfig?Rr.defaultConfig:Yj}static set DefaultConfig(e){Rr.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Gv,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=F5(e.debug||!1,"Hls instance",e.assetPlayerId),n=this.config=Zj(Rr.DefaultConfig,e,t);this.userConfig=e,n.progressive&&Qj(n,t);const{abrController:r,bufferController:s,capLevelController:o,errorController:a,fpsController:l}=n,c=new a(this),u=this.abrController=new r(this),d=new CV(this),h=n.interstitialsController,f=h?this.interstitialsController=new h(this,Rr):null,p=this.bufferController=new s(this,d),g=this.capLevelController=new o(this),m=new l(this),v=new d9(this),y=n.contentSteeringController,S=y?new y(this):null,x=this.levelController=new o9(this,S),E=new r9(this),C=new u9(this.config,this.logger),b=this.streamController=new c9(this,d,C),I=this.gapController=new i9(this,d);g.setStreamController(b),m.setStreamController(b);const D=[v,x,b];f&&D.splice(1,0,f),S&&D.splice(1,0,S),this.networkControllers=D;const P=[u,p,I,g,m,E,d];this.audioTrackController=this.createController(n.audioTrackController,D);const k=n.audioStreamController;k&&D.push(this.audioStreamController=new k(this,d,C)),this.subtitleTrackController=this.createController(n.subtitleTrackController,D);const N=n.subtitleStreamController;N&&D.push(this.subtititleStreamController=new N(this,d,C)),this.createController(n.timelineController,P),C.emeController=this.emeController=this.createController(n.emeController,P),this.cmcdController=this.createController(n.cmcdController,P),this.latencyController=this.createController(s9,P),this.coreComponents=P,D.push(c);const B=c.onErrorOut;typeof B=="function"&&this.on(_.ERROR,B,c),this.on(_.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const r=e===_.ERROR;this.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.INTERNAL_EXCEPTION,fatal:r,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(_.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const s=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(_.ERROR,{type:we.OTHER_ERROR,details:W.ATTACH_MEDIA_ERROR,fatal:!0,error:s});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(_.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(_.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(_.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,n=this._url,r=this._url=Sv.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(_.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),!(!this.started||!this.networkControllers));n++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[ve.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ve.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[ve.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=oj()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){pV(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,n)for(let s=r;s--;){const o=e[s].attrs["HDCP-LEVEL"];if(o&&o<=n)return s}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const n=mC(t);return hC(e,n,navigator.mediaCapabilities)}}Rr.defaultConfig=void 0;const jP=Object.freeze(Object.defineProperty({__proto__:null,AbrController:SC,AttrList:xt,AudioStreamController:HI,AudioTrackController:VI,BasePlaylistController:fh,BaseSegment:xv,BaseStreamController:sh,BufferController:jI,CMCDController:aP,CapLevelController:ph,ChunkMetadata:Qd,ContentSteeringController:lP,Cues:BP,DateRange:Dv,EMEController:ao,ErrorActionFlags:Ri,ErrorController:RC,ErrorDetails:W,ErrorTypes:we,Events:_,FPSController:hP,FetchLoader:E0,Fragment:$d,Hls:Rr,HlsSkip:ic,HlsUrlParameters:Cv,KeySystemFormats:jt,KeySystems:Tt,Level:ga,LevelDetails:BC,LevelKey:ps,LoadStats:Ud,M3U8Parser:bn,MetadataSchema:Ii,NetworkErrorAction:Wt,Part:qR,PlaylistLevelType:ve,SubtitleStreamController:xP,SubtitleTrackController:gP,TimelineController:OP,XhrLoader:w0,default:Rr,fetchSupported:UP,getMediaSource:Er,isMSESupported:R0,isSupported:GP,requestMediaKeySystemAccess:Bv},Symbol.toStringTag,{value:"Module"}))});
|