aimeat 2.2.0 → 2.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.
- package/README.md +110 -84
- package/dist/.env.example +47 -11
- package/dist/locales/en.json +251 -371
- package/dist/locales/fi.json +255 -375
- package/dist/public/components/ContactCard.js +30 -5
- package/dist/public/components/ContactPicker.js +3 -2
- package/dist/public/components/ImageDeliverable.js +2 -1
- package/dist/public/components/JsonView.js +1 -0
- package/dist/public/components/LinkPreview.js +1 -1
- package/dist/public/components/NotificationBell.js +6 -4
- package/dist/public/components/UsageChart.js +2 -1
- package/dist/public/css/theme.css +1516 -1432
- package/dist/public/css/views/app-grant.css +95 -36
- package/dist/public/css/views/help.css +28 -0
- package/dist/public/css/views/landing.css +20 -0
- package/dist/public/css/views/members.css +40 -10
- package/dist/public/css/views/portal-dev.css +64 -45
- package/dist/public/css/views/profile.css +8 -0
- package/dist/public/js/api.js +1 -0
- package/dist/public/js/app-sandbox.js +1 -0
- package/dist/public/js/components/auth-image.js +3 -1
- package/dist/public/js/i18n.js +3 -1
- package/dist/public/js/presence-store.js +3 -1
- package/dist/public/js/recents.js +2 -0
- package/dist/public/js/services/agent-activity.js +2 -1
- package/dist/public/js/services/agent-directives.js +2 -1
- package/dist/public/js/services/agent-integration.js +2 -1
- package/dist/public/js/services/agent-messages.js +2 -1
- package/dist/public/js/services/agent-tasks.js +2 -1
- package/dist/public/js/services/agents.js +3 -2
- package/dist/public/js/services/calibrator.js +2 -1
- package/dist/public/js/services/consent.js +2 -1
- package/dist/public/js/services/contacts.js +2 -1
- package/dist/public/js/services/cortex.js +5 -4
- package/dist/public/js/services/ecosystem.js +2 -1
- package/dist/public/js/services/knowledge.js +2 -1
- package/dist/public/js/services/ledger.js +2 -1
- package/dist/public/js/services/living.js +10 -9
- package/dist/public/js/services/memory.js +2 -1
- package/dist/public/js/services/messages.js +53 -8
- package/dist/public/js/services/nodes.js +3 -2
- package/dist/public/js/services/notebook-plan.js +2 -1
- package/dist/public/js/services/notebook.js +6 -5
- package/dist/public/js/services/offers.js +6 -5
- package/dist/public/js/services/organisms.js +26 -25
- package/dist/public/js/services/organisms.prompts.js +3 -2
- package/dist/public/js/services/organisms.shared.js +2 -1
- package/dist/public/js/services/organisms.workspace-gen.js +3 -2
- package/dist/public/js/services/packages.js +1 -0
- package/dist/public/js/services/schedules.js +2 -1
- package/dist/public/js/services/security.js +3 -2
- package/dist/public/js/services/skills.js +1 -0
- package/dist/public/js/services/tracked-responses.js +4 -3
- package/dist/public/js/services/unfurl.js +4 -4
- package/dist/public/js/services/work.js +2 -1
- package/dist/public/js/site.js +74 -0
- package/dist/public/js/swallowed.js +69 -0
- package/dist/public/js/theme.js +2 -1
- package/dist/public/js/utils.js +3 -1
- package/dist/public/lib/VENDORED.md +1 -0
- package/dist/public/lib/aimeat-game/board.css +262 -0
- package/dist/public/lib/aimeat-game/progress.css +406 -0
- package/dist/public/lib/aimeat-game/shell.css +388 -0
- package/dist/public/lib/aimeat-game.css +394 -0
- package/dist/public/lib/pdfjs@6/pdf.min.mjs +29 -0
- package/dist/public/lib/pdfjs@6/pdf.worker.min.mjs +29 -0
- package/dist/public/privacy.fi.html +1 -1
- package/dist/public/privacy.html +1 -1
- package/dist/public/spa.html +885 -793
- package/dist/public/sw.js +4 -2
- package/dist/public/views/admin/agent-integration-tab.js +7 -6
- package/dist/public/views/admin/ai-usage-tab.js +2 -1
- package/dist/public/views/admin/cortex-tab.js +2 -1
- package/dist/public/views/admin/economy-tab.js +0 -1
- package/dist/public/views/admin/email-tab.js +4 -2
- package/dist/public/views/admin/federation-tab.js +3 -2
- package/dist/public/views/admin/feedback-tab.js +2 -1
- package/dist/public/views/admin/knowledge-tab.js +2 -1
- package/dist/public/views/admin/messages-tab.js +2 -1
- package/dist/public/views/admin/msm-tab.js +2 -1
- package/dist/public/views/admin/packages-tab.js +3 -2
- package/dist/public/views/admin/portal-tab.js +7 -2
- package/dist/public/views/admin/push-tab.js +9 -4
- package/dist/public/views/admin/stats-tab.js +2 -1
- package/dist/public/views/admin/usage-tab.js +4 -3
- package/dist/public/views/admin.js +6 -4
- package/dist/public/views/agent-solo.js +4 -3
- package/dist/public/views/app-grant.js +105 -32
- package/dist/public/views/business.js +139 -55
- package/dist/public/views/command-palette.js +5 -3
- package/dist/public/views/companies.js +3 -2
- package/dist/public/views/doc-solo.js +2 -1
- package/dist/public/views/help.js +95 -15
- package/dist/public/views/how-it-works.js +41 -8
- package/dist/public/views/invite-accept.js +3 -2
- package/dist/public/views/landing-activity.js +3 -2
- package/dist/public/views/landing-node-totals.js +2 -1
- package/dist/public/views/landing.js +75 -152
- package/dist/public/views/members.js +29 -2
- package/dist/public/views/my-company.js +9 -7
- package/dist/public/views/my-company.payments.js +2 -1
- package/dist/public/views/portal-classic.js +2 -1
- package/dist/public/views/portal-dev.js +64 -35
- package/dist/public/views/portal-dev.panels.js +39 -2
- package/dist/public/views/portal-dev.upload.js +25 -196
- package/dist/public/views/portal.components.js +4 -3
- package/dist/public/views/portfolio.js +5 -4
- package/dist/public/views/profile/access-tab/access-tokens.js +2 -1
- package/dist/public/views/profile/access-tab/agent-defaults.js +3 -1
- package/dist/public/views/profile/access-tab/connected-apps.js +72 -3
- package/dist/public/views/profile/access-tab/sharing-groups.js +4 -1
- package/dist/public/views/profile/access-tab.js +3 -1
- package/dist/public/views/profile/agents/agent-card.js +6 -5
- package/dist/public/views/profile/agents/tab-activity.js +10 -8
- package/dist/public/views/profile/agents/tab-agent-config.js +3 -1
- package/dist/public/views/profile/agents/tab-contracts.js +2 -1
- package/dist/public/views/profile/agents/tab-data-access.js +10 -7
- package/dist/public/views/profile/agents/tab-helpers.js +5 -0
- package/dist/public/views/profile/agents/tab-integration.js +12 -9
- package/dist/public/views/profile/agents/tab-messages.js +6 -4
- package/dist/public/views/profile/agents/tab-quality.js +3 -2
- package/dist/public/views/profile/agents/tab-usage.js +5 -3
- package/dist/public/views/profile/agents/task-item.js +12 -7
- package/dist/public/views/profile/agents-activity-subtab.js +5 -2
- package/dist/public/views/profile/agents-capabilities-subtab.js +4 -2
- package/dist/public/views/profile/agents-messages-subtab.js +5 -2
- package/dist/public/views/profile/agents-services-subtab.js +1 -0
- package/dist/public/views/profile/agents-tab.js +11 -7
- package/dist/public/views/profile/appdev-tab.js +3 -2
- package/dist/public/views/profile/apps-tab.js +10 -8
- package/dist/public/views/profile/boards-tab.js +5 -4
- package/dist/public/views/profile/calibrator-batch.helpers.js +3 -2
- package/dist/public/views/profile/calibrator-batch.js +3 -1
- package/dist/public/views/profile/calibrator-llm-editor.js +3 -2
- package/dist/public/views/profile/calibrator-tab.js +5 -4
- package/dist/public/views/profile/capabilities-tab.js +2 -1
- package/dist/public/views/profile/chat-sessions-tab.js +6 -3
- package/dist/public/views/profile/contacts-tab.js +2 -1
- package/dist/public/views/profile/data-wallet-tab.js +5 -4
- package/dist/public/views/profile/discover-tab.js +4 -1
- package/dist/public/views/profile/ecosystem-tab.automation.js +13 -9
- package/dist/public/views/profile/ecosystem-tab.cards.js +3 -2
- package/dist/public/views/profile/ecosystem-tab.js +10 -7
- package/dist/public/views/profile/email-tab.js +2 -1
- package/dist/public/views/profile/extensions-tab.js +7 -6
- package/dist/public/views/profile/extensions-tab.maturity.js +2 -1
- package/dist/public/views/profile/extensions-tab.prompts.js +24 -0
- package/dist/public/views/profile/federation-tab.js +2 -1
- package/dist/public/views/profile/inbox-tab/components.js +13 -10
- package/dist/public/views/profile/inbox-tab/helpers.js +15 -1
- package/dist/public/views/profile/inbox-tab/use-thread-ux.js +1 -1
- package/dist/public/views/profile/inbox-tab.js +33 -30
- package/dist/public/views/profile/inline-panels.js +5 -4
- package/dist/public/views/profile/knowledge-tab.js +15 -13
- package/dist/public/views/profile/landing-page.cards.js +14 -9
- package/dist/public/views/profile/landing-page.helpers.js +5 -2
- package/dist/public/views/profile/landing-page.js +11 -7
- package/dist/public/views/profile/landing-page.modals.js +8 -5
- package/dist/public/views/profile/living-tab.js +3 -2
- package/dist/public/views/profile/mcp-tab.js +4 -2
- package/dist/public/views/profile/memory-tab/browse-view.js +3 -2
- package/dist/public/views/profile/memory-tab/components.js +4 -3
- package/dist/public/views/profile/memory-tab/entries-view.js +3 -2
- package/dist/public/views/profile/memory-tab.js +18 -16
- package/dist/public/views/profile/nodes-tab.js +2 -1
- package/dist/public/views/profile/notebook-card.js +4 -3
- package/dist/public/views/profile/notebook-tab.js +7 -5
- package/dist/public/views/profile/notifications-tab.js +9 -5
- package/dist/public/views/profile/offers-tab.js +5 -4
- package/dist/public/views/profile/openrouter-settings.js +5 -4
- package/dist/public/views/profile/organisms/activity-panel.js +2 -1
- package/dist/public/views/profile/organisms/agents.js +2 -1
- package/dist/public/views/profile/organisms/document.js +13 -12
- package/dist/public/views/profile/organisms/helpers.js +2 -1
- package/dist/public/views/profile/organisms/home.js +7 -6
- package/dist/public/views/profile/organisms/invite-panel.js +1 -1
- package/dist/public/views/profile/organisms/members.js +7 -6
- package/dist/public/views/profile/organisms/mindmap.js +1 -1
- package/dist/public/views/profile/organisms/panels.js +4 -3
- package/dist/public/views/profile/organisms/participants-panel.js +11 -10
- package/dist/public/views/profile/organisms/readme-panel.js +1 -0
- package/dist/public/views/profile/organisms/sources-panel.js +2 -1
- package/dist/public/views/profile/organisms/workspace/doc-space.js +2 -1
- package/dist/public/views/profile/organisms/workspace/model.js +1 -0
- package/dist/public/views/profile/organisms/workspace-apps.js +4 -2
- package/dist/public/views/profile/organisms/workspace-comments.js +3 -2
- package/dist/public/views/profile/organisms/workspace-list.js +5 -4
- package/dist/public/views/profile/organisms/workspace.js +19 -16
- package/dist/public/views/profile/organisms-tab.js +20 -12
- package/dist/public/views/profile/packages-tab.js +6 -4
- package/dist/public/views/profile/portfolio-tab.js +1 -1
- package/dist/public/views/profile/scheduler-calendar.js +2 -1
- package/dist/public/views/profile/scheduler-tab.js +2 -1
- package/dist/public/views/profile/security-tab.js +2 -1
- package/dist/public/views/profile/services-tab.js +4 -3
- package/dist/public/views/profile/wallet-tab.js +90 -84
- package/dist/public/views/profile/work-tab.js +3 -2
- package/dist/public/views/profile/workflows-form.js +2 -1
- package/dist/public/views/profile/workflows-tab.js +3 -2
- package/dist/public/views/public-workspace-viewer.js +7 -4
- package/dist/scripts/build-sdk-libs.d.ts.map +1 -1
- package/dist/scripts/build-sdk-libs.js +4 -0
- package/dist/scripts/build-sdk-libs.js.map +1 -1
- package/dist/scripts/check-silent-catch.d.ts +2 -0
- package/dist/scripts/check-silent-catch.d.ts.map +1 -0
- package/dist/scripts/check-silent-catch.js +159 -0
- package/dist/scripts/check-silent-catch.js.map +1 -0
- package/dist/src/auth/jwt.d.ts +2 -0
- package/dist/src/auth/jwt.d.ts.map +1 -1
- package/dist/src/auth/jwt.js +15 -3
- package/dist/src/auth/jwt.js.map +1 -1
- package/dist/src/auth/keypair.d.ts.map +1 -1
- package/dist/src/auth/keypair.js +3 -0
- package/dist/src/auth/keypair.js.map +1 -1
- package/dist/src/auth/middleware.d.ts +2 -0
- package/dist/src/auth/middleware.d.ts.map +1 -1
- package/dist/src/auth/middleware.js +33 -14
- package/dist/src/auth/middleware.js.map +1 -1
- package/dist/src/auth/node-keys.d.ts.map +1 -1
- package/dist/src/auth/node-keys.js +59 -16
- package/dist/src/auth/node-keys.js.map +1 -1
- package/dist/src/cli/config-import.d.ts.map +1 -1
- package/dist/src/cli/config-import.js +3 -1
- package/dist/src/cli/config-import.js.map +1 -1
- package/dist/src/cli/connect/auth.d.ts.map +1 -1
- package/dist/src/cli/connect/auth.js +1 -0
- package/dist/src/cli/connect/auth.js.map +1 -1
- package/dist/src/cli/connect/config.d.ts.map +1 -1
- package/dist/src/cli/connect/config.js +3 -1
- package/dist/src/cli/connect/config.js.map +1 -1
- package/dist/src/cli/connect/keychain.d.ts.map +1 -1
- package/dist/src/cli/connect/keychain.js +6 -2
- package/dist/src/cli/connect/keychain.js.map +1 -1
- package/dist/src/cli/connect/mcp/local-server.d.ts.map +1 -1
- package/dist/src/cli/connect/mcp/local-server.js +9 -2
- package/dist/src/cli/connect/mcp/local-server.js.map +1 -1
- package/dist/src/cli/connect/mcp/tools/workspaces.d.ts.map +1 -1
- package/dist/src/cli/connect/mcp/tools/workspaces.js +2 -0
- package/dist/src/cli/connect/mcp/tools/workspaces.js.map +1 -1
- package/dist/src/cli/connect/task-runner.d.ts.map +1 -1
- package/dist/src/cli/connect/task-runner.js +11 -4
- package/dist/src/cli/connect/task-runner.js.map +1 -1
- package/dist/src/cli/connect/tool-call-helpers.d.ts.map +1 -1
- package/dist/src/cli/connect/tool-call-helpers.js +1 -0
- package/dist/src/cli/connect/tool-call-helpers.js.map +1 -1
- package/dist/src/cli/connect/tunnel-client.d.ts.map +1 -1
- package/dist/src/cli/connect/tunnel-client.js +26 -8
- package/dist/src/cli/connect/tunnel-client.js.map +1 -1
- package/dist/src/cli/federation-join.d.ts.map +1 -1
- package/dist/src/cli/federation-join.js +7 -3
- package/dist/src/cli/federation-join.js.map +1 -1
- package/dist/src/cli/init-wizard/presets.d.ts.map +1 -1
- package/dist/src/cli/init-wizard/presets.js +21 -0
- package/dist/src/cli/init-wizard/presets.js.map +1 -1
- package/dist/src/cli/init-wizard/steps-advanced.d.ts.map +1 -1
- package/dist/src/cli/init-wizard/steps-advanced.js +2 -0
- package/dist/src/cli/init-wizard/steps-advanced.js.map +1 -1
- package/dist/src/cli/init-wizard/steps-operator.d.ts.map +1 -1
- package/dist/src/cli/init-wizard/steps-operator.js +10 -0
- package/dist/src/cli/init-wizard/steps-operator.js.map +1 -1
- package/dist/src/commerce/invoice-handler.d.ts +5 -0
- package/dist/src/commerce/invoice-handler.d.ts.map +1 -0
- package/dist/src/commerce/invoice-handler.js +41 -0
- package/dist/src/commerce/invoice-handler.js.map +1 -0
- package/dist/src/commerce/payable-book.d.ts +31 -0
- package/dist/src/commerce/payable-book.d.ts.map +1 -0
- package/dist/src/commerce/payable-book.js +27 -0
- package/dist/src/commerce/payable-book.js.map +1 -0
- package/dist/src/commerce/payment-handlers.d.ts.map +1 -1
- package/dist/src/commerce/payment-handlers.js +8 -4
- package/dist/src/commerce/payment-handlers.js.map +1 -1
- package/dist/src/commerce/sellable-resolvers.d.ts +6 -6
- package/dist/src/commerce/sellable-resolvers.d.ts.map +1 -1
- package/dist/src/commerce/sellable-resolvers.js +17 -4
- package/dist/src/commerce/sellable-resolvers.js.map +1 -1
- package/dist/src/commerce/session-service.js +2 -2
- package/dist/src/commerce/session-service.js.map +1 -1
- package/dist/src/commerce/stripe-handler.d.ts +33 -0
- package/dist/src/commerce/stripe-handler.d.ts.map +1 -0
- package/dist/src/commerce/stripe-handler.js +108 -0
- package/dist/src/commerce/stripe-handler.js.map +1 -0
- package/dist/src/commerce/types.d.ts +10 -12
- package/dist/src/commerce/types.d.ts.map +1 -1
- package/dist/src/commerce/x402-facilitator.d.ts.map +1 -1
- package/dist/src/commerce/x402-facilitator.js +1 -0
- package/dist/src/commerce/x402-facilitator.js.map +1 -1
- package/dist/src/config-types.d.ts +66 -0
- package/dist/src/config-types.d.ts.map +1 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.js +62 -1
- package/dist/src/config.js.map +1 -1
- package/dist/src/data/library-packs/sdk.d.ts +4 -0
- package/dist/src/data/library-packs/sdk.d.ts.map +1 -1
- package/dist/src/data/library-packs/sdk.js +46 -0
- package/dist/src/data/library-packs/sdk.js.map +1 -1
- package/dist/src/data/library-packs/vendored.d.ts.map +1 -1
- package/dist/src/data/library-packs/vendored.js +88 -0
- package/dist/src/data/library-packs/vendored.js.map +1 -1
- package/dist/src/generated/api-types.d.ts +472 -26
- package/dist/src/generated/api-types.d.ts.map +1 -1
- package/dist/src/index-connect.d.ts.map +1 -1
- package/dist/src/index-connect.js +4 -1
- package/dist/src/index-connect.js.map +1 -1
- package/dist/src/index-start.d.ts.map +1 -1
- package/dist/src/index-start.js +10 -6
- package/dist/src/index-start.js.map +1 -1
- package/dist/src/mcp/app-template-proposals.d.ts.map +1 -1
- package/dist/src/mcp/app-template-proposals.js +2 -1
- package/dist/src/mcp/app-template-proposals.js.map +1 -1
- package/dist/src/mcp/apps.d.ts.map +1 -1
- package/dist/src/mcp/apps.js +4 -3
- package/dist/src/mcp/apps.js.map +1 -1
- package/dist/src/mcp/capabilities.d.ts.map +1 -1
- package/dist/src/mcp/capabilities.js +3 -2
- package/dist/src/mcp/capabilities.js.map +1 -1
- package/dist/src/mcp/catalog/scopes.d.ts +0 -1
- package/dist/src/mcp/catalog/scopes.d.ts.map +1 -1
- package/dist/src/mcp/catalog/scopes.js +2 -11
- package/dist/src/mcp/catalog/scopes.js.map +1 -1
- package/dist/src/mcp/catalog/surfaces.d.ts +1 -7
- package/dist/src/mcp/catalog/surfaces.d.ts.map +1 -1
- package/dist/src/mcp/catalog/surfaces.js +10 -16
- package/dist/src/mcp/catalog/surfaces.js.map +1 -1
- package/dist/src/mcp/commerce.d.ts.map +1 -1
- package/dist/src/mcp/commerce.js +35 -3
- package/dist/src/mcp/commerce.js.map +1 -1
- package/dist/src/mcp/core.d.ts.map +1 -1
- package/dist/src/mcp/core.js +3 -2
- package/dist/src/mcp/core.js.map +1 -1
- package/dist/src/mcp/exchange-run.d.ts +28 -0
- package/dist/src/mcp/exchange-run.d.ts.map +1 -1
- package/dist/src/mcp/exchange-run.js +58 -37
- package/dist/src/mcp/exchange-run.js.map +1 -1
- package/dist/src/mcp/exchange.d.ts.map +1 -1
- package/dist/src/mcp/exchange.js +9 -7
- package/dist/src/mcp/exchange.js.map +1 -1
- package/dist/src/mcp/extensions.d.ts.map +1 -1
- package/dist/src/mcp/extensions.js +60 -106
- package/dist/src/mcp/extensions.js.map +1 -1
- package/dist/src/mcp/index.d.ts.map +1 -1
- package/dist/src/mcp/index.js +1 -5
- package/dist/src/mcp/index.js.map +1 -1
- package/dist/src/mcp/knowledge.d.ts.map +1 -1
- package/dist/src/mcp/knowledge.js +1 -0
- package/dist/src/mcp/knowledge.js.map +1 -1
- package/dist/src/mcp/oauth.d.ts +3 -0
- package/dist/src/mcp/oauth.d.ts.map +1 -1
- package/dist/src/mcp/oauth.js +13 -8
- package/dist/src/mcp/oauth.js.map +1 -1
- package/dist/src/mcp/workspaces.d.ts.map +1 -1
- package/dist/src/mcp/workspaces.js +7 -4
- package/dist/src/mcp/workspaces.js.map +1 -1
- package/dist/src/middleware/cors.d.ts.map +1 -1
- package/dist/src/middleware/cors.js +3 -1
- package/dist/src/middleware/cors.js.map +1 -1
- package/dist/src/middleware/subdomain.d.ts +4 -0
- package/dist/src/middleware/subdomain.d.ts.map +1 -1
- package/dist/src/middleware/subdomain.js +23 -2
- package/dist/src/middleware/subdomain.js.map +1 -1
- package/dist/src/models/app-tool-schemas.d.ts +35 -0
- package/dist/src/models/app-tool-schemas.d.ts.map +1 -1
- package/dist/src/models/app-tool-schemas.js +44 -0
- package/dist/src/models/app-tool-schemas.js.map +1 -1
- package/dist/src/routes/admin-config.d.ts.map +1 -1
- package/dist/src/routes/admin-config.js +4 -1
- package/dist/src/routes/admin-config.js.map +1 -1
- package/dist/src/routes/admin-extensions.d.ts.map +1 -1
- package/dist/src/routes/admin-extensions.js +2 -1
- package/dist/src/routes/admin-extensions.js.map +1 -1
- package/dist/src/routes/admin-monitoring.js +14 -5
- package/dist/src/routes/admin-monitoring.js.map +1 -1
- package/dist/src/routes/admin-security.d.ts.map +1 -1
- package/dist/src/routes/admin-security.js +4 -1
- package/dist/src/routes/admin-security.js.map +1 -1
- package/dist/src/routes/admin.d.ts.map +1 -1
- package/dist/src/routes/admin.js +6 -4
- package/dist/src/routes/admin.js.map +1 -1
- package/dist/src/routes/agent-activity.d.ts.map +1 -1
- package/dist/src/routes/agent-activity.js +4 -1
- package/dist/src/routes/agent-activity.js.map +1 -1
- package/dist/src/routes/agent-directives.d.ts +3 -10
- package/dist/src/routes/agent-directives.d.ts.map +1 -1
- package/dist/src/routes/agent-directives.js +7 -12
- package/dist/src/routes/agent-directives.js.map +1 -1
- package/dist/src/routes/agent-integration.d.ts.map +1 -1
- package/dist/src/routes/agent-integration.js +3 -1
- package/dist/src/routes/agent-integration.js.map +1 -1
- package/dist/src/routes/agent-messages.d.ts.map +1 -1
- package/dist/src/routes/agent-messages.js +5 -2
- package/dist/src/routes/agent-messages.js.map +1 -1
- package/dist/src/routes/agent-onboarding.d.ts.map +1 -1
- package/dist/src/routes/agent-onboarding.js +19 -6
- package/dist/src/routes/agent-onboarding.js.map +1 -1
- package/dist/src/routes/agent-skills-discovery.d.ts.map +1 -1
- package/dist/src/routes/agent-skills-discovery.js +2 -1
- package/dist/src/routes/agent-skills-discovery.js.map +1 -1
- package/dist/src/routes/agent-tasks/completion.js +1 -1
- package/dist/src/routes/agent-tasks/completion.js.map +1 -1
- package/dist/src/routes/agent-tasks/create-read.js +3 -1
- package/dist/src/routes/agent-tasks/create-read.js.map +1 -1
- package/dist/src/routes/agent-tasks/lifecycle.d.ts.map +1 -1
- package/dist/src/routes/agent-tasks/lifecycle.js +28 -9
- package/dist/src/routes/agent-tasks/lifecycle.js.map +1 -1
- package/dist/src/routes/agents/management.d.ts.map +1 -1
- package/dist/src/routes/agents/management.js +4 -1
- package/dist/src/routes/agents/management.js.map +1 -1
- package/dist/src/routes/agents/offers.d.ts.map +1 -1
- package/dist/src/routes/agents/offers.js +0 -0
- package/dist/src/routes/agents/offers.js.map +1 -1
- package/dist/src/routes/agents/profile-metadata.d.ts.map +1 -1
- package/dist/src/routes/agents/profile-metadata.js +2 -1
- package/dist/src/routes/agents/profile-metadata.js.map +1 -1
- package/dist/src/routes/app-grants.d.ts +7 -0
- package/dist/src/routes/app-grants.d.ts.map +1 -1
- package/dist/src/routes/app-grants.js +69 -4
- package/dist/src/routes/app-grants.js.map +1 -1
- package/dist/src/routes/appdev-overview.d.ts.map +1 -1
- package/dist/src/routes/appdev-overview.js +2 -1
- package/dist/src/routes/appdev-overview.js.map +1 -1
- package/dist/src/routes/apps/catalogue-admin.d.ts.map +1 -1
- package/dist/src/routes/apps/catalogue-admin.js +2 -1
- package/dist/src/routes/apps/catalogue-admin.js.map +1 -1
- package/dist/src/routes/apps/drafts.d.ts.map +1 -1
- package/dist/src/routes/apps/drafts.js +2 -1
- package/dist/src/routes/apps/drafts.js.map +1 -1
- package/dist/src/routes/apps/fork-manage.d.ts.map +1 -1
- package/dist/src/routes/apps/fork-manage.js +6 -3
- package/dist/src/routes/apps/fork-manage.js.map +1 -1
- package/dist/src/routes/apps/helpers.d.ts.map +1 -1
- package/dist/src/routes/apps/helpers.js +5 -1
- package/dist/src/routes/apps/helpers.js.map +1 -1
- package/dist/src/routes/apps/publish.d.ts.map +1 -1
- package/dist/src/routes/apps/publish.js +8 -3
- package/dist/src/routes/apps/publish.js.map +1 -1
- package/dist/src/routes/apps/read.d.ts.map +1 -1
- package/dist/src/routes/apps/read.js +2 -1
- package/dist/src/routes/apps/read.js.map +1 -1
- package/dist/src/routes/auth.d.ts.map +1 -1
- package/dist/src/routes/auth.js +2 -1
- package/dist/src/routes/auth.js.map +1 -1
- package/dist/src/routes/boards.js +1 -1
- package/dist/src/routes/boards.js.map +1 -1
- package/dist/src/routes/bootstrap.d.ts.map +1 -1
- package/dist/src/routes/bootstrap.js +8 -3
- package/dist/src/routes/bootstrap.js.map +1 -1
- package/dist/src/routes/capabilities.d.ts.map +1 -1
- package/dist/src/routes/capabilities.js +4 -3
- package/dist/src/routes/capabilities.js.map +1 -1
- package/dist/src/routes/commerce-acp.js +1 -1
- package/dist/src/routes/commerce-acp.js.map +1 -1
- package/dist/src/routes/commerce-ucp.d.ts +2 -3
- package/dist/src/routes/commerce-ucp.d.ts.map +1 -1
- package/dist/src/routes/commerce-ucp.js +6 -12
- package/dist/src/routes/commerce-ucp.js.map +1 -1
- package/dist/src/routes/commerce.d.ts +7 -1
- package/dist/src/routes/commerce.d.ts.map +1 -1
- package/dist/src/routes/commerce.js +65 -15
- package/dist/src/routes/commerce.js.map +1 -1
- package/dist/src/routes/csm.d.ts.map +1 -1
- package/dist/src/routes/csm.js +3 -1
- package/dist/src/routes/csm.js.map +1 -1
- package/dist/src/routes/ecosystem-apps.d.ts.map +1 -1
- package/dist/src/routes/ecosystem-apps.js +7 -6
- package/dist/src/routes/ecosystem-apps.js.map +1 -1
- package/dist/src/routes/exchange-market.d.ts.map +1 -1
- package/dist/src/routes/exchange-market.js +10 -6
- package/dist/src/routes/exchange-market.js.map +1 -1
- package/dist/src/routes/exchange.d.ts +10 -1
- package/dist/src/routes/exchange.d.ts.map +1 -1
- package/dist/src/routes/exchange.js +344 -9
- package/dist/src/routes/exchange.js.map +1 -1
- package/dist/src/routes/extensions/actions.d.ts +2 -0
- package/dist/src/routes/extensions/actions.d.ts.map +1 -1
- package/dist/src/routes/extensions/actions.js +47 -8
- package/dist/src/routes/extensions/actions.js.map +1 -1
- package/dist/src/routes/extensions/entitlement-gate.d.ts +44 -7
- package/dist/src/routes/extensions/entitlement-gate.d.ts.map +1 -1
- package/dist/src/routes/extensions/entitlement-gate.js +21 -142
- package/dist/src/routes/extensions/entitlement-gate.js.map +1 -1
- package/dist/src/routes/extensions/internal-pass.d.ts +23 -0
- package/dist/src/routes/extensions/internal-pass.d.ts.map +1 -0
- package/dist/src/routes/extensions/internal-pass.js +70 -0
- package/dist/src/routes/extensions/internal-pass.js.map +1 -0
- package/dist/src/routes/extensions/manifest.d.ts +4 -0
- package/dist/src/routes/extensions/manifest.d.ts.map +1 -1
- package/dist/src/routes/extensions/manifest.js +68 -4
- package/dist/src/routes/extensions/manifest.js.map +1 -1
- package/dist/src/routes/extensions/metered-response.d.ts +37 -0
- package/dist/src/routes/extensions/metered-response.d.ts.map +1 -0
- package/dist/src/routes/extensions/metered-response.js +60 -0
- package/dist/src/routes/extensions/metered-response.js.map +1 -0
- package/dist/src/routes/extensions/pacing.d.ts +31 -0
- package/dist/src/routes/extensions/pacing.d.ts.map +1 -1
- package/dist/src/routes/extensions/pacing.js +5 -33
- package/dist/src/routes/extensions/pacing.js.map +1 -1
- package/dist/src/routes/extensions/paywall.d.ts +16 -0
- package/dist/src/routes/extensions/paywall.d.ts.map +1 -1
- package/dist/src/routes/extensions/paywall.js +157 -8
- package/dist/src/routes/extensions/paywall.js.map +1 -1
- package/dist/src/routes/extensions/priced-binding.d.ts +50 -0
- package/dist/src/routes/extensions/priced-binding.d.ts.map +1 -0
- package/dist/src/routes/extensions/priced-binding.js +46 -0
- package/dist/src/routes/extensions/priced-binding.js.map +1 -0
- package/dist/src/routes/federation-genesis.d.ts.map +1 -1
- package/dist/src/routes/federation-genesis.js +14 -5
- package/dist/src/routes/federation-genesis.js.map +1 -1
- package/dist/src/routes/federation-peer/introduce.d.ts.map +1 -1
- package/dist/src/routes/federation-peer/introduce.js +3 -1
- package/dist/src/routes/federation-peer/introduce.js.map +1 -1
- package/dist/src/routes/federation-peer/lifecycle.d.ts.map +1 -1
- package/dist/src/routes/federation-peer/lifecycle.js +3 -2
- package/dist/src/routes/federation-peer/lifecycle.js.map +1 -1
- package/dist/src/routes/federation-peer/peers.d.ts.map +1 -1
- package/dist/src/routes/federation-peer/peers.js +5 -3
- package/dist/src/routes/federation-peer/peers.js.map +1 -1
- package/dist/src/routes/federation-peer/policy-book.d.ts.map +1 -1
- package/dist/src/routes/federation-peer/policy-book.js +2 -1
- package/dist/src/routes/federation-peer/policy-book.js.map +1 -1
- package/dist/src/routes/federation-peer/promotion.d.ts.map +1 -1
- package/dist/src/routes/federation-peer/promotion.js +4 -1
- package/dist/src/routes/federation-peer/promotion.js.map +1 -1
- package/dist/src/routes/federation-settlements.js +2 -2
- package/dist/src/routes/federation-settlements.js.map +1 -1
- package/dist/src/routes/federation-sync/catalogue-trust.js +5 -3
- package/dist/src/routes/federation-sync/catalogue-trust.js.map +1 -1
- package/dist/src/routes/federation-sync/messaging.js +5 -3
- package/dist/src/routes/federation-sync/messaging.js.map +1 -1
- package/dist/src/routes/federation-sync/routing.d.ts.map +1 -1
- package/dist/src/routes/federation-sync/routing.js +7 -5
- package/dist/src/routes/federation-sync/routing.js.map +1 -1
- package/dist/src/routes/flags.d.ts.map +1 -1
- package/dist/src/routes/flags.js +3 -1
- package/dist/src/routes/flags.js.map +1 -1
- package/dist/src/routes/ghii/register-login.js +1 -1
- package/dist/src/routes/ghii/register-login.js.map +1 -1
- package/dist/src/routes/instances/install.d.ts.map +1 -1
- package/dist/src/routes/instances/install.js +2 -1
- package/dist/src/routes/instances/install.js.map +1 -1
- package/dist/src/routes/instances/manage.d.ts.map +1 -1
- package/dist/src/routes/instances/manage.js +2 -1
- package/dist/src/routes/instances/manage.js.map +1 -1
- package/dist/src/routes/knowledge/packages-core.d.ts.map +1 -1
- package/dist/src/routes/knowledge/packages-core.js +2 -1
- package/dist/src/routes/knowledge/packages-core.js.map +1 -1
- package/dist/src/routes/knowledge/sharing.d.ts.map +1 -1
- package/dist/src/routes/knowledge/sharing.js +2 -1
- package/dist/src/routes/knowledge/sharing.js.map +1 -1
- package/dist/src/routes/library-packs.d.ts.map +1 -1
- package/dist/src/routes/library-packs.js +10 -3
- package/dist/src/routes/library-packs.js.map +1 -1
- package/dist/src/routes/libs.d.ts +9 -0
- package/dist/src/routes/libs.d.ts.map +1 -1
- package/dist/src/routes/libs.js +11 -2
- package/dist/src/routes/libs.js.map +1 -1
- package/dist/src/routes/matches.d.ts.map +1 -1
- package/dist/src/routes/matches.js +7 -3
- package/dist/src/routes/matches.js.map +1 -1
- package/dist/src/routes/memory/bulk.d.ts.map +1 -1
- package/dist/src/routes/memory/bulk.js +3 -1
- package/dist/src/routes/memory/bulk.js.map +1 -1
- package/dist/src/routes/memory/crud.d.ts.map +1 -1
- package/dist/src/routes/memory/crud.js +4 -2
- package/dist/src/routes/memory/crud.js.map +1 -1
- package/dist/src/routes/memory/federation.d.ts.map +1 -1
- package/dist/src/routes/memory/federation.js +5 -0
- package/dist/src/routes/memory/federation.js.map +1 -1
- package/dist/src/routes/memory/key.d.ts.map +1 -1
- package/dist/src/routes/memory/key.js +9 -4
- package/dist/src/routes/memory/key.js.map +1 -1
- package/dist/src/routes/messages.d.ts.map +1 -1
- package/dist/src/routes/messages.js +2 -1
- package/dist/src/routes/messages.js.map +1 -1
- package/dist/src/routes/msm.d.ts.map +1 -1
- package/dist/src/routes/msm.js +3 -1
- package/dist/src/routes/msm.js.map +1 -1
- package/dist/src/routes/oauth-login.d.ts.map +1 -1
- package/dist/src/routes/oauth-login.js +1 -0
- package/dist/src/routes/oauth-login.js.map +1 -1
- package/dist/src/routes/openrouter.js +2 -2
- package/dist/src/routes/openrouter.js.map +1 -1
- package/dist/src/routes/organisms/crud.d.ts.map +1 -1
- package/dist/src/routes/organisms/crud.js +3 -2
- package/dist/src/routes/organisms/crud.js.map +1 -1
- package/dist/src/routes/organisms/gates.d.ts.map +1 -1
- package/dist/src/routes/organisms/gates.js +3 -2
- package/dist/src/routes/organisms/gates.js.map +1 -1
- package/dist/src/routes/organisms/intake.d.ts.map +1 -1
- package/dist/src/routes/organisms/intake.js +13 -1
- package/dist/src/routes/organisms/intake.js.map +1 -1
- package/dist/src/routes/organisms/shared.d.ts.map +1 -1
- package/dist/src/routes/organisms/shared.js +7 -3
- package/dist/src/routes/organisms/shared.js.map +1 -1
- package/dist/src/routes/organisms/workspace-ops.d.ts.map +1 -1
- package/dist/src/routes/organisms/workspace-ops.js +6 -5
- package/dist/src/routes/organisms/workspace-ops.js.map +1 -1
- package/dist/src/routes/organisms/workspace-read.d.ts.map +1 -1
- package/dist/src/routes/organisms/workspace-read.js +4 -2
- package/dist/src/routes/organisms/workspace-read.js.map +1 -1
- package/dist/src/routes/owners.d.ts.map +1 -1
- package/dist/src/routes/owners.js +37 -12
- package/dist/src/routes/owners.js.map +1 -1
- package/dist/src/routes/personal.js +3 -1
- package/dist/src/routes/personal.js.map +1 -1
- package/dist/src/routes/portal.d.ts +6 -1
- package/dist/src/routes/portal.d.ts.map +1 -1
- package/dist/src/routes/portal.js +75 -10
- package/dist/src/routes/portal.js.map +1 -1
- package/dist/src/routes/portfolio.d.ts.map +1 -1
- package/dist/src/routes/portfolio.js +5 -1
- package/dist/src/routes/portfolio.js.map +1 -1
- package/dist/src/routes/prompts.d.ts.map +1 -1
- package/dist/src/routes/prompts.js +36 -2
- package/dist/src/routes/prompts.js.map +1 -1
- package/dist/src/routes/public-events.d.ts.map +1 -1
- package/dist/src/routes/public-events.js +4 -1
- package/dist/src/routes/public-events.js.map +1 -1
- package/dist/src/routes/public-stats.d.ts.map +1 -1
- package/dist/src/routes/public-stats.js +29 -10
- package/dist/src/routes/public-stats.js.map +1 -1
- package/dist/src/routes/schedules.d.ts +3 -0
- package/dist/src/routes/schedules.d.ts.map +1 -1
- package/dist/src/routes/schedules.js +14 -1
- package/dist/src/routes/schedules.js.map +1 -1
- package/dist/src/routes/stats.d.ts.map +1 -1
- package/dist/src/routes/stats.js +5 -1
- package/dist/src/routes/stats.js.map +1 -1
- package/dist/src/routes/storage-files.d.ts +4 -0
- package/dist/src/routes/storage-files.d.ts.map +1 -1
- package/dist/src/routes/storage-files.js +11 -0
- package/dist/src/routes/storage-files.js.map +1 -1
- package/dist/src/routes/subdomains.d.ts +9 -0
- package/dist/src/routes/subdomains.d.ts.map +1 -1
- package/dist/src/routes/subdomains.js +66 -5
- package/dist/src/routes/subdomains.js.map +1 -1
- package/dist/src/routes/unfurl.d.ts.map +1 -1
- package/dist/src/routes/unfurl.js +13 -3
- package/dist/src/routes/unfurl.js.map +1 -1
- package/dist/src/routes/upload.d.ts +11 -0
- package/dist/src/routes/upload.d.ts.map +1 -1
- package/dist/src/routes/upload.js +99 -9
- package/dist/src/routes/upload.js.map +1 -1
- package/dist/src/routes/wallet.d.ts +3 -0
- package/dist/src/routes/wallet.d.ts.map +1 -1
- package/dist/src/routes/wallet.js +6 -1
- package/dist/src/routes/wallet.js.map +1 -1
- package/dist/src/routes/webmcp.d.ts +8 -0
- package/dist/src/routes/webmcp.d.ts.map +1 -1
- package/dist/src/routes/webmcp.js +96 -49
- package/dist/src/routes/webmcp.js.map +1 -1
- package/dist/src/routes/wellknown.d.ts.map +1 -1
- package/dist/src/routes/wellknown.js +1 -0
- package/dist/src/routes/wellknown.js.map +1 -1
- package/dist/src/server-bootstrap/config-init.d.ts.map +1 -1
- package/dist/src/server-bootstrap/config-init.js +2 -0
- package/dist/src/server-bootstrap/config-init.js.map +1 -1
- package/dist/src/server-bootstrap/routes-loader.d.ts +4 -2
- package/dist/src/server-bootstrap/routes-loader.d.ts.map +1 -1
- package/dist/src/server-bootstrap/routes-loader.js +11 -22
- package/dist/src/server-bootstrap/routes-loader.js.map +1 -1
- package/dist/src/server-bootstrap/service-init.js +3 -1
- package/dist/src/server-bootstrap/service-init.js.map +1 -1
- package/dist/src/server-bootstrap/static-files.d.ts.map +1 -1
- package/dist/src/server-bootstrap/static-files.js +3 -1
- package/dist/src/server-bootstrap/static-files.js.map +1 -1
- package/dist/src/services/agent-statistics.d.ts.map +1 -1
- package/dist/src/services/agent-statistics.js +4 -1
- package/dist/src/services/agent-statistics.js.map +1 -1
- package/dist/src/services/app-agent-deploy.d.ts.map +1 -1
- package/dist/src/services/app-agent-deploy.js +4 -1
- package/dist/src/services/app-agent-deploy.js.map +1 -1
- package/dist/src/services/app-agent-surface.d.ts +78 -0
- package/dist/src/services/app-agent-surface.d.ts.map +1 -0
- package/dist/src/services/app-agent-surface.js +74 -0
- package/dist/src/services/app-agent-surface.js.map +1 -0
- package/dist/src/services/app-tool-names.d.ts +15 -0
- package/dist/src/services/app-tool-names.d.ts.map +1 -0
- package/dist/src/services/app-tool-names.js +24 -0
- package/dist/src/services/app-tool-names.js.map +1 -0
- package/dist/src/services/appdev-overview.d.ts.map +1 -1
- package/dist/src/services/appdev-overview.js +3 -2
- package/dist/src/services/appdev-overview.js.map +1 -1
- package/dist/src/services/attachment-duplication.js +3 -3
- package/dist/src/services/attachment-duplication.js.map +1 -1
- package/dist/src/services/build-extension-prompt.d.ts +40 -0
- package/dist/src/services/build-extension-prompt.d.ts.map +1 -0
- package/dist/src/services/build-extension-prompt.js +253 -0
- package/dist/src/services/build-extension-prompt.js.map +1 -0
- package/dist/src/services/cache-cleanup.d.ts.map +1 -1
- package/dist/src/services/cache-cleanup.js +2 -1
- package/dist/src/services/cache-cleanup.js.map +1 -1
- package/dist/src/services/call-timing.d.ts.map +1 -1
- package/dist/src/services/call-timing.js +2 -1
- package/dist/src/services/call-timing.js.map +1 -1
- package/dist/src/services/capability-invoke.d.ts +6 -1
- package/dist/src/services/capability-invoke.d.ts.map +1 -1
- package/dist/src/services/capability-invoke.js +14 -2
- package/dist/src/services/capability-invoke.js.map +1 -1
- package/dist/src/services/catalogue-sync.d.ts.map +1 -1
- package/dist/src/services/catalogue-sync.js +1 -0
- package/dist/src/services/catalogue-sync.js.map +1 -1
- package/dist/src/services/component-registrar.d.ts.map +1 -1
- package/dist/src/services/component-registrar.js +22 -6
- package/dist/src/services/component-registrar.js.map +1 -1
- package/dist/src/services/config-loader.d.ts.map +1 -1
- package/dist/src/services/config-loader.js +6 -1
- package/dist/src/services/config-loader.js.map +1 -1
- package/dist/src/services/config-schema.d.ts.map +1 -1
- package/dist/src/services/config-schema.js +1 -0
- package/dist/src/services/config-schema.js.map +1 -1
- package/dist/src/services/connect-tunnel.d.ts.map +1 -1
- package/dist/src/services/connect-tunnel.js +17 -6
- package/dist/src/services/connect-tunnel.js.map +1 -1
- package/dist/src/services/consent.d.ts.map +1 -1
- package/dist/src/services/consent.js +3 -1
- package/dist/src/services/consent.js.map +1 -1
- package/dist/src/services/consul-config.d.ts.map +1 -1
- package/dist/src/services/consul-config.js +7 -2
- package/dist/src/services/consul-config.js.map +1 -1
- package/dist/src/services/contacts.js +4 -2
- package/dist/src/services/contacts.js.map +1 -1
- package/dist/src/services/core-jobs.js +1 -1
- package/dist/src/services/core-jobs.js.map +1 -1
- package/dist/src/services/db/agent-messages-overview-db-service.d.ts.map +1 -1
- package/dist/src/services/db/agent-messages-overview-db-service.js +2 -1
- package/dist/src/services/db/agent-messages-overview-db-service.js.map +1 -1
- package/dist/src/services/db/agent-quality-overview-db-service.d.ts.map +1 -1
- package/dist/src/services/db/agent-quality-overview-db-service.js +2 -1
- package/dist/src/services/db/agent-quality-overview-db-service.js.map +1 -1
- package/dist/src/services/db/messages-inbox-db-service.d.ts.map +1 -1
- package/dist/src/services/db/messages-inbox-db-service.js +3 -2
- package/dist/src/services/db/messages-inbox-db-service.js.map +1 -1
- package/dist/src/services/db/messaging-db-service.d.ts.map +1 -1
- package/dist/src/services/db/messaging-db-service.js +3 -2
- package/dist/src/services/db/messaging-db-service.js.map +1 -1
- package/dist/src/services/db/wallet-tab-db-service.d.ts +3 -3
- package/dist/src/services/doc-images.d.ts.map +1 -1
- package/dist/src/services/doc-images.js +7 -4
- package/dist/src/services/doc-images.js.map +1 -1
- package/dist/src/services/ecosystem-automation-notify.d.ts.map +1 -1
- package/dist/src/services/ecosystem-automation-notify.js +10 -4
- package/dist/src/services/ecosystem-automation-notify.js.map +1 -1
- package/dist/src/services/ecosystem-automation.d.ts.map +1 -1
- package/dist/src/services/ecosystem-automation.js +3 -2
- package/dist/src/services/ecosystem-automation.js.map +1 -1
- package/dist/src/services/ecosystem-events.js +1 -1
- package/dist/src/services/ecosystem-events.js.map +1 -1
- package/dist/src/services/entitlement-merge.d.ts +50 -0
- package/dist/src/services/entitlement-merge.d.ts.map +1 -0
- package/dist/src/services/entitlement-merge.js +116 -0
- package/dist/src/services/entitlement-merge.js.map +1 -0
- package/dist/src/services/entitlement-money.d.ts.map +1 -1
- package/dist/src/services/entitlement-money.js +4 -1
- package/dist/src/services/entitlement-money.js.map +1 -1
- package/dist/src/services/exchange-market.d.ts +47 -2
- package/dist/src/services/exchange-market.d.ts.map +1 -1
- package/dist/src/services/exchange-market.js +80 -9
- package/dist/src/services/exchange-market.js.map +1 -1
- package/dist/src/services/exchange-projection.d.ts +8 -2
- package/dist/src/services/exchange-projection.d.ts.map +1 -1
- package/dist/src/services/exchange-projection.js +146 -21
- package/dist/src/services/exchange-projection.js.map +1 -1
- package/dist/src/services/exchange-proposals.d.ts.map +1 -1
- package/dist/src/services/exchange-proposals.js +4 -2
- package/dist/src/services/exchange-proposals.js.map +1 -1
- package/dist/src/services/extension-purchase.d.ts +36 -0
- package/dist/src/services/extension-purchase.d.ts.map +1 -0
- package/dist/src/services/extension-purchase.js +110 -0
- package/dist/src/services/extension-purchase.js.map +1 -0
- package/dist/src/services/extension-runtime.d.ts +23 -1
- package/dist/src/services/extension-runtime.d.ts.map +1 -1
- package/dist/src/services/extension-runtime.js +21 -4
- package/dist/src/services/extension-runtime.js.map +1 -1
- package/dist/src/services/extension-secrets.d.ts +8 -0
- package/dist/src/services/extension-secrets.d.ts.map +1 -1
- package/dist/src/services/extension-secrets.js +14 -0
- package/dist/src/services/extension-secrets.js.map +1 -1
- package/dist/src/services/federation-availability.d.ts.map +1 -1
- package/dist/src/services/federation-availability.js +1 -0
- package/dist/src/services/federation-availability.js.map +1 -1
- package/dist/src/services/federation-book.js +15 -7
- package/dist/src/services/federation-book.js.map +1 -1
- package/dist/src/services/federation-helpers.d.ts.map +1 -1
- package/dist/src/services/federation-helpers.js +1 -0
- package/dist/src/services/federation-helpers.js.map +1 -1
- package/dist/src/services/federation.d.ts.map +1 -1
- package/dist/src/services/federation.js +8 -6
- package/dist/src/services/federation.js.map +1 -1
- package/dist/src/services/gate-expiry.d.ts.map +1 -1
- package/dist/src/services/gate-expiry.js +2 -1
- package/dist/src/services/gate-expiry.js.map +1 -1
- package/dist/src/services/genesis-sync.d.ts.map +1 -1
- package/dist/src/services/genesis-sync.js +9 -4
- package/dist/src/services/genesis-sync.js.map +1 -1
- package/dist/src/services/handbooks/commerce.d.ts +13 -0
- package/dist/src/services/handbooks/commerce.d.ts.map +1 -0
- package/dist/src/services/handbooks/commerce.js +60 -0
- package/dist/src/services/handbooks/commerce.js.map +1 -0
- package/dist/src/services/handbooks/index.d.ts +1 -0
- package/dist/src/services/handbooks/index.d.ts.map +1 -1
- package/dist/src/services/handbooks/index.js +2 -2
- package/dist/src/services/handbooks/index.js.map +1 -1
- package/dist/src/services/hooks.d.ts.map +1 -1
- package/dist/src/services/hooks.js +2 -0
- package/dist/src/services/hooks.js.map +1 -1
- package/dist/src/services/invitations.d.ts.map +1 -1
- package/dist/src/services/invitations.js +2 -0
- package/dist/src/services/invitations.js.map +1 -1
- package/dist/src/services/living-author.d.ts.map +1 -1
- package/dist/src/services/living-author.js +4 -1
- package/dist/src/services/living-author.js.map +1 -1
- package/dist/src/services/living-pulse.js +18 -6
- package/dist/src/services/living-pulse.js.map +1 -1
- package/dist/src/services/mailbox-notification.d.ts.map +1 -1
- package/dist/src/services/mailbox-notification.js +1 -0
- package/dist/src/services/mailbox-notification.js.map +1 -1
- package/dist/src/services/match-notification.d.ts.map +1 -1
- package/dist/src/services/match-notification.js +2 -1
- package/dist/src/services/match-notification.js.map +1 -1
- package/dist/src/services/matching.d.ts.map +1 -1
- package/dist/src/services/matching.js +5 -2
- package/dist/src/services/matching.js.map +1 -1
- package/dist/src/services/memory-replication.d.ts.map +1 -1
- package/dist/src/services/memory-replication.js +3 -1
- package/dist/src/services/memory-replication.js.map +1 -1
- package/dist/src/services/message-broadcast.d.ts.map +1 -1
- package/dist/src/services/message-broadcast.js +2 -1
- package/dist/src/services/message-broadcast.js.map +1 -1
- package/dist/src/services/message-delivery.d.ts.map +1 -1
- package/dist/src/services/message-delivery.js +9 -4
- package/dist/src/services/message-delivery.js.map +1 -1
- package/dist/src/services/metered-access.d.ts +148 -0
- package/dist/src/services/metered-access.d.ts.map +1 -0
- package/dist/src/services/metered-access.js +128 -0
- package/dist/src/services/metered-access.js.map +1 -0
- package/dist/src/services/metered-entitlements.d.ts +140 -5
- package/dist/src/services/metered-entitlements.d.ts.map +1 -1
- package/dist/src/services/metered-entitlements.js +247 -30
- package/dist/src/services/metered-entitlements.js.map +1 -1
- package/dist/src/services/metered-settlement.d.ts +45 -0
- package/dist/src/services/metered-settlement.d.ts.map +1 -0
- package/dist/src/services/metered-settlement.js +117 -0
- package/dist/src/services/metered-settlement.js.map +1 -0
- package/dist/src/services/network-policy.d.ts.map +1 -1
- package/dist/src/services/network-policy.js +6 -2
- package/dist/src/services/network-policy.js.map +1 -1
- package/dist/src/services/notebook-classify.d.ts.map +1 -1
- package/dist/src/services/notebook-classify.js +7 -2
- package/dist/src/services/notebook-classify.js.map +1 -1
- package/dist/src/services/notebook-plan.d.ts.map +1 -1
- package/dist/src/services/notebook-plan.js +4 -1
- package/dist/src/services/notebook-plan.js.map +1 -1
- package/dist/src/services/notify.d.ts.map +1 -1
- package/dist/src/services/notify.js +6 -3
- package/dist/src/services/notify.js.map +1 -1
- package/dist/src/services/openrouter.d.ts.map +1 -1
- package/dist/src/services/openrouter.js +1 -0
- package/dist/src/services/openrouter.js.map +1 -1
- package/dist/src/services/organism-export.d.ts.map +1 -1
- package/dist/src/services/organism-export.js +4 -1
- package/dist/src/services/organism-export.js.map +1 -1
- package/dist/src/services/organism-import.d.ts.map +1 -1
- package/dist/src/services/organism-import.js +5 -1
- package/dist/src/services/organism-import.js.map +1 -1
- package/dist/src/services/perf-trace.js +3 -1
- package/dist/src/services/perf-trace.js.map +1 -1
- package/dist/src/services/personal-tunnel.js +14 -8
- package/dist/src/services/personal-tunnel.js.map +1 -1
- package/dist/src/services/presence.d.ts.map +1 -1
- package/dist/src/services/presence.js +11 -5
- package/dist/src/services/presence.js.map +1 -1
- package/dist/src/services/protected-resource.d.ts +60 -0
- package/dist/src/services/protected-resource.d.ts.map +1 -0
- package/dist/src/services/protected-resource.js +137 -0
- package/dist/src/services/protected-resource.js.map +1 -0
- package/dist/src/services/realtime-manager.d.ts.map +1 -1
- package/dist/src/services/realtime-manager.js +8 -5
- package/dist/src/services/realtime-manager.js.map +1 -1
- package/dist/src/services/safe-zip.d.ts.map +1 -1
- package/dist/src/services/safe-zip.js +4 -1
- package/dist/src/services/safe-zip.js.map +1 -1
- package/dist/src/services/scheduler-extension-job.js +2 -2
- package/dist/src/services/scheduler-extension-job.js.map +1 -1
- package/dist/src/services/scheduler.js +13 -7
- package/dist/src/services/scheduler.js.map +1 -1
- package/dist/src/services/security-incident.d.ts.map +1 -1
- package/dist/src/services/security-incident.js +7 -2
- package/dist/src/services/security-incident.js.map +1 -1
- package/dist/src/services/site-sync.d.ts.map +1 -1
- package/dist/src/services/site-sync.js +1 -0
- package/dist/src/services/site-sync.js.map +1 -1
- package/dist/src/services/site.d.ts +1 -1
- package/dist/src/services/site.d.ts.map +1 -1
- package/dist/src/services/site.js +29 -8
- package/dist/src/services/site.js.map +1 -1
- package/dist/src/services/structure-overview.d.ts.map +1 -1
- package/dist/src/services/structure-overview.js +4 -1
- package/dist/src/services/structure-overview.js.map +1 -1
- package/dist/src/services/structure-snapshot.d.ts.map +1 -1
- package/dist/src/services/structure-snapshot.js +3 -2
- package/dist/src/services/structure-snapshot.js.map +1 -1
- package/dist/src/services/sync-scheduler.js +3 -2
- package/dist/src/services/sync-scheduler.js.map +1 -1
- package/dist/src/services/tracked-response.js +1 -1
- package/dist/src/services/tracked-response.js.map +1 -1
- package/dist/src/services/trust-broadcast.d.ts.map +1 -1
- package/dist/src/services/trust-broadcast.js +1 -0
- package/dist/src/services/trust-broadcast.js.map +1 -1
- package/dist/src/services/upload-zip.d.ts +7 -0
- package/dist/src/services/upload-zip.d.ts.map +1 -1
- package/dist/src/services/upload-zip.js +19 -85
- package/dist/src/services/upload-zip.js.map +1 -1
- package/dist/src/services/web-bot-auth.d.ts.map +1 -1
- package/dist/src/services/web-bot-auth.js +1 -0
- package/dist/src/services/web-bot-auth.js.map +1 -1
- package/dist/src/services/workflow/engine-steps.d.ts.map +1 -1
- package/dist/src/services/workflow/engine-steps.js +12 -6
- package/dist/src/services/workflow/engine-steps.js.map +1 -1
- package/dist/src/services/workspace-export.d.ts.map +1 -1
- package/dist/src/services/workspace-export.js +5 -2
- package/dist/src/services/workspace-export.js.map +1 -1
- package/dist/src/services/workspace-import.d.ts.map +1 -1
- package/dist/src/services/workspace-import.js +2 -1
- package/dist/src/services/workspace-import.js.map +1 -1
- package/dist/src/services/workspace-versions.d.ts.map +1 -1
- package/dist/src/services/workspace-versions.js +0 -0
- package/dist/src/services/workspace-versions.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/db-types.d.ts +5 -0
- package/dist/src/storage/providers/postgres-kysely/db-types.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/helpers.d.ts +11 -0
- package/dist/src/storage/providers/postgres-kysely/helpers.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/helpers.js +14 -0
- package/dist/src/storage/providers/postgres-kysely/helpers.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/app-grants.d.ts +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/app-grants.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/app-grants.js +6 -0
- package/dist/src/storage/providers/postgres-kysely/methods/app-grants.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/capabilities.js +3 -3
- package/dist/src/storage/providers/postgres-kysely/methods/capabilities.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/ecosystem.js +3 -3
- package/dist/src/storage/providers/postgres-kysely/methods/ecosystem.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/federation.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/federation.js +12 -10
- package/dist/src/storage/providers/postgres-kysely/methods/federation.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/identity.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/identity.js +26 -12
- package/dist/src/storage/providers/postgres-kysely/methods/identity.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/marketplace.js +5 -5
- package/dist/src/storage/providers/postgres-kysely/methods/marketplace.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/node-ext-escrow.d.ts +9 -0
- package/dist/src/storage/providers/postgres-kysely/methods/node-ext-escrow.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/node-ext-escrow.js +31 -27
- package/dist/src/storage/providers/postgres-kysely/methods/node-ext-escrow.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/organisms.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/organisms.js +10 -14
- package/dist/src/storage/providers/postgres-kysely/methods/organisms.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/otk.js +3 -3
- package/dist/src/storage/providers/postgres-kysely/methods/otk.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/packages.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/packages.js +4 -14
- package/dist/src/storage/providers/postgres-kysely/methods/packages.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/template-listings.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/template-listings.js +11 -10
- package/dist/src/storage/providers/postgres-kysely/methods/template-listings.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/wallet.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/methods/wallet.js +3 -1
- package/dist/src/storage/providers/postgres-kysely/methods/wallet.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/migrate.d.ts.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/migrate.js +3 -0
- package/dist/src/storage/providers/postgres-kysely/migrate.js.map +1 -1
- package/dist/src/storage/providers/postgres-kysely/migrations/0013_ghii_password_lockout.sql +12 -0
- package/dist/src/storage/providers/postgres-kysely/migrations/0014_transaction_initiator.sql +6 -0
- package/dist/src/storage/providers/postgres-kysely/migrations/0015_app_grant_spend_cap.sql +5 -0
- package/dist/src/storage/providers/sqlite/methods/apps.d.ts +1 -1
- package/dist/src/storage/providers/sqlite/methods/apps.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/apps.js +12 -2
- package/dist/src/storage/providers/sqlite/methods/apps.js.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/community.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/community.js +6 -1
- package/dist/src/storage/providers/sqlite/methods/community.js.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/identity-nodes.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/identity-nodes.js +9 -2
- package/dist/src/storage/providers/sqlite/methods/identity-nodes.js.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/work.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/methods/work.js +4 -2
- package/dist/src/storage/providers/sqlite/methods/work.js.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/community.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/community.js +6 -1
- package/dist/src/storage/providers/sqlite/repos/community.js.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/identity.d.ts +3 -0
- package/dist/src/storage/providers/sqlite/repos/identity.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/identity.js +13 -4
- package/dist/src/storage/providers/sqlite/repos/identity.js.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/work.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/repos/work.js +4 -2
- package/dist/src/storage/providers/sqlite/repos/work.js.map +1 -1
- package/dist/src/storage/providers/sqlite/schema-tables-1.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/schema-tables-1.js +1 -0
- package/dist/src/storage/providers/sqlite/schema-tables-1.js.map +1 -1
- package/dist/src/storage/providers/sqlite/schema-tables-2.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/schema-tables-2.js +2 -0
- package/dist/src/storage/providers/sqlite/schema-tables-2.js.map +1 -1
- package/dist/src/storage/providers/sqlite/schema.d.ts.map +1 -1
- package/dist/src/storage/providers/sqlite/schema.js +14 -1
- package/dist/src/storage/providers/sqlite/schema.js.map +1 -1
- package/dist/src/storage/repositories/app-grant.repository.d.ts +1 -1
- package/dist/src/storage/repositories/app-grant.repository.d.ts.map +1 -1
- package/dist/src/storage/types/auth.d.ts +9 -0
- package/dist/src/storage/types/auth.d.ts.map +1 -1
- package/dist/src/storage/types/commerce.d.ts +13 -0
- package/dist/src/storage/types/commerce.d.ts.map +1 -1
- package/dist/src/utils/app-agent-discovery.d.ts +31 -0
- package/dist/src/utils/app-agent-discovery.d.ts.map +1 -0
- package/dist/src/utils/app-agent-discovery.js +96 -0
- package/dist/src/utils/app-agent-discovery.js.map +1 -0
- package/dist/src/utils/app-protect.d.ts.map +1 -1
- package/dist/src/utils/app-protect.js +1 -0
- package/dist/src/utils/app-protect.js.map +1 -1
- package/dist/src/utils/env-validator.d.ts.map +1 -1
- package/dist/src/utils/env-validator.js +5 -1
- package/dist/src/utils/env-validator.js.map +1 -1
- package/dist/src/utils/gaii.d.ts +50 -0
- package/dist/src/utils/gaii.d.ts.map +1 -1
- package/dist/src/utils/gaii.js +66 -0
- package/dist/src/utils/gaii.js.map +1 -1
- package/dist/src/utils/url-validator.d.ts.map +1 -1
- package/dist/src/utils/url-validator.js +4 -1
- package/dist/src/utils/url-validator.js.map +1 -1
- package/dist/src/utils/version.d.ts.map +1 -1
- package/dist/src/utils/version.js +1 -0
- package/dist/src/utils/version.js.map +1 -1
- package/dist/static/sdk-libs/auth/session.js +7 -3
- package/dist/static/sdk-libs/dist/aimeat-auth.js +1 -1
- package/dist/static/sdk-libs/dist/aimeat-exchange.js +675 -0
- package/dist/static/sdk-libs/dist/aimeat-game.js +1555 -0
- package/dist/static/sdk-libs/dist/aimeat-webmcp.js +46 -0
- package/dist/static/sdk-libs/exchange/browse.js +81 -0
- package/dist/static/sdk-libs/exchange/client.js +131 -0
- package/dist/static/sdk-libs/exchange/contracts.js +228 -0
- package/dist/static/sdk-libs/exchange/demand.js +106 -0
- package/dist/static/sdk-libs/exchange/earnings.js +39 -0
- package/dist/static/sdk-libs/exchange/format.js +51 -0
- package/dist/static/sdk-libs/exchange/index.js +70 -0
- package/dist/static/sdk-libs/exchange/odps-completeness.js +177 -0
- package/dist/static/sdk-libs/exchange/sell.js +253 -0
- package/dist/static/sdk-libs/game/board.js +331 -0
- package/dist/static/sdk-libs/game/dom.js +223 -0
- package/dist/static/sdk-libs/game/i18n.js +201 -0
- package/dist/static/sdk-libs/game/index.js +72 -0
- package/dist/static/sdk-libs/game/markers.js +150 -0
- package/dist/static/sdk-libs/game/menu.js +260 -0
- package/dist/static/sdk-libs/game/overlay.js +193 -0
- package/dist/static/sdk-libs/game/progress.js +280 -0
- package/dist/static/sdk-libs/game/score.js +134 -0
- package/dist/static/sdk-libs/game/screen.js +120 -0
- package/dist/static/sdk-libs/game/units.js +55 -0
- package/dist/static/sdk-libs/webmcp/index.js +63 -0
- package/package.json +2 -1
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @licstart The following is the entire license notice for the
|
|
3
|
+
* JavaScript code in this page
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2024 Mozilla Foundation
|
|
6
|
+
*
|
|
7
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
* you may not use this file except in compliance with the License.
|
|
9
|
+
* You may obtain a copy of the License at
|
|
10
|
+
*
|
|
11
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
*
|
|
13
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
* See the License for the specific language governing permissions and
|
|
17
|
+
* limitations under the License.
|
|
18
|
+
*
|
|
19
|
+
* @licend The above is the entire license notice for the
|
|
20
|
+
* JavaScript code in this page
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* pdfjsVersion = 6.1.200
|
|
24
|
+
* pdfjsBuild = 6353acefe
|
|
25
|
+
*/
|
|
26
|
+
const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[1/0,1/0,-1/0,-1/0],i=new Float32Array(e),n=[.001,0,0,.001,0,0],s=1.35,a="http://www.w3.org/2000/svg",r=1,o=2,l=4,h=16,c=32,d=64,u=128,p=256,g={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},m="pdfjs_internal_id_",f="pdfjs_internal_editor_",b={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},y={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},v={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},A=0,w=1,x=2,C=3,E=3,S=4,T={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},k={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},_=1,M=2,D=3,P=4,I=5,F={ERRORS:0,WARNINGS:1,INFOS:5},B={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},L=0,O=1,R=2,N=3,U=4,H={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let z=F.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(z=t)}function getVerbosityLevel(){return z}function info(t){z>=F.INFOS&&console.info(`Info: ${t}`)}function warn(t){z>=F.WARNINGS&&console.warn(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function updateUrlHash(t,e,i=!1){const n=URL.parse(t);if(n){n.hash=e;return n.href}return i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function stripPath(t){return t.substring(t.lastIndexOf("/")+1)}function shadow(t,e,i,n=!1){Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1});return i}const G=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends G{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends G{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends G{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends G{constructor(t,e,i){super(t,"ResponseException");this.status=e;this.missing=i}}class FormatError extends G{constructor(t){super(t,"FormatError")}}class AbortException extends G{constructor(t){super(t,"AbortException")}}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}class FeatureTest{static get isLittleEndian(){const t=new Uint8Array(4);t[0]=1;return shadow(this,"isLittleEndian",1===new Uint32Array(t.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:t,userAgent:e}=navigator;return shadow(this,"platform",{isAndroid:e.includes("Android"),isLinux:t.includes("Linux"),isMac:t.includes("Mac"),isWindows:t.includes("Win"),isFirefox:e.includes("Firefox")})}static get isCanvasFilterSupported(){let t;this.isOffscreenCanvasSupported?t=new OffscreenCanvas(1,1).getContext("2d"):"undefined"!=typeof document&&(t=document.createElement("canvas").getContext("2d"));return shadow(this,"isCanvasFilterSupported",void 0!==t?.filter)}static get isAlphaColorInputSupported(){if("undefined"==typeof document)return shadow(this,"isAlphaColorInputSupported",!1);const t=document.createElement("input");t.type="color";t.setAttribute("alpha","");t.value="#ff000080";return shadow(this,"isAlphaColorInputSupported","#ff0000"!==t.value)}static get isBackdropFilterSupported(){return shadow(this,"isBackdropFilterSupported","undefined"!=typeof CSS&&CSS.supports("backdrop-filter","blur(1px)"))}}class Util{static get hexNums(){return shadow(this,"hexNums",Array.from(Array(256).keys(),t=>t.toString(16).padStart(2,"0")))}static makeHexColor(t,e,i){return`#${this.hexNums[t]}${this.hexNums[e]}${this.hexNums[i]}`}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static multiplyByDOMMatrix(t,e){return[t[0]*e.a+t[2]*e.b,t[1]*e.a+t[3]*e.b,t[0]*e.c+t[2]*e.d,t[1]*e.c+t[3]*e.d,t[0]*e.e+t[2]*e.f+t[4],t[1]*e.e+t[3]*e.f+t[5]]}static applyTransform(t,e,i=0){const n=t[i],s=t[i+1];t[i]=n*e[0]+s*e[2]+e[4];t[i+1]=n*e[1]+s*e[3]+e[5]}static applyTransformToBezier(t,e,i=0){const n=e[0],s=e[1],a=e[2],r=e[3],o=e[4],l=e[5];for(let e=0;e<6;e+=2){const h=t[i+e],c=t[i+e+1];t[i+e]=h*n+c*a+o;t[i+e+1]=h*s+c*r+l}}static applyInverseTransform(t,e){const i=t[0],n=t[1],s=e[0]*e[3]-e[1]*e[2];t[0]=(i*e[3]-n*e[2]+e[2]*e[5]-e[4]*e[3])/s;t[1]=(-i*e[1]+n*e[0]+e[4]*e[1]-e[5]*e[0])/s}static axialAlignedBoundingBox(t,e,i){const n=e[0],s=e[1],a=e[2],r=e[3],o=e[4],l=e[5],h=t[0],c=t[1],d=t[2],u=t[3];let p=n*h+o,g=p,m=n*d+o,f=m,b=r*c+l,y=b,v=r*u+l,A=v;if(0!==s||0!==a){const t=s*h,e=s*d,i=a*c,n=a*u;p+=i;f+=i;m+=n;g+=n;b+=t;A+=t;v+=e;y+=e}i[0]=Math.min(i[0],p,m,g,f);i[1]=Math.min(i[1],b,v,y,A);i[2]=Math.max(i[2],p,m,g,f);i[3]=Math.max(i[3],b,v,y,A)}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t,e){const i=t[0],n=t[1],s=t[2],a=t[3],r=i**2+n**2,o=i*s+n*a,l=s**2+a**2,h=(r+l)/2,c=Math.sqrt(h**2-(r*l-o**2));e[0]=Math.sqrt(h+c||1);e[1]=Math.sqrt(h-c||1)}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>n)return null;const s=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return s>a?null:[i,s,n,a]}static pointBoundingBox(t,e,i){i[0]=Math.min(i[0],t);i[1]=Math.min(i[1],e);i[2]=Math.max(i[2],t);i[3]=Math.max(i[3],e)}static rectBoundingBox(t,e,i,n,s){s[0]=Math.min(s[0],t,i);s[1]=Math.min(s[1],e,n);s[2]=Math.max(s[2],t,i);s[3]=Math.max(s[3],e,n)}static#t(t,e,i,n,s,a,r,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*n,g=c*(c*(c*s+3*l*a)+3*d*r)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,n,s,a,r,o,l,h,c,d){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,n,s,a,r,o,-c/h,d);return}const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,n,s,a,r,o,(-h+p)/g,d);this.#t(t,e,i,n,s,a,r,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,n,s,a,r,o,l){l[0]=Math.min(l[0],t,r);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,r);l[3]=Math.max(l[3],e,o);this.#e(t,i,s,r,e,n,a,o,3*(3*(i-s)-t+r),6*(t-2*i+s),3*(i-t),l);this.#e(t,i,s,r,e,n,a,o,3*(3*(n-a)-e+o),6*(e-2*n+a),3*(n-e),l)}}let W=null,V=null;function normalizeUnicode(t){if(!W){W=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;V=new Map([["ſt","ſt"]])}return t.replaceAll(W,(t,e,i)=>e?e.normalize("NFKC"):V.get(i))}function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(e<i)return String.fromCharCode.apply(null,t);const n=[];for(let s=0;s<e;s+=i){const a=Math.min(s+i,e),r=t.subarray(s,a);n.push(String.fromCharCode.apply(null,r))}return n.join("")}(t)}const makeArr=()=>[],makeMap=()=>new Map,makeObj=()=>Object.create(null);function MathClamp(t,e,i){return Math.min(Math.max(t,e),i)}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:n,offsetX:s=0,offsetY:a=0,dontFlip:r=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=n;this.offsetX=s;this.offsetY=a;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,m,f;(n%=360)<0&&(n+=360);switch(n){case 180:h=-1;c=0;d=0;u=1;break;case 90:h=0;c=1;d=1;u=0;break;case 270:h=0;c=-1;d=-1;u=0;break;case 0:h=1;c=0;d=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(r){d=-d;u=-u}if(0===h){p=Math.abs(l-t[1])*i+s;g=Math.abs(o-t[0])*i+a;m=(t[3]-t[1])*i;f=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+s;g=Math.abs(l-t[1])*i+a;m=(t[2]-t[0])*i;f=(t[3]-t[1])*i}this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l];this.width=m;this.height=f}get rawDims(){const t=this.viewBox;return shadow(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:n=this.offsetY,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}convertToViewportPoint(t,e){const i=[t,e];Util.applyTransform(i,this.transform);return i}convertToPdfPoint(t,e){const i=[t,e];Util.applyInverseTransform(i,this.transform);return i}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const n=t.name;if("#text"===n)i=t.value;else{if(!XfaText.shouldBuildText(n))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}class XfaLayer{static setupStorage(t,e,i,n,s){const a=n.getValue(e,{value:null});switch(i.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})});break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){a.value===i.attributes.xfaOn?t.setAttribute("checked",!0):a.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===s)break;t.addEventListener("change",t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})})}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===s)break;t.addEventListener("input",t=>{n.setValue(e,{value:t.target.value})})}break;case"select":if(null!==a.value){t.setAttribute("value",a.value);for(const t of i.children)t.attributes.value===a.value?t.attributes.selected=!0:Object.hasOwn(t.attributes,"selected")&&delete t.attributes.selected}t.addEventListener("input",t=>{const i=t.target.options,s=-1===i.selectedIndex?"":i[i.selectedIndex].value;n.setValue(e,{value:s})})}}static setAttributes({html:t,element:e,storage:i=null,intent:n,linkService:s}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${n}`);for(const[e,i]of Object.entries(a))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}r&&s.addLinkAttributes(t,a.href,a.newWindow);i&&a.dataId&&this.setupStorage(t,a.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,n=t.xfaHtml,s=t.intent||"display",a=document.createElement(n.name);n.attributes&&this.setAttributes({html:a,element:n,intent:s,linkService:i});const r="richText"!==s,o=t.div;o.append(a);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}r&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===n.children.length){if(n.value){const t=document.createTextNode(n.value);a.append(t);r&&XfaText.shouldBuildText(n.name)&&l.push(t)}return{textDivs:l}}const h=[[n,-1,a]];for(;h.length>0;){const[t,n,a]=h.at(-1);if(n+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.push(t);a.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);a.append(d);o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:s,linkService:i});if(o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);r&&XfaText.shouldBuildText(c)&&l.push(t);d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}static getPageViewport(t,{scale:e=1,rotation:i=0}){const{width:n,height:s}=t.attributes.style;return new PageViewport({viewBox:[0,0,parseInt(n,10),parseInt(s,10)],userUnit:1,scale:e,rotation:i})}}class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"blob":return i.blob();case"bytes":return i.bytes();case"json":return i.json()}return i.text()}return new Promise((i,n)=>{const s=new XMLHttpRequest;s.open("GET",t,!0);s.responseType="bytes"===e?"arraybuffer":e;s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE)if(200!==s.status&&0!==s.status)n(new Error(s.statusText));else{switch(e){case"bytes":i(new Uint8Array(s.response));return;case"blob":case"json":i(s.response);return}i(s.responseText)}};s.send(null)})}class RenderingCancelledException extends G{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i<e&&""===t[i].trim();)i++;return"data:"===t.substring(i,i+5).toLowerCase()}function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)}function getFilenameFromUrl(t){[t]=t.split(/[#?]/,1);return stripPath(t)}function getPdfFilenameFromUrl(t,e="document.pdf"){if("string"!=typeof t)return e;if(isDataScheme(t)){warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const i=(t=>{try{return new URL(t)}catch{}try{return new URL(decodeURIComponent(t))}catch{}try{return new URL(t,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(t),"https://foo.bar")}catch{}return null})(t);if(!i)return e;const decode=t=>{try{let e=decodeURIComponent(t);if(e.includes("/")){e=stripPath(e);if(4===e.length&&n.test(e))return t}return e}catch{return t}},n=/\.pdf$/i,s=stripPath(i.pathname);if(n.test(s))return decode(s);if(i.searchParams.size>0){const getLast=t=>[...t].findLast(t=>n.test(t)),t=getLast(i.searchParams.values())??getLast(i.searchParams.keys());if(t)return decode(t)}if(i.hash){const t=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(i.hash);if(t)return decode(t[0])}return e}class StatTimer{#i=new Map;times=[];time(t){this.#i.has(t)&&warn(`Timer is already running for ${t}`);this.#i.set(t,Date.now())}timeEnd(t){this.#i.has(t)||warn(`Timer has not been started for ${t}`);this.times.push({name:t,start:this.#i.get(t),end:Date.now()});this.#i.delete(t)}toString(){const t=Math.max(...this.times.map(t=>t.name.length));return this.times.map(e=>`${e.name.padEnd(t)} ${e.end-e.start}ms\n`).join("")}}function isValidFetchUrl(t,e){const i=e?URL.parse(t,e):URL.parse(t);return/https?:/.test(i?.protocol??"")}function noContextMenu(t){t.preventDefault()}function stopEvent(t){t.preventDefault();t.stopPropagation()}class PDFDateString{static#n;static toDateObject(t){if(t instanceof Date)return t;if(!t||"string"!=typeof t)return null;this.#n||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#n.exec(t);if(!e)return null;const i=parseInt(e[1],10);let n=parseInt(e[2],10);n=n>=1&&n<=12?n-1:0;let s=parseInt(e[3],10);s=s>=1&&s<=31?s:1;let a=parseInt(e[4],10);a=a>=0&&a<=23?a:0;let r=parseInt(e[5],10);r=r>=0&&r<=59?r:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;c=c>=0&&c<=59?c:0;if("-"===l){a+=h;r+=c}else if("+"===l){a-=h;r-=c}return new Date(Date.UTC(i,n,s,a,r,o))}}function getRGBA(t){if(t.startsWith("#")){const e=t.slice(1);return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16),e.length>=8?parseInt(e.slice(6,8),16)/255:1]}if(t.startsWith("rgb(")){const[e,i,n]=t.slice(4,-1).split(",").map(t=>parseInt(t,10));return[e,i,n,1]}if(t.startsWith("rgba(")){const e=t.slice(5,-1).split(",");return[parseInt(e[0],10),parseInt(e[1],10),parseInt(e[2],10),parseFloat(e[3])]}const e=t.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(255*parseFloat(e[1])),Math.round(255*parseFloat(e[2])),Math.round(255*parseFloat(e[3])),void 0!==e[4]&&"none"!==e[4]?parseFloat(e[4]):1]:null}function getRGB(t){const e=getRGBA(t);if(!e){warn(`Not a valid color format: "${t}"`);return[0,0,0]}return e.slice(0,3)}function getCurrentTransform(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform();return[e,i,n,s,a,r]}function getCurrentTransformInverse(t){const{a:e,b:i,c:n,d:s,e:a,f:r}=t.getTransform().invertSelf();return[e,i,n,s,a,r]}function setLayerDimensions(t,e,i=!1,n=!0){if(e instanceof PageViewport){const{pageWidth:n,pageHeight:s}=e.rawDims,{style:a}=t,r=`round(down, var(--total-scale-factor) * ${n}px, var(--scale-round-x))`,o=`round(down, var(--total-scale-factor) * ${s}px, var(--scale-round-y))`;if(i&&e.rotation%180!=0){a.width=o;a.height=r}else{a.width=r;a.height=o}}n&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const{pixelRatio:t}=OutputScale;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}limitCanvas(t,e,i,n,s=-1){let a=1/0,r=1/0,o=1/0;(i=OutputScale.capPixels(i,s))>0&&(a=Math.sqrt(i/(t*e)));if(-1!==n){r=n/t;o=n/e}const l=Math.min(a,r,o);if(this.sx>l||this.sy>l){this.sx=l;this.sy=l;return!0}return!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(t,e){if(e>=0){const i=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+e/100));return t>0?Math.min(t,i):i}return t}}const j=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ColorScheme{static get isDarkMode(){return shadow(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class CSSConstants{static get commentForegroundColor(){const t=document.createElement("span");t.classList.add("comment","sidebar");const{style:e}=t;e.width=e.height="0";e.display="none";e.color="var(--comment-fg-color)";document.body.append(t);const{color:i}=window.getComputedStyle(t);t.remove();return shadow(this,"commentForegroundColor",getRGB(i))}}function applyOpacity(t,e){const i=255*(1-(e=MathClamp(e??1,0,1)));return t.map(t=>Math.round(t*e+i))}function RGBToHSL(t,e){const i=t[0]/255,n=t[1]/255,s=t[2]/255,a=Math.max(i,n,s),r=Math.min(i,n,s),o=(a+r)/2;if(a===r)e[0]=e[1]=0;else{const t=a-r;e[1]=o<.5?t/(a+r):t/(2-a-r);switch(a){case i:e[0]=60*((n-s)/t+(n<s?6:0));break;case n:e[0]=60*((s-i)/t+2);break;case s:e[0]=60*((i-n)/t+4)}}e[2]=o}function HSLToRGB(t,e){const i=t[0],n=t[1],s=t[2],a=(1-Math.abs(2*s-1))*n,r=a*(1-Math.abs(i/60%2-1)),o=s-a/2;switch(Math.floor(i/60)){case 0:e[0]=a+o;e[1]=r+o;e[2]=o;break;case 1:e[0]=r+o;e[1]=a+o;e[2]=o;break;case 2:e[0]=o;e[1]=a+o;e[2]=r+o;break;case 3:e[0]=o;e[1]=r+o;e[2]=a+o;break;case 4:e[0]=r+o;e[1]=o;e[2]=a+o;break;case 5:case 6:e[0]=a+o;e[1]=o;e[2]=r+o}}function computeLuminance(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function contrastRatio(t,e,i){HSLToRGB(t,i);i.map(computeLuminance);const n=.2126*i[0]+.7152*i[1]+.0722*i[2];HSLToRGB(e,i);i.map(computeLuminance);const s=.2126*i[0]+.7152*i[1]+.0722*i[2];return n>s?(n+.05)/(s+.05):(s+.05)/(n+.05)}const $=new Map;function findContrastColor(t,e){const i=t[0]+256*t[1]+65536*t[2]+16777216*e[0]+4294967296*e[1]+1099511627776*e[2];let n=$.get(i);if(n)return n;const s=new Float32Array(9),a=s.subarray(0,3),r=s.subarray(3,6);RGBToHSL(t,r);const o=s.subarray(6,9);RGBToHSL(e,o);const l=o[2]<.5,h=l?12:4.5;r[2]=l?Math.sqrt(r[2]):1-Math.sqrt(1-r[2]);if(contrastRatio(r,o,a)<h){let t,e;if(l){t=r[2];e=1}else{t=0;e=r[2]}const i=.005;for(;e-t>i;){const i=r[2]=(t+e)/2;l===contrastRatio(r,o,a)<h?t=i:e=i}r[2]=l?e:t}HSLToRGB(r,a);n=Util.makeHexColor(Math.round(255*a[0]),Math.round(255*a[1]),Math.round(255*a[2]));$.set(i,n);return n}function renderRichText({html:t,dir:e,className:i},n){const s=document.createDocumentFragment();if("string"==typeof t){const i=document.createElement("p");i.dir=e||"auto";const n=t.split(/\r\n?|\n/);for(let t=0,e=n.length;t<e;++t){const s=n[t];i.append(document.createTextNode(s));t<e-1&&i.append(document.createElement("br"))}s.append(i)}else XfaLayer.render({xfaHtml:t,div:s,intent:"richText"});s.firstElementChild.classList.add("richText",i);n.append(s)}function makePathFromDrawOPS(t){const e=new Path2D;if(!t)return e;for(let i=0,n=t.length;i<n;)switch(t[i++]){case L:e.moveTo(t[i++],t[i++]);break;case O:e.lineTo(t[i++],t[i++]);break;case R:e.bezierCurveTo(t[i++],t[i++],t[i++],t[i++],t[i++],t[i++]);break;case N:e.quadraticCurveTo(t[i++],t[i++],t[i++],t[i++]);break;case U:e.closePath();break;default:warn(`Unrecognized drawing path operator: ${t[i-1]}`)}return e}class EditorToolbar{#s=null;#a=null;#r;#o=null;#l=null;#h=null;#c=null;#d=null;static#u=null;constructor(t){this.#r=t;EditorToolbar.#u||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;if(e instanceof AbortSignal&&!e.aborted){t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#p,{signal:e})}const i=this.#o=document.createElement("div");i.className="buttons";t.append(i);const n=this.#r.toolbarPosition;if(n){const{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-n[0]:n[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*n[1]}% + var(--editor-toolbar-vert-offset))`}return t}get div(){return this.#s}static#p(t){t.stopPropagation()}#g(t){this.#r._focusEventsAllowed=!1;stopEvent(t)}#m(t){this.#r._focusEventsAllowed=!0;stopEvent(t)}#f(t){const e=this.#r._uiManager._signal;if(!(e instanceof AbortSignal)||e.aborted)return!1;t.addEventListener("focusin",this.#g.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#m.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});return!0}hide(){this.#s.classList.add("hidden");this.#a?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#l?.shown();this.#h?.shown()}addDeleteButton(){const{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.classList.add("basic","deleteButton");i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#u[t]);this.#f(i)&&i.addEventListener("click",t=>{e.delete()},{signal:e._signal});this.#o.append(i)}get#b(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#f(e);this.#o.append(e,this.#b);this.#l=t}addComment(t,e=null){if(this.#h)return;const i=t.renderForToolbar();if(!i)return;this.#f(i);const n=this.#c=this.#b;if(e){this.#o.insertBefore(i,e);this.#o.insertBefore(n,e)}else this.#o.append(i,n);this.#h=t;t.toolbar=this}addColorPicker(t){if(this.#a)return;this.#a=t;const e=t.renderButton();this.#f(e);this.#o.append(e,this.#b)}async addEditSignatureButton(t){const e=this.#d=await t.renderEditButton(this.#r);this.#f(e);this.#o.append(e,this.#b)}removeButton(t){if("comment"===t){this.#h?.removeToolbarCommentButton();this.#h=null;this.#c?.remove();this.#c=null}}async addButton(t,e){switch(t){case"colorPicker":e&&this.addColorPicker(e);break;case"altText":e&&await this.addAltText(e);break;case"editSignature":e&&await this.addEditSignatureButton(e);break;case"delete":this.addDeleteButton();break;case"comment":e&&this.addComment(e)}}async addButtonBefore(t,e,i){if(!e&&"comment"===t)return;const n=this.#o.querySelector(i);n&&"comment"===t&&this.addComment(e,n)}updateEditSignatureButton(t){this.#d&&(this.#d.title=t)}remove(){this.#s.remove();this.#a?.destroy();this.#a=null}}class FloatingToolbar{#o=null;#s=null;#y;constructor(t){this.#y=t}#v(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");const e=this.#y._signal;e instanceof AbortSignal&&!e.aborted&&t.addEventListener("contextmenu",noContextMenu,{signal:e});const i=this.#o=document.createElement("div");i.className="buttons";t.append(i);this.#y.hasCommentManager()&&this.#A("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#y.commentSelection("floating_button")});this.#A("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#y.highlightSelection("floating_button")});return t}#w(t,e){let i=0,n=0;for(const s of t){const t=s.y+s.height;if(t<i)continue;const a=s.x+(e?s.width:0);if(t>i){n=a;i=t}else e?a>n&&(n=a):a<n&&(n=a)}return[e?1-n:n,i]}show(t,e,i){const[n,s]=this.#w(e,i),{style:a}=this.#s||=this.#v();t.append(this.#s);a.insetInlineEnd=100*n+"%";a.top=`calc(${100*s}% + var(--editor-toolbar-vert-offset))`}hide(){this.#s.remove()}#A(t,e,i,n){const s=document.createElement("button");s.classList.add("basic",t);s.tabIndex=0;s.setAttribute("data-l10n-id",e);const a=document.createElement("span");s.append(a);a.className="visuallyHidden";a.setAttribute("data-l10n-id",i);const r=this.#y._signal;if(r instanceof AbortSignal&&!r.aborted){s.addEventListener("contextmenu",noContextMenu,{signal:r});s.addEventListener("click",n,{signal:r})}this.#o.append(s)}}const K=Object.freeze({internal:"068f09d6-5b37-4f77-a97a-f8ff4f253b68"});function bindEvents(t,e,i){for(const n of i)e.addEventListener(n,t[n].bind(t))}class CurrentPointers{static#x=NaN;static#C=null;static#E=NaN;static#S=null;static initializeAndAddPointerId(t){(CurrentPointers.#C||=new Set).add(t)}static setPointer(t,e){CurrentPointers.#x||=e;CurrentPointers.#S??=t}static setTimeStamp(t){CurrentPointers.#E=t}static isSamePointerId(t){return CurrentPointers.#x===t}static isSamePointerIdOrRemove(t){if(CurrentPointers.#x===t)return!0;CurrentPointers.#C?.delete(t);return!1}static isSamePointerType(t){return CurrentPointers.#S===t}static isInitializedAndDifferentPointerType(t){return null!==CurrentPointers.#S&&!CurrentPointers.isSamePointerType(t)}static isSameTimeStamp(t){return CurrentPointers.#E===t}static isUsingMultiplePointers(){return CurrentPointers.#C?.size>=1}static clearPointerType(){CurrentPointers.#S=null}static clearPointerIds(){CurrentPointers.#x=NaN;CurrentPointers.#C=null}static clearTimeStamp(){CurrentPointers.#E=NaN}}class IdManager{#T=0;get id(){return`${f}${this.#T++}`}}class ImageManager{#k=getUuid();#T=0;#_=null;static get _isSVGFittingCanvas(){const t=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${a}"><rect width="1" height="1" style="fill:red;"/></svg>`,e=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;return shadow(this,"_isSVGFittingCanvas",i.decode().then(()=>{e.drawImage(i,0,0,1,1,0,0,1,3);return 0===new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0]}))}async#M(t,e){this.#_||=new Map;let i=this.#_.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#k}_${this.#T++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,n=new FileReader,s=new Image,a=new Promise((t,a)=>{s.onload=()=>{i.bitmap=s;i.isSvg=!0;t()};n.onload=async()=>{const t=i.svgUrl=n.result;s.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};s.onerror=n.onerror=a});n.readAsDataURL(t);await a}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#_.set(t,i);i&&this.#_.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:n,type:s}=t;return this.#M(`${e}_${i}_${n}_${s}`,t)}async getFromUrl(t){return this.#M(t,t)}async getFromBlob(t,e){const i=await e;return this.#M(t,i)}async getFromId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#_||=new Map;let i=this.#_.get(t);if(i?.bitmap){i.refCounter+=1;return i}const n=new OffscreenCanvas(e.width,e.height);n.getContext("2d").drawImage(e,0,0);i={bitmap:n.transferToImageBitmap(),id:`image_${this.#k}_${this.#T++}`,refCounter:1,isSvg:!1};this.#_.set(t,i);this.#_.set(i.id,i);return i}getSvgUrl(t){const e=this.#_.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#_||=new Map;const e=this.#_.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#k}_`)}}class CommandManager{#D=[];#P=!1;#I;#F=-1;constructor(t=128){this.#I=t}add({cmd:t,undo:e,post:i,mustExec:n,type:s=NaN,overwriteIfSameType:a=!1,keepUndo:r=!1}){n&&t();if(this.#P)return;const o={cmd:t,undo:e,post:i,type:s};if(-1===this.#F){this.#D.length>0&&(this.#D.length=0);this.#F=0;this.#D.push(o);return}if(a&&this.#D[this.#F].type===s){r&&(o.undo=this.#D[this.#F].undo);this.#D[this.#F]=o;return}const l=this.#F+1;if(l===this.#I)this.#D.splice(0,1);else{this.#F=l;l<this.#D.length&&this.#D.splice(l)}this.#D.push(o)}undo(){if(-1===this.#F)return;this.#P=!0;const{undo:t,post:e}=this.#D[this.#F];t();e?.();this.#P=!1;this.#F-=1}redo(){if(this.#F<this.#D.length-1){this.#F+=1;this.#P=!0;const{cmd:t,post:e}=this.#D[this.#F];t();e?.();this.#P=!1}}hasSomethingToUndo(){return-1!==this.#F}hasSomethingToRedo(){return this.#F<this.#D.length-1}cleanType(t){if(-1!==this.#F){for(let e=this.#F;e>=0;e--)if(this.#D[e].type!==t){this.#D.splice(e+1,this.#F-e);this.#F=e;return}this.#D.length=0;this.#F=-1}}destroy(){this.#D=null}}class KeyboardManager{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;const{isMac:e}=FeatureTest.platform;for(const[i,n,s={}]of t){const t=i.some(t=>t.startsWith("mac+"));for(const a of i){let i=a;if(t){const t=a.startsWith("mac+");if(e!==t)continue;t&&(i=a.slice(4))}const[r,o]=KeyboardManager.#B(i);null!==r&&this.callbacks.getOrInsertComputed(r,makeArr).push({callback:n,options:s,modifiers:o})}}}static#B(t){let e=null,i=0;for(let n of t.split("+")){n=n.trim();if(!n)continue;const s=n.toUpperCase(),a=KeyboardManager[s];if(a)i|=a;else{if(null!==e){warn(`KeyboardManager: multiple keys in shortcut "${t}"`);break}e="SPACE"===s?" ":n}}null===e&&warn(`KeyboardManager: no key found in shortcut "${t}"`);return[e,i]}static#L(t){const e=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(t);return e?e[1]?.toLowerCase()??e[2]:null}exec(t,e){let i=this.callbacks.get(e.key);if(!i){if(/^[a-z]$/i.test(e.key))return;const t=KeyboardManager.#L(e.code);if(null===t||t===e.key)return;i=this.callbacks.get(t);if(!i)return}const n=(e.altKey?KeyboardManager.ALT:0)|(e.ctrlKey?KeyboardManager.CTRL:0)|(e.metaKey?KeyboardManager.META:0)|(e.shiftKey?KeyboardManager.SHIFT:0),s=i.find(t=>t.modifiers===n);if(!s)return;const{callback:a,options:{bubbles:r=!1,args:o=[],checker:l=null}}=s;if(!l||l(t,e)){a.bind(t,...o,e)();r||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";e.style.colorScheme="only light";document.body.append(e);for(const i of t.keys()){e.style.color=i;const n=window.getComputedStyle(e).color;t.set(i,getRGB(n))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every((t,i)=>t===e[i]))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#O=new AbortController;#R=null;#N=null;#U=new Map;#H=new Map;#z=null;#G=null;#W=null;#V=null;#j=new CommandManager;#$=null;#K=null;#X=null;#q=0;#Y=new Set;#Q=null;#J=null;#Z=new Set;_editorUndoBar=null;#tt=!1;#et=!1;#it=!1;#nt=null;#st=null;#at=null;#rt=null;#ot=!1;#lt=null;#ht=new IdManager;#ct=!1;#dt=!1;#ut=!1;#pt=null;#gt=null;#mt=null;#ft=null;#bt=null;#yt=b.NONE;#vt=new Set;#At=null;#wt=null;#xt=null;#Ct=null;#Et=null;#St={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#Tt=[0,0];#kt=null;#_t=null;#Mt=null;#Dt=null;#Pt=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#_t.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(e)&&!t.isEnterHandled}],[["Space"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#_t.contains(document.activeElement)}],[["Escape"],t.unselectAll],[["ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,n,s,a,r,o,l,h,c,d,u,p,g,m){const f=this._signal=this.#O.signal;this.#_t=t;this.#Mt=e;this.#Dt=i;this.#G=n;this.#$=s;this.#wt=a;this.#Et=o;this._eventBus=r;const b={signal:f,...K};r.on("editingaction",this.onEditingAction.bind(this),b);r.on("pagechanging",this.onPageChanging.bind(this),b);r.on("scalechanging",this.onScaleChanging.bind(this),b);r.on("rotationchanging",this.onRotationChanging.bind(this),b);r.on("setpreference",this.onSetPreference.bind(this),b);r.on("switchannotationeditorparams",t=>this.updateParams(t.type,t.value),b);window.addEventListener("pointerdown",()=>{this.#dt=!0},{capture:!0,signal:f});window.addEventListener("pointerup",()=>{this.#dt=!1},{capture:!0,signal:f});window.addEventListener("beforeunload",this.#It.bind(this),{capture:!0,signal:f});this.#Ft();this.#Bt();this.#Lt();this.#W=o.annotationStorage;this.#nt=o.filterFactory;this.#xt=l;this.#rt=h||null;this.#tt=c;this.#et=d;this.#it=u;this.#bt=p||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=g||null;this._supportsPinchToZoom=!1!==m;s?.setSidebarUiManager(this)}destroy(){this.#Pt?.resolve();this.#Pt=null;this.#O?.abort();this.#O=null;this._signal=null;for(const t of this.#H.values())t.destroy();this.#H.clear();this.#U.clear();this.#Z.clear();this.#ft?.clear();this.#R=null;this.#vt.clear();this.#j.destroy();this.#G?.destroy();this.#$?.destroy();this.#wt?.destroy();this.#lt?.hide();this.#lt=null;this.#mt?.destroy();this.#mt=null;this.#N=null;if(this.#st){clearTimeout(this.#st);this.#st=null}if(this.#kt){clearTimeout(this.#kt);this.#kt=null}this._editorUndoBar?.destroy();this.#Et=null}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#bt}get useNewAltTextFlow(){return this.#et}get useNewAltTextWhenAddingImage(){return this.#it}get hcmFilter(){return shadow(this,"hcmFilter",this.#xt?this.#nt.addHCMFilter(this.#xt.foreground,this.#xt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#_t).direction)}get _highlightColors(){return shadow(this,"_highlightColors",this.#rt?new Map(this.#rt.split(",").map(t=>{(t=t.split("=").map(t=>t.trim()))[1]=t[1].toUpperCase();return t})):null)}get highlightColors(){const{_highlightColors:t}=this;if(!t)return shadow(this,"highlightColors",null);const e=new Map,i=!!this.#xt;for(const[n,s]of t){const t=n.endsWith("_HCM");i&&t?e.set(n.replace("_HCM",""),s):i||t||e.set(n,s)}return shadow(this,"highlightColors",e)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}getNonHCMColor(t){if(!this._highlightColors)return t;const e=this.highlightColorNames.get(t);return this._highlightColors.get(e)||t}getNonHCMColorName(t){return this.highlightColorNames.get(t)||t}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#X=t}setMainHighlightColorPicker(t){this.#mt=t}editAltText(t,e=!1){this.#G?.editAltText(this,t,e)}hasCommentManager(){return!!this.#$}editComment(t,e,i,n){this.#$?.showDialog(this,t,e,i,n)}selectComment(t,e){const i=this.#H.get(t),n=i?.getEditorByUID(e);n?.toggleComment(!0,!0)}updateComment(t){this.#$?.updateComment(t.getData())}updatePopupColor(t){this.#$?.updatePopupColor(t)}removeComment(t){this.#$?.removeComments([t.uid])}deleteComment(t,e){const undo=()=>{t.comment=e};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,"comment");this.toggleComment(null);t.comment=null},undo,mustExec:!0})}toggleComment(t,e,i=void 0){this.#$?.toggleCommentPopup(t,e,i)}makeCommentColor(t,e){return t&&this.#$?.makeCommentColor(t,e)||null}getCommentDialogElement(){return this.#$?.dialogElement||null}async waitForEditorsRendered(t){if(this.#H.has(t-1))return;const{resolve:e,promise:i}=Promise.withResolvers(),onEditorsRendered=i=>{if(i.pageNumber===t){this._eventBus.off("editorsrendered",onEditorsRendered);e()}};this._eventBus.on("editorsrendered",onEditorsRendered,K);await i}getSignature(t){this.#wt?.getSignature({uiManager:this,editor:t})}get signatureManager(){return this.#wt}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal,...K});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#it=e}onPageChanging({pageNumber:t}){this.#q=t-1}deletePage(t){for(const e of this.getEditors(t))e.remove();this.#H.delete(t);this.#q===t&&(this.#q=0)}focusMainContainer(){this.#_t.focus()}findParent(t,e){for(const i of this.#H.values()){const{x:n,y:s,width:a,height:r}=i.div.getBoundingClientRect();if(t>=n&&t<=n+a&&e>=s&&e<=s+r)return i}return null}disableUserSelect(t=!1){this.#Mt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#Z.add(t)}removeShouldRescale(t){this.#Z.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#Z)t.onScaleChanging();this.#X?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#Ot({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Rt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#H.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t="",e=!1){const i=document.getSelection();if(!i||i.isCollapsed)return;const{anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r}=i,o=i.toString(),l=this.#Ot(i).closest(".textLayer"),h=this.getSelectionBoxes(l);if(!h)return;i.empty();const c=this.#Rt(l),d=this.#yt===b.NONE,callback=()=>{const i=c?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:h,anchorNode:n,anchorOffset:s,focusNode:a,focusOffset:r,text:o});d&&this.showAllEditors("highlight",!0,!0);e&&i?.editComment()};d?this.switchToMode(b.HIGHLIGHT,callback):callback()}commentSelection(t=""){this.highlightSelection(t,!0)}#It(t){this.commitOrRemove();this.currentLayer?.endDrawingSession(!1)}#Nt(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#Ot(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#lt||=new FloatingToolbar(this);this.#lt.show(e,i,"ltr"===this.direction)}}getAndRemoveDataFromAnnotationStorage(t){if(!this.#W)return null;const e=`${f}${t}`,i=this.#W.getRawValue(e);i&&this.#W.remove(e);return i}addToAnnotationStorage(t){t.isEmpty()||!this.#W||this.#W.has(t.id)||this.#W.setValue(t.id,t)}a11yAlert(t,e=null){const i=this.#Dt;if(i){i.setAttribute("data-l10n-id",t);e?i.setAttribute("data-l10n-args",JSON.stringify(e)):i.removeAttribute("data-l10n-args")}}#Ut(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#At){this.#lt?.hide();this.#At=null;this.#Ht({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#At)return;const i=this.#Ot(t).closest(".textLayer");if(i){this.#lt?.hide();this.#At=e;this.#Ht({hasSelectedText:!0});if(this.#yt===b.HIGHLIGHT||this.#yt===b.NONE){this.#yt===b.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#ot=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#yt===b.HIGHLIGHT?this.#Rt(i):null;t?.toggleDrawing();if(this.#dt){const e=new AbortController,i=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#zt("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:i});window.addEventListener("blur",pointerup,{signal:i})}else{t?.toggleDrawing(!0);this.#zt("main_toolbar")}}}}else if(this.#At){this.#lt?.hide();this.#At=null;this.#Ht({hasSelectedText:!1})}}#zt(t=""){this.#yt===b.HIGHLIGHT?this.highlightSelection(t):this.#tt&&this.#Nt()}#Ft(){document.addEventListener("selectionchange",this.#Ut.bind(this),{signal:this._signal})}#Gt(){if(this.#at)return;this.#at=new AbortController;const t=this.combinedSignal(this.#at);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Wt(){this.#at?.abort();this.#at=null}blur(){this.isShiftKeyDown=!1;if(this.#ot){this.#ot=!1;this.#zt("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#vt)if(e.div.contains(t)){this.#gt=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#gt)return;const[t,e]=this.#gt;this.#gt=null;e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal});e.focus()}#Lt(){if(this.#pt)return;this.#pt=new AbortController;const t=this.combinedSignal(this.#pt);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Vt(){this.#pt?.abort();this.#pt=null}#jt(){if(this.#K)return;this.#K=new AbortController;const t=this.combinedSignal(this.#K);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#$t(){this.#K?.abort();this.#K=null}#Bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#Lt();this.setEditingState(!0)}removeEditListeners(){this.#Vt();this.setEditingState(!1)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#J)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#J)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#R?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#vt){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#J)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const n=this.currentLayer;try{const t=[];for(const e of i){const i=await n.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Kt(e);this.#Xt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#yt===b.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#ot){this.#ot=!1;this.#zt("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu")}}updatePageIndex(t,e){for(const i of this.getEditors(t))i.pageIndex=e;const i=this.#z.get(t);if(i){i.pageIndex=e;this.#H.set(e,i);this.#ct?i.enable():i.disable()}}startUpdatePages(){this.#z=new Map(this.#H);this.#H.clear()}endUpdatePages(){this.#z=null}clonePage(t,e){for(const i of this.getEditors(t)){const t=i.serialize(i.mode!==b.HIGHLIGHT);if(t){t.pageIndex=e;t.id=this.getId();t.isClone=!0;delete t.popupRef;this.#W.setValue(t.id,t)}}}findClonesForPage(t){const e=[],{pageIndex:i}=t;for(const[n,s]of this.#W)if(s.pageIndex===i&&s.isClone){this.#W.remove(n);e.push(t.deserialize(s).then(e=>{if(e){e.isClone=!0;t.addOrRebuild(e)}}))}return Promise.all(e)}#Ht(t){if(Object.entries(t).some(([t,e])=>this.#St[t]!==e)){this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#St,t)});this.#yt===b.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#qt([[y.HIGHLIGHT_FREE,!0]])}}#qt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Gt();this.#jt();this.#Ht({isEditing:this.#yt!==b.NONE,isEmpty:this.#Yt(),hasSomethingToUndo:this.#j.hasSomethingToUndo(),hasSomethingToRedo:this.#j.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Wt();this.#$t();this.#Ht({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#J){this.#J=t;for(const t of this.#J)this.#qt(t.defaultPropertiesToUpdate)}}getId(){return this.#ht.id}get currentLayer(){return this.#H.get(this.#q)}getLayer(t){return this.#H.get(t)}get currentPageIndex(){return this.#q}addLayer(t){this.#H.set(t.pageIndex,t);this.#ct?t.enable():t.disable()}removeLayer(t){this.#H.delete(t.pageIndex)}async updateMode(t,e=null,i=!1,n=!1,s=!1,a=!1){if(this.#yt!==t){if(this.#Pt){await this.#Pt.promise;if(!this.#Pt)return}this.#Pt=Promise.withResolvers();this.#X?.commitOrRemove();this.#yt===b.POPUP&&this.#$?.hideSidebar();this.#$?.destroyPopup();this.#yt=t;if(t!==b.NONE){for(const t of this.#U.values())t.addStandaloneCommentButton();t===b.SIGNATURE&&await(this.#wt?.loadSignatures());i&&CurrentPointers.clearPointerType();this.setEditingState(!0);await this.#Qt();this.unselectAll();for(const e of this.#H.values())e.updateMode(t);if(t===b.POPUP){this.#N||=await this.#Et.getAnnotationsByType(new Set(this.#J.map(t=>t._editorType)));const t=new Set,e=[];for(const i of this.#U.values()){const{annotationElementId:n,hasComment:s,deleted:a}=i;n&&t.add(n);s&&!a&&e.push(i.getData())}for(const i of this.#N){const{id:n,popupRef:s,contentsObj:a}=i;s&&a?.str&&!t.has(n)&&!this.#Y.has(n)&&e.push(i)}this.#$?.showSidebar(e)}if(e){for(const t of this.#U.values())if(t.uid===e){this.setSelected(t);a?t.editComment():s?t.enterInEditMode():t.focus()}else t.unselect();this.#Pt.resolve()}else{n&&this.addNewEditorFromKeyboard();this.#Pt.resolve()}}else{this.setEditingState(!1);this.#Jt();for(const t of this.#U.values())t.hideStandaloneCommentButton();this._editorUndoBar?.hide();this.toggleComment(null);this.#Pt.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t.mode!==this.#yt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...t})}updateParams(t,e){if(this.#J){switch(t){case y.CREATE:this.currentLayer.addNewEditor(e);return;case y.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#Ct||=new Map).set(t,e);this.showAllEditors("highlight",e)}if(this.hasSelection)for(const i of this.#vt)i.updateParams(t,e);else for(const i of this.#J)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#U.values())i.editorType===t&&i.show(e);(this.#Ct?.get(y.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#qt([[y.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#ut!==t){this.#ut=t;for(const e of this.#H.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Qt(){if(!this.#ct){this.#ct=!0;const t=[];for(const e of this.#H.values())t.push(e.enable());await Promise.all(t);for(const t of this.#U.values())t.enable()}}#Jt(){this.unselectAll();if(this.#ct){this.#ct=!1;for(const t of this.#H.values())t.disable();for(const t of this.#U.values())t.disable()}}*getEditors(t){for(const e of this.#U.values())e.pageIndex===t&&(yield e)}getEditor(t){return this.#U.get(t)}addEditor(t){this.#U.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#st&&clearTimeout(this.#st);this.#st=setTimeout(()=>{this.focusMainContainer();this.#st=null},0)}this.#U.delete(t.id);t.annotationElementId&&this.#ft?.delete(t.annotationElementId);this.unselect(t);t.annotationElementId&&this.#Y.has(t.annotationElementId)||this.#W?.remove(t.id)}addDeletedAnnotationElement(t){this.#Y.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#Y.has(t)}removeDeletedAnnotationElement(t){this.#Y.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Kt(t){const e=this.#H.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#R!==t){this.#R=t;t&&this.#qt(t.propertiesToUpdate)}}get#Zt(){let t=null;for(t of this.#vt);return t}updateUI(t){this.#Zt===t&&this.#qt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#qt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#vt.has(t)){this.#vt.delete(t);t.unselect();this.#Ht({hasSelectedEditor:this.hasSelection})}else{this.#vt.add(t);t.select();this.#qt(t.propertiesToUpdate);this.#Ht({hasSelectedEditor:!0})}}setSelected(t){this.updateToolbar({mode:t.mode,editId:t.uid});this.#X?.commitOrRemove();for(const e of this.#vt)e!==t&&e.unselect();this.#$?.destroyPopup();this.#vt.clear();this.#vt.add(t);t.select();this.#qt(t.propertiesToUpdate);this.#Ht({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#vt.values().next().value}unselect(t){t.unselect();this.#vt.delete(t);this.#Ht({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#vt.size}get isEnterHandled(){return 1===this.#vt.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#j.undo();this.#Ht({hasSomethingToUndo:this.#j.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#Yt()});this._editorUndoBar?.hide()}redo(){this.#j.redo();this.#Ht({hasSomethingToUndo:!0,hasSomethingToRedo:this.#j.hasSomethingToRedo(),isEmpty:this.#Yt()})}addCommands(t){this.#j.add(t);this.#Ht({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#Yt()})}cleanUndoStack(t){this.#j.cleanType(t)}#Yt(){if(0===this.#U.size)return!0;if(1===this.#U.size)for(const t of this.#U.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#vt],undo=()=>{for(const t of e)this.#Kt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#R?.commitOrRemove()}hasSomethingToControl(){return this.#R||this.hasSelection}#Xt(t){for(const t of this.#vt)t.unselect();this.#vt.clear();for(const e of t)if(!e.isEmpty()){this.#vt.add(e);e.select()}this.#Ht({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#vt)t.commit();this.#Xt(this.#U.values())}unselectAll(){if(this.#R){this.#R.commitOrRemove();if(this.#yt!==b.NONE)return}if(!this.#X?.commitOrRemove()){this.#$?.destroyPopup();if(this.hasSelection){for(const t of this.#vt)t.unselect();this.#vt.clear();this.#Ht({hasSelectedEditor:!1})}}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#Tt[0]+=t;this.#Tt[1]+=e;const[n,s]=this.#Tt,a=[...this.#vt];this.#kt&&clearTimeout(this.#kt);this.#kt=setTimeout(()=>{this.#kt=null;this.#Tt[0]=this.#Tt[1]=0;this.addCommands({cmd:()=>{for(const t of a)if(this.#U.has(t.id)){t.translateInPage(n,s);t.translationDone()}},undo:()=>{for(const t of a)if(this.#U.has(t.id)){t.translateInPage(-n,-s);t.translationDone()}},mustExec:!1})},1e3);for(const i of a){i.translateInPage(t,e);i.translationDone()}}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#Q=new Map;for(const t of this.#vt)this.#Q.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#Q)return!1;this.disableUserSelect(!1);const t=this.#Q;this.#Q=null;let e=!1;for(const[{x:i,y:n,pageIndex:s},a]of t){a.newX=i;a.newY=n;a.newPageIndex=s;e||=i!==a.savedX||n!==a.savedY||s!==a.savedPageIndex}if(!e)return!1;const move=(t,e,i,n)=>{if(this.#U.has(t.id)){const s=this.#H.get(n);if(s)t._setParentAndPosition(s,e,i);else{t.pageIndex=n;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:n,newPageIndex:s}]of t)move(e,i,n,s)},undo:()=>{for(const[e,{savedX:i,savedY:n,savedPageIndex:s}]of t)move(e,i,n,s)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#Q)for(const i of this.#Q.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#vt.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#R===t}getActive(){return this.#R}getMode(){return this.#yt}isEditingMode(){return this.#yt!==b.NONE}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,n=e.rangeCount;i<n;i++)if(!t.contains(e.getRangeAt(i).commonAncestorContainer))return null;const{x:i,y:n,width:s,height:a}=t.getBoundingClientRect();let r;switch(t.getAttribute("data-main-rotation")){case"90":r=(t,e,r,o)=>({x:(e-n)/a,y:1-(t+r-i)/s,width:o/a,height:r/s});break;case"180":r=(t,e,r,o)=>({x:1-(t+r-i)/s,y:1-(e+o-n)/a,width:r/s,height:o/a});break;case"270":r=(t,e,r,o)=>({x:1-(e+o-n)/a,y:(t-i)/s,width:o/a,height:r/s});break;default:r=(t,e,r,o)=>({x:(t-i)/s,y:(e-n)/a,width:r/s,height:o/a})}const o=[];for(let t=0,i=e.rangeCount;t<i;t++){const i=e.getRangeAt(t);if(!i.collapsed)for(const{x:t,y:e,width:n,height:s}of i.getClientRects())0!==n&&0!==s&&o.push(r(t,e,n,s))}return 0===o.length?null:o}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#V||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#V?.delete(t)}renderAnnotationElement(t){const e=this.#V?.get(t.data.id);if(!e)return;const i=this.#W.getRawValue(e);i&&(this.#yt!==b.NONE||i.hasBeenModified)&&i.renderAnnotationElement(t)}setMissingCanvas(t,e,i){const n=this.#ft?.get(t);if(n){n.setCanvas(e,i);this.#ft.delete(t)}}addMissingCanvas(t,e){(this.#ft||=new Map).set(t,e)}}class AltText{#l=null;#te=!1;#ee=null;#ie=null;#ne=null;#se=null;#ae=!1;#re=null;#r=null;#oe=null;#le=null;#he=!1;static#ce=null;static _l10n=null;constructor(t){this.#r=t;this.#he=t._uiManager.useNewAltTextFlow;AltText.#ce||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){AltText._l10n??=t}async render(){const t=this.#ee=document.createElement("button");t.className="altText";t.tabIndex="0";const e=this.#ie=document.createElement("span");t.append(e);if(this.#he){t.classList.add("new");t.setAttribute("data-l10n-id",AltText.#ce.missing);e.setAttribute("data-l10n-id",AltText.#ce["missing-label"])}else{t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button");e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label")}const i=this.#r._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:i});t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=t=>{t.preventDefault();this.#r._uiManager.editAltText(this.#r);this.#he&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#de}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#ae=!0;onClick(e)}},{signal:i});await this.#ue();return t}get#de(){return(this.#l?"added":null===this.#l&&this.guessedText&&"review")||"missing"}finish(){if(this.#ee){this.#ee.focus({focusVisible:this.#ae});this.#ae=!1}}isEmpty(){return this.#he?null===this.#l:!this.#l&&!this.#te}hasData(){return this.#he?null!==this.#l||!!this.#oe:this.isEmpty()}get guessedText(){return this.#oe}async setGuessedText(t){if(null===this.#l){this.#oe=t;this.#le=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#ue()}}toggleAltTextBadge(t=!1){if(this.#he&&!this.#l){if(!this.#re){const t=this.#re=document.createElement("div");t.className="noAltTextBadge";this.#r.div.append(t)}this.#re.classList.toggle("hidden",!t)}else{this.#re?.remove();this.#re=null}}serialize(t){let e=this.#l;t||this.#oe!==e||(e=this.#le);return{altText:e,decorative:this.#te,guessedText:this.#oe,textWithDisclaimer:this.#le}}get data(){return{altText:this.#l,decorative:this.#te}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:n,cancel:s=!1}){if(i){this.#oe=i;this.#le=n}if(this.#l!==t||this.#te!==e){if(!s){this.#l=t;this.#te=e}this.#ue()}}toggle(t=!1){if(this.#ee){if(!t&&this.#se){clearTimeout(this.#se);this.#se=null}this.#ee.disabled=!t}}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#de}})}destroy(){this.#ee?.remove();this.#ee=null;this.#ie=null;this.#ne=null;this.#re?.remove();this.#re=null}async#ue(){const t=this.#ee;if(!t)return;if(this.#he){t.classList.toggle("done",!!this.#l);t.setAttribute("data-l10n-id",AltText.#ce[this.#de]);this.#ie?.setAttribute("data-l10n-id",AltText.#ce[`${this.#de}-label`]);if(!this.#l){this.#ne?.remove();return}}else{if(!this.#l&&!this.#te){t.classList.remove("done");this.#ne?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#ne;if(!e){this.#ne=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#r.id}`;const i=100,n=this.#r._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#se);this.#se=null},{once:!0});t.addEventListener("mouseenter",()=>{this.#se=setTimeout(()=>{this.#se=null;this.#ne.classList.add("show");this.#r._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n});t.addEventListener("mouseleave",()=>{if(this.#se){clearTimeout(this.#se);this.#se=null}this.#ne?.classList.remove("show")},{signal:n})}if(this.#te)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#l}e.parentNode||t.append(e);const i=this.#r.getElementForAltText();i?.setAttribute("aria-describedby",e.id)}}class Comment{#pe=null;#ge=null;#me=!1;#r=null;#fe=null;#be=null;#ye=null;#ve=null;#Ae=!1;#we=null;constructor(t){this.#r=t}renderForToolbar(){const t=this.#ge=document.createElement("button");t.className="comment";return this.#v(t,!1)}renderForStandalone(){const t=this.#pe=document.createElement("button");t.className="annotationCommentButton";const e=this.#r.commentButtonPosition;if(e){const{style:i}=t;i.insetInlineEnd=`calc(${100*("ltr"===this.#r._uiManager.direction?1-e[0]:e[0])}% - var(--comment-button-dim))`;i.top=`calc(${100*e[1]}% - var(--comment-button-dim))`;const n=this.#r.commentButtonColor;n&&(i.backgroundColor=n)}return this.#v(t,!0)}focusButton(){setTimeout(()=>{(this.#pe??this.#ge)?.focus()},0)}onUpdatedColor(){if(!this.#pe)return;const t=this.#r.commentButtonColor;t&&(this.#pe.style.backgroundColor=t);this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#pe?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#we)return this.#we;if(!this.#pe)return null;const{x:t,y:e,height:i}=this.#pe.getBoundingClientRect(),{x:n,y:s,width:a,height:r}=this.#r.parent.boundingClientRect;return[(t-n)/a,(e+i-s)/r]}set commentPopupPositionInLayer(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}removeStandaloneCommentButton(){this.#pe?.remove();this.#pe=null}removeToolbarCommentButton(){this.#ge?.remove();this.#ge=null}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#pe){this.#pe.classList.toggle("selected",t);this.#pe.ariaExpanded=e}}#v(t,e){if(!this.#r._uiManager.hasCommentManager())return null;t.tabIndex="0";t.ariaHasPopup="dialog";if(e){t.ariaControls="commentPopup";t.setAttribute("data-l10n-id","pdfjs-show-comment-button")}else{t.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()];t.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button")}const i=this.#r._uiManager._signal;if(!(i instanceof AbortSignal)||i.aborted)return t;t.addEventListener("contextmenu",noContextMenu,{signal:i});if(e){t.addEventListener("focusin",t=>{this.#r._focusEventsAllowed=!1;stopEvent(t)},{capture:!0,signal:i});t.addEventListener("focusout",t=>{this.#r._focusEventsAllowed=!0;stopEvent(t)},{capture:!0,signal:i})}t.addEventListener("pointerdown",t=>t.stopPropagation(),{signal:i});const onClick=e=>{e.preventDefault();t===this.#ge?this.edit():this.#r.toggleComment(!0)};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",e=>{if(e.target===t&&"Enter"===e.key){this.#me=!0;onClick(e)}},{signal:i});t.addEventListener("pointerenter",()=>{this.#r.toggleComment(!1,!0)},{signal:i});t.addEventListener("pointerleave",()=>{this.#r.toggleComment(!1,!1)},{signal:i});return t}edit(t){const e=this.commentPopupPositionInLayer;let i,n;if(e)[i,n]=e;else{[i,n]=this.#r.commentButtonPosition;const{width:t,height:e,x:s,y:a}=this.#r;i=s+i*t;n=a+n*e}const s=this.#r.parent.boundingClientRect,{x:a,y:r,width:o,height:l}=s;this.#r._uiManager.editComment(this.#r,a+i*o,r+n*l,{...t,parentDimensions:s})}finish(){if(this.#ge){this.#ge.focus({focusVisible:this.#me});this.#me=!1}}isDeleted(){return this.#Ae||""===this.#ye}isEmpty(){return null===this.#ye}hasBeenEdited(){return this.isDeleted()||this.#ye!==this.#fe}serialize(){return this.data}get data(){return{text:this.#ye,richText:this.#be,date:this.#ve,deleted:this.isDeleted()}}set data(t){t!==this.#ye&&(this.#be=null);if(null!==t){this.#ye=t;this.#ve=new Date;this.#Ae=!1}else{this.#ye="";this.#Ae=!0}}restoreData({text:t,richText:e,date:i}){this.#ye=t;this.#be=e;this.#ve=i;this.#Ae=!1}setInitialText(t,e=null){this.#fe=t;this.data=t;this.#ve=null;this.#be=e}shown(){}destroy(){this.#ge?.remove();this.#ge=null;this.#pe?.remove();this.#pe=null;this.#ye="";this.#be=null;this.#ve=null;this.#r=null;this.#me=!1;this.#Ae=!1}}class TouchManager{#_t;#xe=!1;#Ce=null;#Ee;#Se;#Te;#ke;#_e=null;#Me;#De=null;#Pe;#Ie=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:n=null,onPinching:s=null,onPinchEnd:a=null,signal:r}){this.#_t=t;this.#Ce=i;this.#Ee=e;this.#Se=n;this.#Te=s;this.#ke=a;this.#Pe=new AbortController;this.#Me=AbortSignal.any([r,this.#Pe.signal]);t.addEventListener("touchstart",this.#Fe.bind(this),{passive:!1,signal:this.#Me})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/OutputScale.pixelRatio}#Fe(t){if(this.#Ee?.())return;if(1===t.touches.length){if(this.#_e)return;const t=this.#_e=new AbortController,e=AbortSignal.any([this.#Me,t.signal]),i=this.#_t,n={capture:!0,signal:e,passive:!1},cancelPointerDown=t=>{if("touch"===t.pointerType){this.#_e?.abort();this.#_e=null}};i.addEventListener("pointerdown",t=>{if("touch"===t.pointerType){stopEvent(t);cancelPointerDown(t)}},n);i.addEventListener("pointerup",cancelPointerDown,n);i.addEventListener("pointercancel",cancelPointerDown,n);return}if(!this.#Ie){this.#Ie=new AbortController;const t=AbortSignal.any([this.#Me,this.#Ie.signal]),e=this.#_t,i={signal:t,capture:!1,passive:!1};e.addEventListener("touchmove",this.#Be.bind(this),i);const n=this.#Le.bind(this);e.addEventListener("touchend",n,i);e.addEventListener("touchcancel",n,i);i.capture=!0;e.addEventListener("pointerdown",stopEvent,i);e.addEventListener("pointermove",stopEvent,i);e.addEventListener("pointercancel",stopEvent,i);e.addEventListener("pointerup",stopEvent,i);this.#Se?.()}stopEvent(t);if(2!==t.touches.length||this.#Ce?.()){this.#De=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#De={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#Be(t){if(!this.#De||2!==t.touches.length)return;stopEvent(t);let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:n,screenY:s}=e,{screenX:a,screenY:r}=i,o=this.#De,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=a-n,m=r-s,f=Math.hypot(g,m)||1,b=Math.hypot(u,p)||1;if(!this.#xe&&Math.abs(b-f)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=n;o.touch0Y=s;o.touch1X=a;o.touch1Y=r;if(!this.#xe){this.#xe=!0;return}const y=[(n+a)/2,(s+r)/2];this.#Te?.(y,b,f)}#Le(t){if(!(t.touches.length>=2)){if(this.#Ie){this.#Ie.abort();this.#Ie=null;this.#ke?.()}if(this.#De){stopEvent(t);this.#De=null;this.#xe=!1}}}destroy(){this.#Pe?.abort();this.#Pe=null;this.#_e?.abort();this.#_e=null}}class AnnotationEditor{#Oe=null;#Re=null;#l=null;#h=null;#pe=null;#Ne=!1;#Ue=null;#He="";#ze=null;#Ge=null;#We=null;#Ve=null;#je=null;#$e="";#Ke=!1;#Xe=null;#qe=!1;#Ye=!1;#Qe=!1;#Je=null;#Ze=0;#ti=0;#ei=null;#ii=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#ni=!1;#si=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;this.annotationElementId=t.annotationElementId||null;this.creationDate=t.creationDate||new Date;this.modificationDate=t.modificationDate||null;this.canAddComment=!0;const{rotation:e,rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:a}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,n];this.pageTranslation=[s,a];const[r,o]=this.parentDimensions;this.x=t.x/r;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}updatePageIndex(t){this.pageIndex=t}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t._uiManager.getId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"});AnnotationEditor._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#ni}set _isDraggable(t){this.#ni=t;this.div?.classList.toggle("draggable",t)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#si}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else{this.#ai();this.#Ve?.remove();this.#Ve=null}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#Ke?this.#Ke=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,n){const[s,a]=this.parentDimensions;[i,n]=this.screenToPageTranslation(i,n);this.x=(t+i)/s;this.y=(e+n)/a;this.fixAndSetPosition()}_moveAfterPaste(t,e){if(this.isClone){delete this.isClone;return}const[i,n]=this.parentDimensions;this.setAt(t*i,e*n,this.width*i,this.height*n);this._onTranslated()}#ri([t,e],i,n){[i,n]=this.screenToPageTranslation(i,n);this.x+=i/t;this.y+=n/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#ri(this.parentDimensions,t,e)}translateInPage(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];this.#ri(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(t,e){this.#Xe||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[n,s]}=this;this.x+=t/n;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:a,y:r}=this;const[o,l]=this.getBaseTranslation();a+=o;r+=l;const{style:h}=i;h.left=`${(100*a).toFixed(2)}%`;h.top=`${(100*r).toFixed(2)}%`;this._onTranslating(a,r);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Xe&&(this.#Xe[0]!==this.x||this.#Xe[1]!==this.y)}get _hasBeenResized(){return!!this.#Xe&&(this.#Xe[2]!==this.width||this.#Xe[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,n=i/t,s=i/e;switch(this.rotation){case 90:return[-n,s];case 180:return[n,s];case 270:return[n,-s];default:return[-n,-s]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,n]}=this;let{x:s,y:a,width:r,height:o}=this;r*=i;o*=n;s*=i;a*=n;if(this._mustFixPosition)switch(t){case 0:s=MathClamp(s,0,i-r);a=MathClamp(a,0,n-o);break;case 90:s=MathClamp(s,0,i-o);a=MathClamp(a,r,n);break;case 180:s=MathClamp(s,r,i);a=MathClamp(a,o,n);break;case 270:s=MathClamp(s,o,i);a=MathClamp(a,0,n-r)}this.x=s/=i;this.y=a/=n;const[l,h]=this.getBaseTranslation();s+=l;a+=h;e.left=`${(100*s).toFixed(2)}%`;e.top=`${(100*a).toFixed(2)}%`;this.moveInDOM()}static#oi(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#oi(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#oi(t,e,360-this.parentRotation)}#li(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(){const{div:{style:t},width:e,height:i}=this;t.width=`${(100*e).toFixed(2)}%`;t.height=`${(100*i).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#hi(){if(this.#ze)return;this.#ze=document.createElement("div");this.#ze.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#ze.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#ci.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#ze)}#ci(t,e){e.preventDefault();const{isMac:i}=FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#l?.toggle(!1);const n=this._isDraggable;this._isDraggable=!1;this.#Ge=[e.screenX,e.screenY];const s=new AbortController,a=this._uiManager.combinedSignal(s);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#di.bind(this,t),{passive:!0,capture:!0,signal:a});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:a});window.addEventListener("contextmenu",noContextMenu,{signal:a});this.#We={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const r=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{s.abort();this.parent.togglePointerEvents(!0);this.#l?.toggle(!0);this._isDraggable=n;this.parent.div.style.cursor=r;this.div.style.cursor=o;this.#ui()};window.addEventListener("pointerup",pointerUpCallback,{signal:a});window.addEventListener("blur",pointerUpCallback,{signal:a})}#pi(t,e,i,n){this.width=i;this.height=n;this.x=t;this.y=e;this.setDims();this.fixAndSetPosition();this._onResized()}_onResized(){}#ui(){if(!this.#We)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:n}=this.#We;this.#We=null;const s=this.x,a=this.y,r=this.width,o=this.height;s===t&&a===e&&r===i&&o===n||this.addCommands({cmd:this.#pi.bind(this,s,a,r,o),undo:this.#pi.bind(this,t,e,i,n),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#di(t,e){const[i,n]=this.parentDimensions,s=this.x,a=this.y,r=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/n,c=this.#li(this.rotation),transf=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],d=this.#li(360-this.rotation);let u,p,g=!1,m=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":m=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":m=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const f=u(r,o),b=p(r,o);let y=transf(...b);const v=AnnotationEditor._round(s+y[0]),A=AnnotationEditor._round(a+y[1]);let w,x,C=1,E=1;if(e.fromKeyboard)({deltaX:w,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[n,s]=this.#Ge;[w,x]=this.screenToPageTranslation(t-n,i-s);this.#Ge[0]=t;this.#Ge[1]=i}[w,x]=(S=w/i,T=x/n,[d[0]*S+d[2]*T,d[1]*S+d[3]*T]);var S,T;if(g){const t=Math.hypot(r,o);C=E=Math.max(Math.min(Math.hypot(b[0]-f[0]-w,b[1]-f[1]-x)/t,1/r,1/o),l/r,h/o)}else m?C=MathClamp(Math.abs(b[0]-f[0]-w),l,1)/r:E=MathClamp(Math.abs(b[1]-f[1]-x),h,1)/o;const k=AnnotationEditor._round(r*C),_=AnnotationEditor._round(o*E);y=transf(...p(k,_));const M=v-y[0],D=A-y[1];this.#Xe||=[this.x,this.y,this.width,this.height];this.width=k;this.height=_;this.x=M;this.y=D;this.setDims();this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#l?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#Ye)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());const{toolbarButtons:t}=this;if(t)for(const[e,i]of t)await this._editToolbar.addButton(e,i);this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton());this._editToolbar.addButton("delete");return this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove();this._editToolbar=null;this.#l?.destroy()}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#l){AltText.initialize(AnnotationEditor._l10n);this.#l=new AltText(this);if(this.#Oe){this.#l.data=this.#Oe;this.#Oe=null}}return this.#l}get altTextData(){return this.#l?.data}set altTextData(t){this.#l&&(this.#l.data=t)}get guessedAltText(){return this.#l?.guessedText}async setGuessedAltText(t){await(this.#l?.setGuessedText(t))}serializeAltText(t){return this.#l?.serialize(t)}hasAltText(){return!!this.#l&&!this.#l.isEmpty()}hasAltTextData(){return this.#l?.hasData()??!1}focusCommentButton(){this.#h?.focusButton()}addCommentButton(){return this.canAddComment?this.#h||=new Comment(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager())if(this.#pe)this._uiManager.isEditingMode()&&this.#pe.classList.remove("hidden");else if(this.hasComment){this.#pe=this.#h.renderForStandalone();this.div.append(this.#pe)}}removeStandaloneCommentButton(){this.#h.removeStandaloneCommentButton();this.#pe=null}hideStandaloneCommentButton(){this.#pe?.classList.add("hidden")}get comment(){if(!this.#h)return null;const{data:{richText:t,text:e,date:i,deleted:n}}=this.#h;return{text:e,richText:t,date:i,deleted:n,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(t){this.#h||=new Comment(this);"object"==typeof t&&null!==t?this.#h.restoreData(t):this.#h.data=t;if(this.hasComment){this.removeCommentButtonFromToolbar();this.addStandaloneCommentButton();this._uiManager.updateComment(this)}else{this.addCommentButtonInToolbar();this.removeStandaloneCommentButton();this._uiManager.removeComment(this)}}setCommentData({comment:t,popupRef:e,richText:i}){if(!e)return;this.#h||=new Comment(this);this.#h.setInitialText(t,i);if(!this.annotationElementId)return;const n=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);n&&this.updateFromAnnotationLayer(n)}get hasEditedComment(){return this.#h?.hasBeenEdited()}get hasDeletedComment(){return this.#h?.isDeleted()}get hasComment(){return!!this.#h&&!this.#h.isEmpty()&&!this.#h.isDeleted()}async editComment(t){this.#h||=new Comment(this);this.#h.edit(t)}toggleComment(t,e=void 0){this.hasComment&&this._uiManager.toggleComment(this,t,e)}setSelectedCommentButton(t){this.#h.setSelectedButton(t)}addComment(t){if(this.hasEditedComment){const e=180,i=100,[,,,n]=t.rect,[s]=this.pageDimensions,[a]=this.pageTranslation,r=a+s+1,o=n-i,l=r+e;t.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[r,o,l,n]}}}updateFromAnnotationLayer({popup:{contents:t,deleted:e}}){this.#h.data=e?null:t}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){const t=this.div=document.createElement("div");t.setAttribute("data-editor-rotation",(360-this.rotation)%360);t.className=this.name;t.setAttribute("id",this.id);t.tabIndex=this.#Ne?-1:0;t.setAttribute("role","application");this.defaultL10nId&&t.setAttribute("data-l10n-id",this.defaultL10nId);this._isVisible||t.classList.add("hidden");this.setInForeground();this.#gi();const[e,i]=this.parentDimensions;if(this.parentRotation%180!=0){t.style.maxWidth=`${(100*i/e).toFixed(2)}%`;t.style.maxHeight=`${(100*e/i).toFixed(2)}%`}const[n,s]=this.getInitialTranslation();this.translate(n,s);bindEvents(this,t,["keydown","pointerdown","dblclick"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#ii||=new TouchManager({container:t,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#mi.bind(this),onPinching:this.#fi.bind(this),onPinchEnd:this.#bi.bind(this),signal:this._uiManager._signal}));this.addStandaloneCommentButton();this._uiManager._editorUndoBar?.hide();return t}#mi(){this.#We={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#l?.toggle(!1);this.parent.togglePointerEvents(!1)}#fi(t,e,i){let n=i/e*.7+1-.7;if(1===n)return;const s=this.#li(this.rotation),transf=(t,e)=>[s[0]*t+s[2]*e,s[1]*t+s[3]*e],[a,r]=this.parentDimensions,o=this.x,l=this.y,h=this.width,c=this.height,d=AnnotationEditor.MIN_SIZE/a,u=AnnotationEditor.MIN_SIZE/r;n=Math.max(Math.min(n,1/h,1/c),d/h,u/c);const p=AnnotationEditor._round(h*n),g=AnnotationEditor._round(c*n);if(p===h&&g===c)return;this.#Xe||=[o,l,h,c];const m=transf(h/2,c/2),f=AnnotationEditor._round(o+m[0]),b=AnnotationEditor._round(l+m[1]),y=transf(p/2,g/2);this.x=f-y[0];this.y=b-y[1];this.width=p;this.height=g;this.setDims();this.fixAndSetPosition();this._onResizing()}#bi(){this.#l?.toggle(!0);this.parent.togglePointerEvents(!0);this.#ui()}pointerdown(t){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#Ke=!0;this._isDraggable?this.#yi(t):this.#vi(t)}}#vi(t){const{isMac:e}=FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#yi(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const n=new AbortController,s=this._uiManager.combinedSignal(n),a={capture:!0,passive:!1,signal:s},cancelDrag=t=>{n.abort();this.#Ue=null;this.#Ke=!1;this._uiManager.endDragSession()||this.#vi(t);i&&this._onStopDragging()};if(e){this.#Ze=t.clientX;this.#ti=t.clientY;this.#Ue=t.pointerId;this.#He=t.pointerType;window.addEventListener("pointermove",t=>{if(!i){i=!0;this._uiManager.toggleComment(this,!0,!1);this._onStartDragging()}const{clientX:e,clientY:n,pointerId:s}=t;if(s!==this.#Ue){stopEvent(t);return}const[a,r]=this.screenToPageTranslation(e-this.#Ze,n-this.#ti);this.#Ze=e;this.#ti=n;this._uiManager.dragSelectedEditors(a,r)},a);window.addEventListener("touchmove",stopEvent,a);window.addEventListener("pointerdown",t=>{t.pointerType===this.#He&&(this.#ii||t.isPrimary)&&cancelDrag(t);stopEvent(t)},a)}const pointerUpCallback=t=>{this.#Ue&&this.#Ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:s});window.addEventListener("blur",pointerUpCallback,{signal:s})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Je&&clearTimeout(this.#Je);this.#Je=setTimeout(()=>{this.#Je=null;this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const n=this.parentScale,[s,a]=this.pageDimensions,[r,o]=this.pageTranslation,l=t/n,h=e/n,c=this.x*s,d=this.y*a,u=this.width*s,p=this.height*a;switch(i){case 0:return[c+l+r,a-d-h-p+o,c+l+u+r,a-d-h+o];case 90:return[c+h+r,a-d+l+o,c+h+p+r,a-d+l+u+o];case 180:return[c-l-u+r,a-d+h+o,c-l+r,a-d+h+p+o];case 270:return[c-h-p+r,a-d-l-u+o,c-h+r,a-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,n,s,a]=t,r=s-i,o=a-n;switch(this.rotation){case 0:return[i,e-a,r,o];case 90:return[i,e-n,o,r];case 180:return[s,e-n,r,o];case 270:return[s,e-a,o,r];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#h?.onUpdatedColor()}getData(){const{comment:{text:t,color:e,date:i,opacity:n,deleted:s,richText:a},uid:r,pageIndex:o,creationDate:l,modificationDate:h}=this;return{id:r,pageIndex:o,rect:this.getPDFRect(),richText:a,contentsObj:{str:t},creationDate:l,modificationDate:i||h,popupRef:!s,color:e,opacity:n}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;this.parent.setEditingState(!1);this.#Ye=!0;return!0}disableEditMode(){if(!this.isInEditMode())return!1;this.parent.setEditingState(!0);this.#Ye=!1;return!0}isInEditMode(){return this.#Ye}shouldGetKeyboardEvents(){return this.#Qe}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:n}=this.getClientDimensions(),{innerHeight:s,innerWidth:a}=window;return e<a&&n>0&&t<s&&i>0}#gi(){if(this.#je||!this.div)return;this.#je=new AbortController;const t=this._uiManager.combinedSignal(this.#je);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#gi()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(t,e,i){const n=new this.prototype.constructor({parent:e,id:i.getId(),uiManager:i,annotationElementId:t.annotationElementId,creationDate:t.creationDate,modificationDate:t.modificationDate});n.rotation=t.rotation;n.#Oe=t.accessibilityData;n._isCopy=t.isCopy||!1;const[s,a]=n.pageDimensions,[r,o,l,h]=n.getRectInCurrentCoords(t.rect,a);n.x=r/s;n.y=o/a;n.width=l/s;n.height=h/a;return n}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#je?.abort();this.#je=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);this.hideCommentPopup();if(this.#Je){clearTimeout(this.#Je);this.#Je=null}this.#ai();this.removeEditToolbar();if(this.#ei){for(const t of this.#ei.values())clearTimeout(t);this.#ei=null}this.parent=null;this.#ii?.destroy();this.#ii=null;this.#Ve?.remove();this.#Ve=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#hi();this.#ze.classList.remove("hidden")}}get toolbarPosition(){return null}get commentButtonPosition(){return"ltr"===this._uiManager.direction?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[t,e]}=this,[i,n,s,a]=this.getPDFRect();return[AnnotationEditor._round(i+(s-i)*t),AnnotationEditor._round(n+(a-n)*(1-e))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#h.commentPopupPositionInLayer}set commentPopupPosition(t){this.#h.commentPopupPositionInLayer=t}hasDefaultPopupPosition(){return this.#h.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#h.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(t){this.#h?.setCommentButtonStates(t)}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#We={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#ze.children;if(!this.#Re){this.#Re=Array.from(e);const t=this.#Ai.bind(this),i=this.#wi.bind(this),n=this._uiManager._signal;for(const e of this.#Re){const s=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:n});e.addEventListener("blur",i,{signal:n});e.addEventListener("focus",this.#xi.bind(this,s),{signal:n});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[s])}}const i=this.#Re[0];let n=0;for(const t of e){if(t===i)break;n++}const s=(360-this.rotation+this.parentRotation)%360/90*(this.#Re.length/4);if(s!==n){if(s<n)for(let t=0;t<n-s;t++)this.#ze.append(this.#ze.firstElementChild);else if(s>n)for(let t=0;t<s-n;t++)this.#ze.firstElementChild.before(this.#ze.lastElementChild);let t=0;for(const i of e){const e=this.#Re[t++].getAttribute("data-resizer-name");i.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[e])}}this.#Ci(0);this.#Qe=!0;this.#ze.firstElementChild.focus({focusVisible:!0});t.preventDefault();t.stopImmediatePropagation()}#Ai(t){AnnotationEditor._resizerKeyboardManager.exec(this,t)}#wi(t){this.#Qe&&t.relatedTarget?.parentNode!==this.#ze&&this.#ai()}#xi(t){this.#$e=this.#Qe?t:""}#Ci(t){if(this.#Re)for(const e of this.#Re)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#Qe&&this.#di(this.#$e,{deltaX:t,deltaY:e,fromKeyboard:!0})}#ai(){this.#Qe=!1;this.#Ci(-1);this.#ui()}_stopResizingWithKeyboard(){this.#ai();this.div.focus()}select(){if(this.isSelected&&this._editToolbar)this._editToolbar.show();else{this.isSelected=!0;this.makeResizable();this.div?.classList.add("selectedEditor");if(this._editToolbar){this._editToolbar?.show();this.#l?.toggleAltTextBadge(!1)}else this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()})}}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){if(this.isSelected){this.isSelected=!1;this.#ze?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#l?.toggleAltTextBadge(!0);this.hideCommentPopup()}}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(t,e){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){if(this.canChangeContent){this.enableEditMode();this.div.focus()}}dblclick(t){if("BUTTON"!==t.target.nodeName){this.enterInEditMode();this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid})}}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#qe}set isEditing(t){this.#qe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#ei||=new Map;const{action:e}=t;let i=this.#ei.get(e);i&&clearTimeout(i);i=setTimeout(()=>{this._reportTelemetry(t);this.#ei.delete(e);0===this.#ei.size&&(this.#ei=null)},AnnotationEditor._telemetryTimeout);this.#ei.set(e,i);return}t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#Ne=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#Ne=!0}updateFakeAnnotationElement(t){if(this.#Ve||this.deleted)if(this.deleted){this.#Ve.remove();this.#Ve=null}else(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#Ve.updateEdited({rect:this.getPDFRect(),popup:this.comment});else this.#Ve=t.addFakeAnnotation(this)}renderAnnotationElement(t){if(this.deleted){t.hide();return null}let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstElementChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const X=3285377520,q=4294901760,Y=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:X;this.h2=t?4294967295&t:X}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let n=0,s=t.length;n<s;n++){const s=t.charCodeAt(n);if(s<=255)e[i++]=s;else{e[i++]=s>>>8;e[i++]=255&s}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const n=i>>2,s=i-4*n,a=new Uint32Array(e.buffer,0,n);let r=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t<n;t++)if(1&t){r=a[t];r=r*c&q|r*u&Y;r=r<<15|r>>>17;r=r*d&q|r*p&Y;l^=r;l=l<<13|l>>>19;l=5*l+3864292196}else{o=a[t];o=o*c&q|o*u&Y;o=o<<15|o>>>17;o=o*d&q|o*p&Y;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}r=0;switch(s){case 3:r^=e[4*n+2]<<16;case 2:r^=e[4*n+1]<<8;case 1:r^=e[4*n];r=r*c&q|r*u&Y;r=r<<15|r>>>17;r=r*d&q|r*p&Y;1&n?l^=r:h^=r}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&q|36045*t&Y;e=4283543511*e&q|(2950163797*(e<<16|t>>>16)&q)>>>16;t^=e>>>1;t=444984403*t&q|60499*t&Y;e=3301882366*e&q|(3120437893*(e<<16|t>>>16)&q)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Q=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Ei=!1;#Si=null;#Ti=null;#ki=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(t,e){const i=this.#ki.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#ki.get(t)}remove(t){const e=this.#ki.get(t);if(void 0!==e){e instanceof AnnotationEditor&&this.#Ti.delete(e.annotationElementId);this.#ki.delete(t);0===this.#ki.size&&this.resetModified();this.#ki.values().some(t=>t instanceof AnnotationEditor)||this.onAnnotationEditor?.(null)}}setValue(t,e){const i=this.#ki.get(t);let n=!1;if(void 0!==i){for(const[t,s]of Object.entries(e))if(i[t]!==s){n=!0;i[t]=s}}else{n=!0;this.#ki.set(t,e)}n&&this.#_i();if(e instanceof AnnotationEditor){(this.#Ti||=new Map).set(e.annotationElementId,e);this.onAnnotationEditor?.(e.constructor._type)}}has(t){return this.#ki.has(t)}get size(){return this.#ki.size}#_i(){if(!this.#Ei){this.#Ei=!0;this.onSetModified?.()}}resetModified(){if(this.#Ei){this.#Ei=!1;this.onResetModified?.()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#ki.size)return Q;const t=new Map,e=new MurmurHash3_64,i=[],n=Object.create(null);let s=!1;for(const[i,a]of this.#ki){const r=a instanceof AnnotationEditor?a.serialize(!1,n):a;if(a.page){a.pageIndex=a.page._pageIndex;delete a.page}if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);s||=!!r.bitmap}}if(s)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:Q}get editorStats(){let t=null;const e=new Map;let i=0,n=0;for(const s of this.#ki.values()){if(!(s instanceof AnnotationEditor)){s.popup&&(s.popup.deleted?n+=1:i+=1);continue}s.isCommentDeleted?n+=1:s.hasEditedComment&&(i+=1);const a=s.telemetryFinalData;if(!a)continue;const{type:r}=a;e.getOrInsertComputed(r,()=>Object.getPrototypeOf(s).constructor);t||=Object.create(null);const o=t[r]||=new Map;for(const[t,e]of Object.entries(a)){if("type"===t)continue;const i=o.getOrInsertComputed(t,makeMap);i.set(e,(i.get(e)??0)+1)}}if(n>0||i>0){t||=Object.create(null);t.comments={deleted:n,edited:i}}if(!t)return null;for(const[i,n]of e)t[i]=n.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Si=null}updateEditor(t,e){const i=this.#Ti?.get(t);if(i){i.updateFromAnnotationLayer(e);return!0}return!1}getEditor(t){return this.#Ti?.get(t)||null}get modifiedIds(){if(this.#Si)return this.#Si;const t=[];if(this.#Ti)for(const e of this.#Ti.values())e.serialize()&&t.push(e.annotationElementId);let e="";if(t.length){const i=new MurmurHash3_64;i.update(t.join(","));e=i.hexdigest()}return this.#Si={ids:new Set(t),hash:e}}[Symbol.iterator](){return this.#ki.entries()}}class PrintAnnotationStorage extends AnnotationStorage{#Mi=Q;constructor(t){super();const{serializable:e}=t;if(e===Q)return;const{map:i,hash:n,transfer:s}=e,a=structuredClone(i,s?{transfer:s}:null);this.#Mi={map:a,hash:n,transfer:[]}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#Mi}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}const J="__forcedDependency",{floor:Z,ceil:tt}=Math;function expandBBox(t,e,i,n,s,a){t[4*e+0]=Math.min(t[4*e+0],i);t[4*e+1]=Math.min(t[4*e+1],n);t[4*e+2]=Math.max(t[4*e+2],s);t[4*e+3]=Math.max(t[4*e+3],a)}const et=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class BBoxReader{#Di;#Pi;constructor(t,e){this.#Di=t;this.#Pi=e}get length(){return this.#Di.length}isEmpty(t){return this.#Di[t]===et}minX(t){return this.#Pi[4*t+0]/256}minY(t){return this.#Pi[4*t+1]/256}maxX(t){return(this.#Pi[4*t+2]+1)/256}maxY(t){return(this.#Pi[4*t+3]+1)/256}}const ensureDebugMetadata=(t,e)=>t?.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));class CanvasBBoxTracker{#Ii=[[1,0,0,1,0,0]];#Fi=[-1/0,-1/0,1/0,1/0];#Bi=new Float64Array(e);_pendingBBoxIdx=-1;#Li;#Oi;#Ri;#Di;_savesStack=[];_markedContentStack=[];constructor(t,e){this.#Li=t.width;this.#Oi=t.height;this.#Ni(e)}growOperationsCount(t){t>=this.#Di.length&&this.#Ni(t,this.#Di)}#Ni(t,e){const i=new ArrayBuffer(4*t);this.#Ri=new Uint8ClampedArray(i);this.#Di=new Uint32Array(i);if(e&&e.length>0){this.#Di.set(e);this.#Di.fill(et,e.length)}else this.#Di.fill(et)}get clipBox(){return this.#Fi}save(t){this.#Fi={__proto__:this.#Fi};this._savesStack.push(t);return this}restore(t,e){const i=Object.getPrototypeOf(this.#Fi);if(null===i)return this;this.#Fi=i;const n=this._savesStack.pop();if(void 0!==n){e?.(n,t);this.#Di[t]=this.#Di[n]}return this}recordOpenMarker(t){this._savesStack.push(t);return this}getOpenMarker(){return 0===this._savesStack.length?null:this._savesStack.at(-1)}recordCloseMarker(t,e){const i=this._savesStack.pop();if(void 0!==i){e?.(i,t);this.#Di[t]=this.#Di[i]}return this}beginMarkedContent(t){this._markedContentStack.push(t);return this}endMarkedContent(t,e){const i=this._markedContentStack.pop();if(void 0!==i){e?.(i,t);this.#Di[t]=this.#Di[i]}return this}pushBaseTransform(t){this.#Ii.push(Util.multiplyByDOMMatrix(this.#Ii.at(-1),t.getTransform()));return this}popBaseTransform(){this.#Ii.length>1&&this.#Ii.pop();return this}resetBBox(t){if(this._pendingBBoxIdx!==t){this._pendingBBoxIdx=t;this.#Bi.set(e,0)}return this}recordClipBox(t,i,n,s,a,r){const o=Util.multiplyByDOMMatrix(this.#Ii.at(-1),i.getTransform()),l=e.slice();Util.axialAlignedBoundingBox([n,a,s,r],o,l);const h=Util.intersect(this.#Fi,l);if(h){this.#Fi[0]=h[0];this.#Fi[1]=h[1];this.#Fi[2]=h[2];this.#Fi[3]=h[3]}else{this.#Fi[0]=this.#Fi[1]=1/0;this.#Fi[2]=this.#Fi[3]=-1/0}return this}recordBBox(t,i,n,s,a,r){const o=this.#Fi;if(o[0]===1/0)return this;const l=Util.multiplyByDOMMatrix(this.#Ii.at(-1),i.getTransform());if(o[0]===-1/0){Util.axialAlignedBoundingBox([n,a,s,r],l,this.#Bi);return this}const h=e.slice();Util.axialAlignedBoundingBox([n,a,s,r],l,h);this.#Bi[0]=MathClamp(h[0],o[0],this.#Bi[0]);this.#Bi[1]=MathClamp(h[1],o[1],this.#Bi[1]);this.#Bi[2]=MathClamp(h[2],this.#Bi[2],o[2]);this.#Bi[3]=MathClamp(h[3],this.#Bi[3],o[3]);return this}recordFullPageBBox(t){this.#Bi[0]=Math.max(0,this.#Fi[0]);this.#Bi[1]=Math.max(0,this.#Fi[1]);this.#Bi[2]=Math.min(this.#Li,this.#Fi[2]);this.#Bi[3]=Math.min(this.#Oi,this.#Fi[3]);return this}recordOperation(t,e=!1,i){if(this._pendingBBoxIdx!==t)return this;const n=Z(256*this.#Bi[0]/this.#Li),s=Z(256*this.#Bi[1]/this.#Oi),a=tt(256*this.#Bi[2]/this.#Li),r=tt(256*this.#Bi[3]/this.#Oi);expandBBox(this.#Ri,t,n,s,a,r);if(i)for(const e of i)for(const i of e)i!==t&&expandBBox(this.#Ri,i,n,s,a,r);e||(this._pendingBBoxIdx=-1);return this}bboxToClipBoxDropOperation(t){if(this._pendingBBoxIdx===t){this._pendingBBoxIdx=-1;this.#Fi[0]=Math.max(this.#Fi[0],this.#Bi[0]);this.#Fi[1]=Math.max(this.#Fi[1],this.#Bi[1]);this.#Fi[2]=Math.min(this.#Fi[2],this.#Bi[2]);this.#Fi[3]=Math.min(this.#Fi[3],this.#Bi[3])}return this}take(){return new BBoxReader(this.#Di,this.#Ri)}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(t,e){return this}recordIncrementalData(t,e){return this}resetIncrementalData(t,e){return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){return this}recordFutureForcedDependency(t,e){return this}inheritSimpleDataAsFutureForcedDependencies(t){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(t,e,i,n=1,s=0,a=0,r){return this}getSimpleIndex(t){}recordDependencies(t,e){return this}recordNamedDependency(t,e){return this}recordShowTextOperation(t,e=!1){return this}}class CanvasDependencyTracker{#Ui={__proto__:null};#Hi={__proto__:null,transform:[],moveText:[],sameLineText:[],[J]:[]};#zi=new Map;#Gi=new Set;#Wi=new Map;#Vi;#ji;#$i;constructor(t,e=!1){this.#$i=t;if(e){this.#Vi=new Map;this.#ji=(t,e)=>{ensureDebugMetadata(this.#Vi,e).dependencies.add(t)}}}get clipBox(){return this.#$i.clipBox}growOperationsCount(t){this.#$i.growOperationsCount(t)}save(t){this.#Ui={__proto__:this.#Ui};this.#Hi={__proto__:this.#Hi,transform:{__proto__:this.#Hi.transform},moveText:{__proto__:this.#Hi.moveText},sameLineText:{__proto__:this.#Hi.sameLineText},[J]:{__proto__:this.#Hi[J]}};this.#$i.save(t);return this}restore(t){this.#$i.restore(t,this.#ji);const e=Object.getPrototypeOf(this.#Ui);if(null===e)return this;this.#Ui=e;this.#Hi=Object.getPrototypeOf(this.#Hi);return this}recordOpenMarker(t){this.#$i.recordOpenMarker(t,this.#ji);return this}getOpenMarker(){return this.#$i.getOpenMarker()}recordCloseMarker(t){this.#$i.recordCloseMarker(t,this.#ji);return this}beginMarkedContent(t){this.#$i.beginMarkedContent(t);return this}endMarkedContent(t){this.#$i.endMarkedContent(t,this.#ji);return this}pushBaseTransform(t){this.#$i.pushBaseTransform(t);return this}popBaseTransform(){this.#$i.popBaseTransform();return this}recordSimpleData(t,e){this.#Ui[t]=e;return this}recordIncrementalData(t,e){this.#Hi[t].push(e);return this}resetIncrementalData(t,e){this.#Hi[t].length=0;return this}recordNamedData(t,e){this.#zi.set(t,e);return this}recordSimpleDataFromNamed(t,e,i){this.#Ui[t]=this.#zi.get(e)??i}recordFutureForcedDependency(t,e){this.recordIncrementalData(J,e);return this}inheritSimpleDataAsFutureForcedDependencies(t){for(const e of t)e in this.#Ui&&this.recordFutureForcedDependency(e,this.#Ui[e]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const t of this.#Gi)this.recordFutureForcedDependency(J,t);return this}resetBBox(t){this.#$i.resetBBox(t);return this}recordClipBox(t,e,i,n,s,a){this.#$i.recordClipBox(t,e,i,n,s,a);return this}recordBBox(t,e,i,n,s,a){this.#$i.recordBBox(t,e,i,n,s,a);return this}recordCharacterBBox(t,e,i,n=1,s=0,a=0,r){const o=i.bbox;let l,h;if(o){l=o[2]!==o[0]&&o[3]!==o[1]&&this.#Wi.get(i);if(!1!==l){h=[0,0,0,0];Util.axialAlignedBoundingBox(o,i.fontMatrix,h);1===n&&0===s&&0===a||function scaleCharBBox(t,e,i,n,s){let a;if(t){if(t<0){a=s[0];s[0]=s[2];s[2]=a}s[0]*=t;s[2]*=t;if(e<0){a=s[1];s[1]=s[3];s[3]=a}s[1]*=e;s[3]*=e}else s.fill(0);s[0]+=i;s[1]+=n;s[2]+=i;s[3]+=n}(n,-n,s,a,h);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}}if(!r)return this.recordFullPageBBox(t);const c=r();if(o&&h&&void 0===l){l=h[0]<=s-c.actualBoundingBoxLeft&&h[2]>=s+c.actualBoundingBoxRight&&h[1]<=a-c.actualBoundingBoxAscent&&h[3]>=a+c.actualBoundingBoxDescent;this.#Wi.set(i,l);if(l)return this.recordBBox(t,e,h[0],h[2],h[1],h[3])}return this.recordBBox(t,e,s-c.actualBoundingBoxLeft,s+c.actualBoundingBoxRight,a-c.actualBoundingBoxAscent,a+c.actualBoundingBoxDescent)}recordFullPageBBox(t){this.#$i.recordFullPageBBox(t);return this}getSimpleIndex(t){return this.#Ui[t]}recordDependencies(t,e){const i=this.#Gi,n=this.#Ui,s=this.#Hi;for(const t of e)t in this.#Ui?i.add(n[t]):t in s&&s[t].forEach(i.add,i);return this}recordNamedDependency(t,e){this.#zi.has(e)&&this.#Gi.add(this.#zi.get(e));return this}recordOperation(t,e=!1){this.recordDependencies(t,[J]);if(this.#Vi){const e=ensureDebugMetadata(this.#Vi,t),{dependencies:i}=e;this.#Gi.forEach(i.add,i);this.#$i._savesStack.forEach(i.add,i);this.#$i._markedContentStack.forEach(i.add,i);i.delete(t);e.isRenderingOperation=!0}const i=!e&&t===this.#$i._pendingBBoxIdx;this.#$i.recordOperation(t,e,[this.#Gi,this.#$i._savesStack,this.#$i._markedContentStack]);i&&this.#Gi.clear();return this}recordShowTextOperation(t,e=!1){const i=Array.from(this.#Gi);this.recordOperation(t,e);this.recordIncrementalData("sameLineText",t);for(const t of i)this.recordIncrementalData("sameLineText",t);return this}bboxToClipBoxDropOperation(t,e=!1){const i=!e&&t===this.#$i._pendingBBoxIdx;this.#$i.bboxToClipBoxDropOperation(t);i&&this.#Gi.clear();return this}take(){this.#Wi.clear();return this.#$i.take()}takeDebugMetadata(){return this.#Vi}}class CanvasNestedDependencyTracker{#Ki;#Xi;#qi;#Yi=0;#Qi=0;constructor(t,e,i){if(t instanceof CanvasNestedDependencyTracker&&t.#qi===!!i)return t;this.#Ki=t;this.#Xi=e;this.#qi=!!i}get clipBox(){return this.#Ki.clipBox}growOperationsCount(){throw new Error("Unreachable")}save(t){this.#Qi++;this.#Ki.save(this.#Xi);return this}restore(t){if(this.#Qi>0){this.#Ki.restore(this.#Xi);this.#Qi--}return this}recordOpenMarker(t){this.#Yi++;return this}getOpenMarker(){return this.#Yi>0?this.#Xi:this.#Ki.getOpenMarker()}recordCloseMarker(t){this.#Yi--;return this}beginMarkedContent(t){return this}endMarkedContent(t){return this}pushBaseTransform(t){this.#Ki.pushBaseTransform(t);return this}popBaseTransform(){this.#Ki.popBaseTransform();return this}recordSimpleData(t,e){this.#Ki.recordSimpleData(t,this.#Xi);return this}recordIncrementalData(t,e){this.#Ki.recordIncrementalData(t,this.#Xi);return this}resetIncrementalData(t,e){this.#Ki.resetIncrementalData(t,this.#Xi);return this}recordNamedData(t,e){return this}recordSimpleDataFromNamed(t,e,i){this.#Ki.recordSimpleDataFromNamed(t,e,this.#Xi);return this}recordFutureForcedDependency(t,e){this.#Ki.recordFutureForcedDependency(t,this.#Xi);return this}inheritSimpleDataAsFutureForcedDependencies(t){this.#Ki.inheritSimpleDataAsFutureForcedDependencies(t);return this}inheritPendingDependenciesAsFutureForcedDependencies(){this.#Ki.inheritPendingDependenciesAsFutureForcedDependencies();return this}resetBBox(t){this.#qi||this.#Ki.resetBBox(this.#Xi);return this}recordClipBox(t,e,i,n,s,a){this.#qi||this.#Ki.recordClipBox(this.#Xi,e,i,n,s,a);return this}recordBBox(t,e,i,n,s,a){this.#qi||this.#Ki.recordBBox(this.#Xi,e,i,n,s,a);return this}recordCharacterBBox(t,e,i,n,s,a,r){this.#qi||this.#Ki.recordCharacterBBox(this.#Xi,e,i,n,s,a,r);return this}recordFullPageBBox(t){this.#qi||this.#Ki.recordFullPageBBox(this.#Xi);return this}getSimpleIndex(t){return this.#Ki.getSimpleIndex(t)}recordDependencies(t,e){this.#Ki.recordDependencies(this.#Xi,e);return this}recordNamedDependency(t,e){this.#Ki.recordNamedDependency(this.#Xi,e);return this}recordOperation(t){this.#Ki.recordOperation(this.#Xi,!0);return this}recordShowTextOperation(t){this.#Ki.recordShowTextOperation(this.#Xi,!0);return this}bboxToClipBoxDropOperation(t){this.#qi||this.#Ki.bboxToClipBoxDropOperation(this.#Xi,!0);return this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}}const it=["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],nt=["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],st=["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],at=["filter","fillColor","fillAlpha"],rt=["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],ot=["transform"],lt=["transform","fillColor"];class CanvasImagesTracker{#Li;#Oi;#Ji=4;#Zi=0;#Pi=new CanvasImagesTracker.#tn(6*this.#Ji);static#tn=FeatureTest.isFloat16ArraySupported?Float16Array:Float32Array;constructor(t){this.#Li=t.width;this.#Oi=t.height}record(t,i,n,s){if(this.#Zi===this.#Ji){this.#Ji*=2;const t=new CanvasImagesTracker.#tn(6*this.#Ji);t.set(this.#Pi);this.#Pi=t}const a=getCurrentTransform(t);let r;if(s[0]!==1/0){const t=e.slice();Util.axialAlignedBoundingBox([0,-n,i,0],a,t);const o=Util.intersect(s,t);if(!o)return;const[l,h,c,d]=o;if(l!==t[0]||h!==t[1]||c!==t[2]||d!==t[3]){const t=Math.atan2(a[1],a[0]),e=Math.abs(Math.sin(t)),i=Math.abs(Math.cos(t));if(e<1e-6||i<1e-6||Math.abs(e-i)<1e-6)r=[l,h,l,d,c,h];else{const t=c-l,n=d-h,s=e*e,a=i*i,o=i*e,u=a-s,p=(n*a-t*o)/u;r=[l+(n*o-t*s)/u,h,l,h+p,c,d-p]}}}if(!r){r=[0,-n,0,0,i,-n];Util.applyTransform(r,a,0);Util.applyTransform(r,a,2);Util.applyTransform(r,a,4)}r[0]/=this.#Li;r[1]/=this.#Oi;r[2]/=this.#Li;r[3]/=this.#Oi;r[4]/=this.#Li;r[5]/=this.#Oi;this.#Pi.set(r,6*this.#Zi);this.#Zi++}take(){return this.#Pi.subarray(0,6*this.#Zi)}}class FontLoader{#en=new Set;#in=null;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){const e=this.#nn();e.insertRule(t,e.cssRules.length)}#nn(){if(this.#in)return this.#in;const t=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&t){const{adoptedStyleSheets:e}=this._document;if(e){const i=new t;e.push(i);return this.#in=i}}if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}return this.#in=this.styleElement.sheet}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#en.clear();if(this.#in){const{adoptedStyleSheets:t}=this._document;t?.includes(this.#in)&&(this._document.adoptedStyleSheets=t.filter(t=>t!==this.#in));this.#in=null}if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,disableFontFace:e,_inspectFont:i}){if(t&&!this.#en.has(t.loadedName)){assert(!e,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:e,src:n,style:s}=t,a=new FontFace(e,n,s);this.addNativeFontFace(a);try{await a.load();this.#en.add(e);i?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(a)}return}unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise(e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){return shadow(this,"isSyncFontLoadingSupported",t||FeatureTest.platform.isFirefox)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,n){return t.substring(0,e)+n+t.substring(e+i)}let i,n;const s=this._document.createElement("canvas");s.width=1;s.height=1;const a=s.getContext("2d");let r=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let c=int32(l,16);for(i=0,n=o.length-3;i<n;i+=4)c=c-h+int32(o,i)|0;i<o.length&&(c=c-h+int32(o+"XXX",i)|0);l=spliceString(l,16,4,function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}(c));const d=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(d);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++r>30){warn("Load test font never loaded.");e();return}a.font="30px "+t;a.fillText(".",0,20);a.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,()=>{u.remove();e.complete()})}}class FontFaceObject{compiledGlyphs=Object.create(null);#sn;constructor(t,e=null,i,n){this.#sn=t;this._inspectFont=e;i&&(this.charProcOperatorList=i);n&&Object.assign(this,n)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let n;try{n=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const s=makePathFromDrawOPS(n?.path);this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=s}get black(){return this.#sn.black}get bold(){return this.#sn.bold}get disableFontFace(){return this.#sn.disableFontFace}set disableFontFace(t){shadow(this,"disableFontFace",!!t)}get fontExtraProperties(){return this.#sn.fontExtraProperties}get isInvalidPDFjsFont(){return this.#sn.isInvalidPDFjsFont}get isType3Font(){return this.#sn.isType3Font}get italic(){return this.#sn.italic}get missingFile(){return this.#sn.missingFile}get remeasure(){return this.#sn.remeasure}get vertical(){return this.#sn.vertical}get ascent(){return this.#sn.ascent}get defaultWidth(){return this.#sn.defaultWidth}get descent(){return this.#sn.descent}get bbox(){return this.#sn.bbox}get fontMatrix(){return this.#sn.fontMatrix}get fallbackName(){return this.#sn.fallbackName}get loadedName(){return this.#sn.loadedName}get mimetype(){return this.#sn.mimetype}get name(){return this.#sn.name}get data(){return this.#sn.data}clearData(){this.#sn.clearData()}get cssFontInfo(){return this.#sn.cssFontInfo}get systemFontInfo(){return this.#sn.systemFontInfo}get defaultVMetrics(){return this.#sn.defaultVMetrics}}class CSS_FONT_INFO{static strings=["fontFamily","fontWeight","italicAngle"]}class SYSTEM_FONT_INFO{static strings=["css","loadedName","baseFontName","src"]}class FONT_INFO{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(2*this.bools.length/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+8*this.numbers.length;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class PATTERN_INFO{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class CssFontInfo{#an;#rn=new TextDecoder;#on;constructor(t){this.#an=t;this.#on=new DataView(t)}#ln(t){assert(t<CSS_FONT_INFO.strings.length,"Invalid string index");let e=0;for(let i=0;i<t;i++)e+=this.#on.getUint32(e)+4;const i=this.#on.getUint32(e);return this.#rn.decode(new Uint8Array(this.#an,e+4,i))}get fontFamily(){return this.#ln(0)}get fontWeight(){return this.#ln(1)}get italicAngle(){return this.#ln(2)}}class SystemFontInfo{#an;#rn=new TextDecoder;#on;constructor(t){this.#an=t;this.#on=new DataView(t)}get guessFallback(){return 0!==this.#on.getUint8(0)}#ln(t){assert(t<SYSTEM_FONT_INFO.strings.length,"Invalid string index");let e=5;for(let i=0;i<t;i++)e+=this.#on.getUint32(e)+4;const i=this.#on.getUint32(e);return this.#rn.decode(new Uint8Array(this.#an,e+4,i))}get css(){return this.#ln(0)}get loadedName(){return this.#ln(1)}get baseFontName(){return this.#ln(2)}get src(){return this.#ln(3)}get style(){let t=1;t+=4+this.#on.getUint32(t);const e=this.#on.getUint32(t),i=this.#rn.decode(new Uint8Array(this.#an,t+4,e));t+=4+e;const n=this.#on.getUint32(t);return{style:i,weight:this.#rn.decode(new Uint8Array(this.#an,t+4,n))}}}class FontInfo{#an;#rn=new TextDecoder;#on;constructor({buffer:t,extra:e}){this.#an=t;this.#on=new DataView(t);e&&Object.assign(this,e)}#hn(t){assert(t<FONT_INFO.bools.length,"Invalid boolean index");const e=Math.floor(t/4),i=2*t%8,n=this.#on.getUint8(e)>>i&3;return 0===n?void 0:2===n}get black(){return this.#hn(0)}get bold(){return this.#hn(1)}get disableFontFace(){return this.#hn(2)}get fontExtraProperties(){return this.#hn(3)}get isInvalidPDFjsFont(){return this.#hn(4)}get isType3Font(){return this.#hn(5)}get italic(){return this.#hn(6)}get missingFile(){return this.#hn(7)}get remeasure(){return this.#hn(8)}get vertical(){return this.#hn(9)}#cn(t){assert(t<FONT_INFO.numbers.length,"Invalid number index");return this.#on.getFloat64(FONT_INFO.OFFSET_NUMBERS+8*t)}get ascent(){return this.#cn(0)}get defaultWidth(){return this.#cn(1)}get descent(){return this.#cn(2)}#dn(t,e,i,n){const s=this.#on.getUint8(t);if(0===s)return;assert(s===e,"Invalid array length.");t+=1;const a=new Array(s);for(let e=0;e<s;e++){a[e]=this.#on[i](t,!0);t+=n}return a}get bbox(){return this.#dn(FONT_INFO.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#dn(FONT_INFO.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#dn(FONT_INFO.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#ln(t){assert(t<FONT_INFO.strings.length,"Invalid string index");let e=FONT_INFO.OFFSET_STRINGS+4;for(let i=0;i<t;i++)e+=this.#on.getUint32(e)+4;const i=this.#on.getUint32(e);return this.#rn.decode(new Uint8Array(this.#an,e+4,i))}get fallbackName(){return this.#ln(0)}get loadedName(){return this.#ln(1)}get mimetype(){return this.#ln(2)}get name(){return this.#ln(3)}#un(){let t=FONT_INFO.OFFSET_STRINGS;t+=4+this.#on.getUint32(t);t+=4+this.#on.getUint32(t);t+=4+this.#on.getUint32(t);return{offset:t,length:this.#on.getUint32(t)}}get data(){const{offset:t,length:e}=this.#un();return 0===e?void 0:new Uint8Array(this.#an,t+4,e)}clearData(){const{offset:t,length:e}=this.#un();if(0!==e){this.#on.setUint32(t,0);this.#an=new Uint8Array(this.#an,0,t+4).slice().buffer;this.#on=new DataView(this.#an)}}get cssFontInfo(){let t=FONT_INFO.OFFSET_STRINGS;t+=4+this.#on.getUint32(t);t+=4+this.#on.getUint32(t);const e=this.#on.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#an,t+4,e));return new CssFontInfo(i.buffer)}get systemFontInfo(){let t=FONT_INFO.OFFSET_STRINGS;t+=4+this.#on.getUint32(t);const e=this.#on.getUint32(t);if(0===e)return null;const i=new Uint8Array(e);i.set(new Uint8Array(this.#an,t+4,e));return new SystemFontInfo(i.buffer)}}class PatternInfo{constructor(t){this.buffer=t;this.view=new DataView(t);this.data=new Uint8Array(t)}getIR(){const t=this.view,i=this.data[PATTERN_INFO.KIND],n=!!this.data[PATTERN_INFO.HAS_BBOX],s=!!this.data[PATTERN_INFO.HAS_BACKGROUND],a=t.getUint32(PATTERN_INFO.N_COORD,!0),r=t.getUint32(PATTERN_INFO.N_COLOR,!0),o=t.getUint32(PATTERN_INFO.N_STOP,!0);let l=20;const h=new Float32Array(this.buffer,l,2*a);l+=8*a;const c=new Uint8Array(this.buffer,l,4*r);l+=4*r;const d=[];for(let e=0;e<o;++e){const e=t.getFloat32(l,!0);l+=4;const i=t.getUint32(l,!0);l+=4;d.push([e,`#${i.toString(16).padStart(6,"0")}`])}let u=null;if(n){u=[];for(let e=0;e<4;++e){u.push(t.getFloat32(l,!0));l+=4}}let p=null;if(s){p=new Uint8Array(this.buffer,l,3);l+=3}if(1===i)return["RadialAxial","axial",u,d,Array.from(h.slice(0,2)),Array.from(h.slice(2,4)),null,null];if(2===i)return["RadialAxial","radial",u,d,[h[0],h[1]],[h[3],h[4]],h[2],h[5]];if(3===i){const t=this.data[PATTERN_INFO.SHADING_TYPE];let i=null;if(h.length>0){i=e.slice();for(let t=0,e=h.length;t<e;t+=2)Util.pointBoundingBox(h[t],h[t+1],i)}return["Mesh",t,h,c,a,i,u,p]}throw new Error(`Unsupported pattern kind: ${i}`)}}class FontPathInfo{#an;constructor(t){this.#an=t}get path(){return FeatureTest.isFloat16ArraySupported?new Float16Array(this.#an):new Float32Array(this.#an)}}function getFactoryUrlProp(t){if("string"!=typeof t)return null;if(t.endsWith("/"))return t;throw new Error(`Invalid factory url: "${t}" must include trailing slash.`)}const isRefProxy=t=>"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0,ht=function _isValidExplicitDest(t,e,i){if(!Array.isArray(i)||i.length<2)return!1;const[n,s,...a]=i;if(!t(n)&&!Number.isInteger(n))return!1;if(!e(s))return!1;const r=a.length;let o=!0;switch(s.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;o=!1;break;default:return!1}for(const t of a)if(!("number"==typeof t||o&&null===t))return!1;return!0}.bind(null,isRefProxy,t=>"object"==typeof t&&"string"==typeof t?.name);class LoopbackPort{#pn=new Map;#gn=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#gn.then(()=>{for(const[t]of this.#pn)t.call(this,i)})}addEventListener(t,e,i=null){let n=null;if(i?.signal instanceof AbortSignal){const{signal:s}=i;if(s.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);n=()=>s.removeEventListener("abort",onAbort);s.addEventListener("abort",onAbort)}this.#pn.set(e,n)}removeEventListener(t,e){const i=this.#pn.get(e);i?.();this.#pn.delete(e)}terminate(){for(const[,t]of this.#pn)t?.();this.#pn.clear()}}const ct=1,dt=2,ut=1,pt=2,gt=3,mt=4,ft=5,bt=6,yt=7,vt=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof PasswordException||t instanceof ResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"ResponseException":return new ResponseException(t.message,t.status,t.missing);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#mn=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#fn.bind(this),{signal:this.#mn.signal})}#fn({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#bn(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ct)i.resolve(t.data);else{if(t.callback!==dt)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,n=t.sourceName,s=this.comObj;Promise.try(e,t.data).then(function(e){s.postMessage({sourceName:i,targetName:n,callback:ct,callbackId:t.callbackId,data:e})},function(e){s.postMessage({sourceName:i,targetName:n,callback:dt,callbackId:t.callbackId,reason:wrapReason(e)})});return}t.streamId?this.#yn(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,s=Promise.withResolvers();this.callbackCapabilities[n]=s;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){s.reject(t)}return s.promise}sendWithStream(t,e,i,n){const s=this.streamId++,a=this.sourceName,r=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[s]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:a,targetName:r,action:t,streamId:s,data:e,desiredSize:i.desiredSize},n);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[s].pullCall=e;o.postMessage({sourceName:a,targetName:r,stream:bt,streamId:s,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[s].cancelCall=e;this.streamControllers[s].isClosed=!0;o.postMessage({sourceName:a,targetName:r,stream:ut,streamId:s,reason:wrapReason(t)});return e.promise}},i)}#yn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,a=this,r=this.actionHandler[t.action],o={enqueue(t,a=1,r){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=a;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}s.postMessage({sourceName:i,targetName:n,stream:mt,streamId:e,chunk:t},r)},close(){if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:gt,streamId:e});delete a.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;s.postMessage({sourceName:i,targetName:n,stream:ft,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(r,t.data,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:vt,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:vt,streamId:e,reason:wrapReason(t)})})}#bn(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,s=this.comObj,a=this.streamControllers[e],r=this.streamSinks[e];switch(t.stream){case vt:t.success?a.startCall.resolve():a.startCall.reject(wrapReason(t.reason));break;case yt:t.success?a.pullCall.resolve():a.pullCall.reject(wrapReason(t.reason));break;case bt:if(!r){s.postMessage({sourceName:i,targetName:n,stream:yt,streamId:e,success:!0});break}r.desiredSize<=0&&t.desiredSize>0&&r.sinkCapability.resolve();r.desiredSize=t.desiredSize;Promise.try(r.onPull||onFn).then(function(){s.postMessage({sourceName:i,targetName:n,stream:yt,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:yt,streamId:e,reason:wrapReason(t)})});break;case mt:assert(a,"enqueue should have stream controller");if(a.isClosed)break;a.controller.enqueue(t.chunk);break;case gt:assert(a,"close should have stream controller");if(a.isClosed)break;a.isClosed=!0;a.controller.close();this.#vn(a,e);break;case ft:assert(a,"error should have stream controller");a.controller.error(wrapReason(t.reason));this.#vn(a,e);break;case pt:t.success?a.cancelCall.resolve():a.cancelCall.reject(wrapReason(t.reason));this.#vn(a,e);break;case ut:if(!r)break;const o=wrapReason(t.reason);Promise.try(r.onCancel||onFn,o).then(function(){s.postMessage({sourceName:i,targetName:n,stream:pt,streamId:e,success:!0})},function(t){s.postMessage({sourceName:i,targetName:n,stream:pt,streamId:e,reason:wrapReason(t)})});r.sinkCapability.reject(o);r.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#vn(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#mn?.abort();this.#mn=null}}class BaseBinaryDataFactory{#An=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:t=null,standardFontDataUrl:e=null,wasmUrl:i=null}){this.cMapUrl=t;this.standardFontDataUrl=e;this.wasmUrl=i}async fetch({kind:t,filename:e}){switch(t){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:unreachable(`Not implemented: ${t}`)}const i=this[t];if(!i)throw new Error(`Ensure that the \`${t}\` API parameter is provided.`);const n=`${i}${e}`;return this._fetch(n,t).catch(e=>{throw new Error(`Unable to load ${this.#An[t]} data at: ${n}`)})}async _fetch(t,e){unreachable("Abstract method `_fetch` called.")}}class DOMBinaryDataFactory extends BaseBinaryDataFactory{async _fetch(t,e){const i="cMapUrl"!==e||t.endsWith(".bcmap")?"bytes":"text",n=await fetchData(t,i);return n instanceof Uint8Array?n:stringToBytes(n)}}class BaseCanvasFactory{#wn=!1;constructor({enableHWA:t=!1}){this.#wn=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#wn})}}reset({canvas:t},e,i){if(!t)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.width=e;t.height=i}destroy(t){const{canvas:e}=t;if(!e)throw new Error("Canvas is not specified");e.width=e.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}}class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addKnockoutFilter(t=0){return"none"}addHighlightHCMFilter(t,e,i,n,s){return"none"}addSelectionHCMFilter(t,e){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(t=null){return null}destroy(t=!1){}}class DOMFilterFactory extends BaseFilterFactory{#xn;#Cn;#En;#Sn;#Tn;#kn;#T=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#Sn=t;this.#Tn=e}get#_(){return this.#Cn||=new Map}get#_n(){return this.#kn||=new Map}get#Mn(){if(!this.#En){const t=this.#Tn.createElement("div"),{style:e}=t;e.colorScheme="only light";e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#Tn.createElementNS(a,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#En=this.#Tn.createElementNS(a,"defs");t.append(i);i.append(this.#En);this.#Tn.body.append(t)}return this.#En}#Dn(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const n=i.join(",");return[n,n,n]}const[e,i,n]=t,s=new Array(256),a=new Array(256),r=new Array(256);for(let t=0;t<256;t++){s[t]=e[t]/255;a[t]=i[t]/255;r[t]=n[t]/255}return[s.join(","),a.join(","),r.join(",")]}#Pn(t){if(void 0===this.#xn){this.#xn="";const t=this.#Tn.URL;t!==this.#Tn.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#xn=updateUrlHash(t,""))}return`url(${this.#xn}#${t})`}addFilter(t){if(!t)return"none";let e=this.#_.get(t);if(e)return e;const[i,n,s]=this.#Dn(t),a=1===t.length?i:`${i}${n}${s}`;e=this.#_.get(a);if(e){this.#_.set(t,e);return e}const r=`g_${this.#Sn}_transfer_map_${this.#T++}`,o=this.#Pn(r);this.#_.set(t,o);this.#_.set(a,o);const l=this.#In(r);this.#Fn(i,n,s,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,n="base";let s=this.#_n.get(n);if(s?.key===i)return s.url;if(s){s.filter?.remove();s.key=i;s.url="none";s.filter=null}else{s={key:i,url:"none",filter:null};this.#_n.set(n,s)}if(!t||!e)return s.url;const a=this.#Bn(t);t=Util.makeHexColor(...a);const r=this.#Bn(e);e=Util.makeHexColor(...r);this.#Mn.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return s.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#Sn}_hcm_filter`,c=s.filter=this.#In(h);this.#Fn(l,l,l,c);this.#Ln(c);const getSteps=(t,e)=>{const i=a[t]/255,n=r[t]/255,s=new Array(e+1);for(let t=0;t<=e;t++)s[t]=i+t/e*(n-i);return s.join(",")};this.#Fn(getSteps(0,5),getSteps(1,5),getSteps(2,5),c);s.url=this.#Pn(h);return s.url}addSelectionHCMFilter(t,e){return this.addHighlightHCMFilter("selection",t,e,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(t=null){const e=t?this.addSelectionHCMFilter(t.foreground,t.background):this.addSelectionFilter();return"none"!==e&&FeatureTest.platform.isFirefox?{"backdrop-filter":e,"background-color":"transparent"}:null}addAlphaFilter(t){let e=this.#_.get(t);if(e)return e;const[i]=this.#Dn([t]),n=`alpha_${i}`;e=this.#_.get(n);if(e){this.#_.set(t,e);return e}const s=`g_${this.#Sn}_alpha_map_${this.#T++}`,a=this.#Pn(s);this.#_.set(t,a);this.#_.set(n,a);const r=this.#In(s);this.#On(i,r);return a}addLuminosityFilter(t){let e,i,n=this.#_.get(t||"luminosity");if(n)return n;if(t){[e]=this.#Dn([t]);i=`luminosity_${e}`}else i="luminosity";n=this.#_.get(i);if(n){this.#_.set(t,n);return n}const s=`g_${this.#Sn}_luminosity_map_${this.#T++}`,a=this.#Pn(s);this.#_.set(t,a);this.#_.set(i,a);const r=this.#In(s);this.#Rn(r);t&&this.#On(e,r);return a}addKnockoutFilter(t=0){const e=t>0?Math.min(1/t,1e6):1e6,i=`knockout_${e}`,n=this.#_.get(i);if(n)return n;const s=`g_${this.#Sn}_knockout_filter_${this.#T++}`,r=this.#Pn(s);this.#_.set(i,r);const o=this.#In(s),l=this.#Tn.createElementNS(a,"feComponentTransfer");o.append(l);const h=this.#Tn.createElementNS(a,"feFuncA");h.setAttribute("type","linear");h.setAttribute("slope",`${e}`);h.setAttribute("intercept","0");l.append(h);return r}addHighlightHCMFilter(t,e,i,n,s){const a=`${e}-${i}-${n}-${s}`;let r=this.#_n.get(t);if(r?.key===a)return r.url;if(r){r.filter?.remove();r.key=a;r.url="none";r.filter=null}else{r={key:a,url:"none",filter:null};this.#_n.set(t,r)}if(!e||!i)return r.url;const[o,l]=[e,i].map(this.#Bn.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[n,s].map(this.#Nn.bind(this));c<h&&([h,c,d,u]=[c,h,u,d]);this.#Mn.style.color="";const getSteps=(t,e,i)=>{const n=new Array(256),s=(c-h)/i,a=t/255,r=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*s),i=a+t*r;for(let t=o;t<=e;t++)n[t]=i;o=e+1}for(let t=o;t<256;t++)n[t]=n[o-1];return n.join(",")},p=`g_${this.#Sn}_hcm_${t}_filter`,g=r.filter=this.#In(p);this.#Ln(g);this.#Fn(getSteps(d[0],u[0],5),getSteps(d[1],u[1],5),getSteps(d[2],u[2],5),g);r.url=this.#Pn(p);return r.url}destroy(t=!1){if(!t||!this.#kn?.size){this.#En?.parentNode.parentNode.remove();this.#En=null;this.#Cn?.clear();this.#Cn=null;this.#kn?.clear();this.#kn=null;this.#T=0}}#Rn(t){const e=this.#Tn.createElementNS(a,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#Ln(t){const e=this.#Tn.createElementNS(a,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#In(t){const e=this.#Tn.createElementNS(a,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#Mn.append(e);return e}#Un(t,e,i){const n=this.#Tn.createElementNS(a,e);n.setAttribute("type","discrete");n.setAttribute("tableValues",i);t.append(n)}#Fn(t,e,i,n){const s=this.#Tn.createElementNS(a,"feComponentTransfer");n.append(s);this.#Un(s,"feFuncR",t);this.#Un(s,"feFuncG",e);this.#Un(s,"feFuncB",i)}#On(t,e){const i=this.#Tn.createElementNS(a,"feComponentTransfer");e.append(i);this.#Un(i,"feFuncA",t)}#Bn(t){this.#Mn.style.color=t;return getRGB(getComputedStyle(this.#Mn).getPropertyValue("color"))}#Hn(t){this.#Mn.style.color=t;return getRGBA(getComputedStyle(this.#Mn).getPropertyValue("color"))}#Nn(t){const[e,i,n,s]=this.#Hn(t);if(1===s)return[e,i,n];const[a,r,o]=this.#Bn("Canvas");return[blend(e,a,s),blend(i,r,s),blend(n,o,s)]}}function blend(t,e,i){return Math.round(i*t+(1-i)*e)}t&&warn("Please use the `legacy` build in Node.js environments.");class NodeFilterFactory extends BaseFilterFactory{}class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}class NodeBinaryDataFactory extends BaseBinaryDataFactory{async _fetch(t,e){return async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs/promises"),i=await e.readFile(t);return new Uint8Array(i)}(t)}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:n,height:s,nonBlackColor:a=4294967295,inverseDecode:r=!1}){const o=FeatureTest.isLittleEndian?4278190080:255,[l,h]=r?[a,o]:[o,a],c=n>>3,d=7&n,u=l^h,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let n=0;n<s;++n){for(const n=e+c;e<n;++e,g+=8){const n=t[e];i[g]=l^-(n>>7&1)&u;i[g+1]=l^-(n>>6&1)&u;i[g+2]=l^-(n>>5&1)&u;i[g+3]=l^-(n>>4&1)&u;i[g+4]=l^-(n>>3&1)&u;i[g+5]=l^-(n>>2&1)&u;i[g+6]=l^-(n>>1&1)&u;i[g+7]=l^-(1&n)&u}if(0===d)continue;const n=e<p?t[e++]:255;for(let t=0;t<d;++t,++g)i[g]=l^-(n>>7-t&1)&u}return{srcPos:e,destPos:g}}function convertRGBToRGBA({src:t,srcPos:e=0,dest:i,destPos:n=0,width:s,height:a}){let r=0;const o=s*a*3,l=o>>2,h=new Uint32Array(t.buffer,e,l),c=FeatureTest.isLittleEndian?4278190080:255;if(FeatureTest.isLittleEndian){for(;r<l-2;r+=3,n+=4){const t=h[r],e=h[r+1],s=h[r+2];i[n]=t|c;i[n+1]=t>>>24|e<<8|c;i[n+2]=e>>>16|s<<16|c;i[n+3]=s>>>8|c}for(let s=4*r,a=e+o;s<a;s+=3)i[n++]=t[s]|t[s+1]<<8|t[s+2]<<16|c}else{for(;r<l-2;r+=3,n+=4){const t=h[r],e=h[r+1],s=h[r+2];i[n]=t|c;i[n+1]=t<<24|e>>>8|c;i[n+2]=e<<16|s>>>16|c;i[n+3]=s<<8|c}for(let s=4*r,a=e+o;s<a;s+=3)i[n++]=t[s]<<24|t[s+1]<<16|t[s+2]<<8|c}return{srcPos:e+o,destPos:n}}const At=new class WebGPU{#zn=null;#Gn=null;#Wn=null;#Vn=null;async#jn(){if(!globalThis.navigator?.gpu)return!1;try{const t=await navigator.gpu.requestAdapter();if(!t)return!1;this.#Vn=navigator.gpu.getPreferredCanvasFormat();this.#Gn=await t.requestDevice();return!0}catch{return!1}}init(){return this.#zn||=this.#jn()}get isReady(){return null!==this.#Gn}loadMeshShader(){if(!this.#Gn||this.#Wn)return;const t=this.#Gn.createShaderModule({code:"\nstruct Uniforms {\n offsetX : f32,\n offsetY : f32,\n scaleX : f32,\n scaleY : f32,\n paddedWidth : f32,\n paddedHeight : f32,\n borderSize : f32,\n _pad : f32,\n};\n\n@group(0) @binding(0) var<uniform> u : Uniforms;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) color : vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position : vec4<f32>,\n @location(0) color : vec3<f32>,\n};\n\n@vertex\nfn vs_main(in : VertexInput) -> VertexOutput {\n var out : VertexOutput;\n let cx = (in.position.x + u.offsetX) * u.scaleX;\n let cy = (in.position.y + u.offsetY) * u.scaleY;\n out.position = vec4<f32>(\n ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,\n 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,\n 0.0,\n 1.0\n );\n out.color = in.color.rgb;\n return out;\n}\n\n@fragment\nfn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {\n return vec4<f32>(in.color, 1.0);\n}\n"});this.#Wn=this.#Gn.createRenderPipeline({layout:"auto",vertex:{module:t,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:t,entryPoint:"fs_main",targets:[{format:this.#Vn}]},primitive:{topology:"triangle-list"}})}draw(t,e,i,n,s,a,r,o){this.loadMeshShader();const l=this.#Gn,{offsetX:h,offsetY:c,scaleX:d,scaleY:u}=n,p=l.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&l.queue.writeBuffer(p,0,t);const g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,0,e);const m=l.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([h,c,d,u,a,r,o,0]));const f=l.createBindGroup({layout:this.#Wn.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),b=new OffscreenCanvas(a,r),y=b.getContext("webgpu");y.configure({device:l,format:this.#Vn,alphaMode:s?"opaque":"premultiplied"});const v=s?{r:s[0]/255,g:s[1]/255,b:s[2]/255,a:1}:{r:0,g:0,b:0,a:0},A=l.createCommandEncoder(),w=A.beginRenderPass({colorAttachments:[{view:y.getCurrentTexture().createView(),clearValue:v,loadOp:"clear",storeOp:"store"}]});if(i>0){w.setPipeline(this.#Wn);w.setBindGroup(0,f);w.setVertexBuffer(0,p);w.setVertexBuffer(1,g);w.draw(i)}w.end();l.queue.submit([A.finish()]);p.destroy();g.destroy();m.destroy();return b.transferToImageBitmap()}};const wt="Fill",xt="Stroke",Ct="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],n=e[3]-e[1],s=new Path2D;s.rect(e[0],e[1],i,n);t.clip(s)}class BaseShadingPattern{isModifyingCurrentTransform(){return!1}getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}isOriginBased(){return 0===this._p0[0]&&0===this._p0[1]&&(!this.isRadial()||0===this._p1[0]&&0===this._p1[1])}isRadial(){return"radial"===this._type}areConic(){if(!this.isRadial())return!1;const t=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return t+this._r1>this._r0&&t+this._r0>this._r1}_createGradient(t,e=null){let i,n=this._p0,s=this._p1;if(e){n=n.slice();s=s.slice();Util.applyTransform(n,e);Util.applyTransform(s,e)}if("axial"===this._type)i=t.createLinearGradient(n[0],n[1],s[0],s[1]);else if("radial"===this._type){let a=this._r0,r=this._r1;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t);a*=t[0];r*=t[0]}i=t.createRadialGradient(n[0],n[1],a,s[0],s[1],r)}for(const t of this._colorStops)i.addColorStop(t[0],t[1]);return i}_createReversedGradient(t,e=null){let i=this._p1,n=this._p0;if(e){i=i.slice();n=n.slice();Util.applyTransform(i,e);Util.applyTransform(n,e)}let s=this._r1,a=this._r0;if(e){const t=new Float32Array(2);Util.singularValueDecompose2dScale(e,t);s*=t[0];a*=t[0]}const r=t.createRadialGradient(i[0],i[1],s,n[0],n[1],a),o=this._colorStops.map(([t,e])=>[1-t,e]).reverse();for(const[t,e]of o)r.addColorStop(t,e);return r}getPattern(t,e,i,n){let s;if(n===xt||n===wt){if(this.isOriginBased()){let n=Util.transform(i,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix));const s=.001,a=Math.hypot(n[0],n[1]),r=Math.hypot(n[2],n[3]),o=(n[0]*n[2]+n[1]*n[3])/(a*r);if(Math.abs(o)<s){if(!this.isRadial())return this._createGradient(t,n);if(Math.abs(a-r)<s)return this._createGradient(t,n)}}const a=e.current.getClippedPathBoundingBox(n,getCurrentTransform(t))||[0,0,0,0],r=Math.ceil(a[2]-a[0])||1,o=Math.ceil(a[3]-a[1])||1,l=e.canvasFactory.create(r,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-a[0],-a[1]);i=Util.transform(i,[1,0,0,1,a[0],a[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);if(this.areConic()){h.fillStyle=this._createReversedGradient(h);h.fill()}h.fillStyle=this._createGradient(h);h.fill();s=t.createPattern(l.canvas,"no-repeat");e.canvasFactory.destroy(l);const c=new DOMMatrix(i);s.setTransform(c)}else{if(this.areConic()){t.save();applyBoundingBox(t,this._bbox);t.fillStyle=this._createReversedGradient(t);t.fillRect(-1e10,-1e10,2e10,2e10);t.restore()}applyBoundingBox(t,this._bbox);s=this._createGradient(t)}return s}}function drawTriangle(t,e,i,n,s,a,r,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;if(l[2*i+1]>l[2*n+1]){u=i;i=n;n=u;u=a;a=r;r=u}if(l[2*n+1]>l[2*s+1]){u=n;n=s;s=u;u=r;r=o;o=u}if(l[2*i+1]>l[2*n+1]){u=i;i=n;n=u;u=a;a=r;r=u}const p=(l[2*i]+e.offsetX)*e.scaleX,g=(l[2*i+1]+e.offsetY)*e.scaleY,m=(l[2*n]+e.offsetX)*e.scaleX,f=(l[2*n+1]+e.offsetY)*e.scaleY,b=(l[2*s]+e.offsetX)*e.scaleX,y=(l[2*s+1]+e.offsetY)*e.scaleY;if(g>=y)return;const v=h[4*a],A=h[4*a+1],w=h[4*a+2],x=h[4*r],C=h[4*r+1],E=h[4*r+2],S=h[4*o],T=h[4*o+1],k=h[4*o+2],_=Math.round(g),M=Math.round(y);let D,P,I,F,B,L,O,R;for(let t=_;t<=M;t++){if(t<f){const e=t<g?0:(g-t)/(g-f);D=p-(p-m)*e;P=v-(v-x)*e;I=A-(A-C)*e;F=w-(w-E)*e}else{let e;e=t>y?1:f===y?0:(f-t)/(f-y);D=m-(m-b)*e;P=x-(x-S)*e;I=C-(C-T)*e;F=E-(E-k)*e}let e;e=t<g?0:t>y?1:(g-t)/(g-y);B=p-(p-b)*e;L=v-(v-S)*e;O=A-(A-T)*e;R=w-(w-k)*e;const i=Math.round(Math.min(D,B)),n=Math.round(Math.max(D,B));let s=d*t+4*i;for(let t=i;t<=n;t++){e=(D-t)/(D-B);e<0?e=0:e>1&&(e=1);c[s++]=P-(P-L)*e|0;c[s++]=I-(I-O)*e|0;c[s++]=F-(F-R)*e|0;c[s++]=255}}}class MeshShadingPattern extends BaseShadingPattern{constructor(t){super();this._posData=t[2];this._colData=t[3];this._vertexCount=t[4];this._bounds=t[5];this._bbox=t[6];this._background=t[7];this.matrix=null;!function loadMeshShader(){At.loadMeshShader()}()}_createMeshCanvas(t,e,i){const n=Math.floor(this._bounds[0]),s=Math.floor(this._bounds[1]),a=Math.ceil(this._bounds[2])-n,r=Math.ceil(this._bounds[3])-s,o=Math.min(Math.ceil(Math.abs(a*t[0]*1.1)),3e3)||1,l=Math.min(Math.ceil(Math.abs(r*t[1]*1.1)),3e3)||1,h=a?a/o:1,c=r?r/l:1,d={coords:this._posData,colors:this._colData,offsetX:-n,offsetY:-s,scaleX:1/h,scaleY:1/c},u=o+4,p=l+4,g=i.create(u,p);if(function isGPUReady(){return At.isReady}()&&this._vertexCount>48)g.context.drawImage(function drawMeshWithGPU(t,e,i,n,s,a,r,o){return At.draw(t,e,i,n,s,a,r,o)}(this._posData,this._colData,this._vertexCount,d,e,u,p,2),0,0);else{const t=g.context.createImageData(o,l);if(e){const i=t.data;for(let t=0,n=i.length;t<n;t+=4){i[t]=e[0];i[t+1]=e[1];i[t+2]=e[2];i[t+3]=255}}for(let e=0,i=this._vertexCount;e<i;e+=3)drawTriangle(t,d,e,e+1,e+2,e,e+1,e+2);g.context.putImageData(t,2,2)}return{canvas:g.canvas,offsetX:n-2*h,offsetY:s-2*c,scaleX:h,scaleY:c}}isModifyingCurrentTransform(){return!0}getPattern(t,e,i,n){applyBoundingBox(t,this._bbox);const s=new Float32Array(2);if(n===Ct)Util.singularValueDecompose2dScale(getCurrentTransform(t),s);else if(this.matrix){Util.singularValueDecompose2dScale(this.matrix,s);const[t,i]=s;Util.singularValueDecompose2dScale(e.baseTransform,s);s[0]*=t;s[1]*=i}else Util.singularValueDecompose2dScale(e.baseTransform,s);const a=this._createMeshCanvas(s,n===Ct?null:this._background,e.canvasFactory);if(n!==Ct){t.setTransform(...e.baseTransform);this.matrix&&t.transform(...this.matrix)}t.translate(a.offsetX,a.offsetY);t.scale(a.scaleX,a.scaleY);const r=t.createPattern(a.canvas,"no-repeat");e.canvasFactory.destroy(a);return r}}class DummyShadingPattern extends BaseShadingPattern{getPattern(){return"hotpink"}}const Et=1,St=2;class TilingPattern{static MAX_PATTERN_SIZE=3e3;constructor(t,e,i,n){this.color=t[1];this.operatorList=t[2];this.matrix=t[3];this.bbox=t[4];this.xstep=t[5];this.ystep=t[6];this.paintType=t[7];this.tilingType=t[8];this.needsIsolation=t[9]??!0;this.ctx=e;this.canvasGraphicsFactory=i;this.baseTransform=n;this.patternBaseMatrix=this.matrix?Util.transform(n,this.matrix):n}canSkipPatternCanvas([t,e,i,n]){const[s,a,r,o]=this.bbox,l=Math.abs(this.xstep),h=Math.abs(this.ystep);if(t>l+1e-6||e>h+1e-6)return null;const c=Math.floor((i-r)/l)+1,d=Math.ceil((i+t-s)/l)-1,u=Math.floor((n-o)/h)+1,p=Math.ceil((n+e-a)/h)-1;return d<=c&&p<=u?[c,u]:null}updatePatternDims(t,e){const i=Util.inverseTransform(this.patternBaseMatrix),n=[t[0],t[1]],s=[t[2],t[3]];Util.applyTransform(n,i);Util.applyTransform(s,i);e[0]=Math.abs(s[0]-n[0]);e[1]=Math.abs(s[1]-n[1]);e[2]=Math.min(n[0],s[0]);e[3]=Math.min(n[1],s[1])}_renderTileCanvas(t,e,i,n){const[s,a,r,o]=this.bbox,l=t.canvasFactory.create(i.size,n.size),h=l.context,c=this.canvasGraphicsFactory.createCanvasGraphics(h,e);c.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(c,this.paintType,this.color);h.translate(-i.scale*s,-n.scale*a);c.transform(0,i.scale,0,0,n.scale,0,0);h.save();c.dependencyTracker?.save();this.clipBbox(c,s,a,r,o);c.baseTransform=getCurrentTransform(c.ctx);c.executeOperatorList(this.operatorList);c.endDrawing();c.dependencyTracker?.restore();h.restore();return l}_getCombinedScales(){const t=new Float32Array(2);Util.singularValueDecompose2dScale(this.matrix,t);const[e,i]=t;Util.singularValueDecompose2dScale(this.baseTransform,t);return[e*t[0],i*t[1]]}drawPattern(t,e,i=!1,[n,s],a){const[r,o,l,h]=this.bbox,c=t.dependencyTracker;c&&(t.dependencyTracker=new CanvasNestedDependencyTracker(c,a));t.save();i?t.ctx.clip(e,"evenodd"):t.ctx.clip(e);t.ctx.setTransform(...this.patternBaseMatrix);t.ctx.translate(n*this.xstep,s*this.ystep);if(this.needsIsolation||1!==t.ctx.globalAlpha||"source-over"!==t.ctx.globalCompositeOperation||t.inSMaskMode){const e=l-r,i=h-o,[n,s]=this._getCombinedScales(),c=this.getSizeAndScale(e,this.ctx.canvas.width,n),d=this.getSizeAndScale(i,this.ctx.canvas.height,s),u=this._renderTileCanvas(t,a,c,d);t.ctx.drawImage(u.canvas,r,o,e,i);t.canvasFactory.destroy(u)}else{this.setFillAndStrokeStyleToContext(t,this.paintType,this.color);this.clipBbox(t,r,o,l,h);t.baseTransformStack.push(t.baseTransform);t.baseTransform=getCurrentTransform(t.ctx);t.executeOperatorList(this.operatorList);t.baseTransform=t.baseTransformStack.pop()}t.restore();c&&(t.dependencyTracker=c)}createPatternCanvas(t,e){const[i,n,s,a]=this.bbox,r=s-i,o=a-n;let{xstep:l,ystep:h}=this;l=Math.abs(l);h=Math.abs(h);info("TilingType: "+this.tilingType);const[c,d]=this._getCombinedScales();let u=r,p=o,g=!1,m=!1;Math.ceil(l*c)>=Math.ceil(r*c)?u=l:g=!0;Math.ceil(h*d)>=Math.ceil(o*d)?p=h:m=!0;const f=this.getSizeAndScale(u,this.ctx.canvas.width,c),b=this.getSizeAndScale(p,this.ctx.canvas.height,d),y=this._renderTileCanvas(t,e,f,b);if(g||m){const e=y.canvas;g&&(u=l);m&&(p=h);const s=this.getSizeAndScale(u,this.ctx.canvas.width,c),a=this.getSizeAndScale(p,this.ctx.canvas.height,d),f=s.size,b=a.size,v=t.canvasFactory.create(f,b),A=v.context,w=g?Math.floor(r/l):0,x=m?Math.floor(o/h):0;for(let t=0;t<=w;t++)for(let i=0;i<=x;i++)A.drawImage(e,f*t,b*i,f,b,0,0,f,b);t.canvasFactory.destroy(y);return{canvas:v.canvas,canvasEntry:v,scaleX:s.scale,scaleY:a.scale,offsetX:i,offsetY:n}}return{canvas:y.canvas,canvasEntry:y,scaleX:f.scale,scaleY:b.scale,offsetX:i,offsetY:n}}getSizeAndScale(t,e,i){const n=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let s=Math.ceil(t*i);s>=n?s=n:i=s/t;return{scale:i,size:s}}clipBbox(t,e,i,n,s){const a=n-e,r=s-i,o=new Path2D;o.rect(e,i,a,r);Util.axialAlignedBoundingBox([e,i,n,s],getCurrentTransform(t.ctx),t.current.minMax);t.ctx.clip(o);t.current.updateClipFromPath()}setFillAndStrokeStyleToContext(t,e,i){const n=t.ctx,s=t.current;s.patternFill=s.patternStroke=!1;switch(e){case Et:const{fillStyle:t,strokeStyle:a}=this.ctx;n.fillStyle=s.fillColor=t;n.strokeStyle=s.strokeColor=a;break;case St:n.fillStyle=n.strokeStyle=i;s.fillColor=s.strokeColor=i;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}isModifyingCurrentTransform(){return!1}getPattern(t,e,i,n,s){const a=n!==Ct?Util.transform(i,this.patternBaseMatrix):i,r=this.createPatternCanvas(e,s);let o=new DOMMatrix(a);o=o.translate(r.offsetX,r.offsetY);o=o.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");e.canvasFactory.destroy(r.canvasEntry);l.setTransform(o);return l}}const Tt=16,kt=new DOMMatrix,_t=new Float32Array(2);function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");const i=new Map;for(const n of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){const s=t[n];if("function"==typeof s&&"function"==typeof e[n]){i.set(n,s);t[n]=function(...t){e[n](...t);return s.apply(this,t)}}}t._removeMirroring=()=>{for(const[e,n]of i)t[e]=n;delete t._removeMirroring}}function drawImageAtIntegerCoords(t,e,i,n,s,a,r,o,l,h){const[c,d,u,p,g,m]=getCurrentTransform(t);if(0===d&&0===u){const f=r*c+g,b=Math.round(f),y=o*p+m,v=Math.round(y),A=(r+l)*c+g,w=Math.abs(Math.round(A)-b)||1,x=(o+h)*p+m,C=Math.abs(Math.round(x)-v)||1;t.setTransform(Math.sign(c),0,0,Math.sign(p),b,v);t.drawImage(e,i,n,s,a,0,0,w,C);t.setTransform(c,d,u,p,g,m);return[w,C]}if(0===c&&0===p){const f=o*u+g,b=Math.round(f),y=r*d+m,v=Math.round(y),A=(o+h)*u+g,w=Math.abs(Math.round(A)-b)||1,x=(r+l)*d+m,C=Math.abs(Math.round(x)-v)||1;t.setTransform(0,Math.sign(d),Math.sign(u),0,b,v);t.drawImage(e,i,n,s,a,0,0,C,w);t.setTransform(c,d,u,p,g,m);return[C,w]}t.drawImage(e,i,n,s,a,r,o,l,h);return[Math.hypot(c,d)*l,Math.hypot(u,p)*h]}class CanvasExtraState{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=n;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=A;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=i.slice();constructor(t,e){this.clipBox=new Float32Array([0,0,t,e])}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();t.minMax=this.minMax.slice();t.tilingPatternDims=this.tilingPatternDims?.slice();return t}getPathBoundingBox(t=wt,e=null){const i=this.minMax.slice();if(t===xt){e||unreachable("Stroke bounding box must include transform.");Util.singularValueDecompose2dScale(e,_t);const t=_t[0]*this.lineWidth/2,n=_t[1]*this.lineWidth/2;i[0]-=t;i[1]-=n;i[2]+=t;i[3]+=n}return i}updateClipFromPath(){const t=Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(t){this.clipBox.set(t,0);this.minMax.set(i,0)}getClippedPathBoundingBox(t=wt,e=null){return Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e){const{width:i,height:n,kind:s}=e,a=n%Tt,r=(n-a)/Tt,o=0===a?r:r+1,l=t.createImageData(i,Tt);let h=0;const c=e.data,d=l.data;let u;if(s===T.GRAYSCALE_1BPP)for(u=0;u<o;u++){({srcPos:h}=convertBlackAndWhiteToRGBA({src:c,srcPos:h,dest:d,width:i,height:u<r?Tt:a}));t.putImageData(l,0,u*Tt)}else if(s===T.RGBA_32BPP){let e=0,n=i*Tt*4;for(u=0;u<r;u++){d.set(c.subarray(h,h+n));h+=n;t.putImageData(l,0,e);e+=Tt}if(u<o){n=i*a*4;d.set(c.subarray(h,h+n));t.putImageData(l,0,e)}}else{if(s!==T.RGB_24BPP)throw new Error(`bad image kind: ${s}`);for(u=0;u<o;u++){({srcPos:h}=convertRGBToRGBA({src:c,srcPos:h,dest:new Uint32Array(d.buffer),width:i,height:u<r?Tt:a}));t.putImageData(l,0,u*Tt)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const{width:i,height:n}=e,s=n%Tt,a=(n-s)/Tt,r=0===s?a:a+1,o=t.createImageData(i,Tt);let l=0;const h=e.data,c=o.data;for(let e=0;e<r;e++){({srcPos:l}=convertBlackAndWhiteToRGBA({src:h,srcPos:l,dest:c,width:i,height:e<a?Tt:s,nonBlackColor:0}));t.putImageData(o,0,e*Tt)}}function copyCtxState(t,e){const i=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const n of i)void 0!==t[n]&&(e[n]=t[n]);if(void 0!==t.setLineDash){e.setLineDash(t.getLineDash());e.lineDashOffset=t.lineDashOffset}}function resetCtxToDefault(t){t.strokeStyle=t.fillStyle="#000000";t.fillRule="nonzero";t.globalAlpha=1;t.lineWidth=1;t.lineCap="butt";t.lineJoin="miter";t.miterLimit=10;t.globalCompositeOperation="source-over";t.font="10px sans-serif";if(void 0!==t.setLineDash){t.setLineDash([]);t.lineDashOffset=0}const{filter:e}=t;"none"!==e&&""!==e&&(t.filter="none")}function getImageSmoothingEnabled(t,e){if(e)return!0;Util.singularValueDecompose2dScale(t,_t);const i=Math.fround(OutputScale.pixelRatio*PixelsPerInch.PDF_TO_CSS_UNITS);return _t[0]<=i&&_t[1]<=i}const Mt=["butt","round","square"],Dt=["miter","round","bevel"],Pt={},It={};class CanvasGraphics{#$n=0;#Kn=0;#Xn=null;#qn=null;#Yn=null;#Qn=null;#Jn=1;#Zn;#ts=null;#es=[];constructor(t,e,i,n,s,{optionalContentConfig:a,markedContentStack:r=null},o,l,h,c){this.ctx=t;this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.stateStack=[];this.pendingClip=null;this.pendingEOFill=!1;this.commonObjs=e;this.objs=i;this.canvasFactory=n;this.filterFactory=s;this.groupStack=[];this.baseTransform=null;this.baseTransformStack=[];this.groupLevel=0;this.smaskStack=[];this.tempSMask=null;this.smaskGroupCanvases=[];this.smaskPreparedEntry=null;this.smaskPreparedFor=null;this.smaskPreparedOffsetX=0;this.smaskPreparedOffsetY=0;this.smaskPreparedOOBAlpha=null;this.suspendedCtx=null;this.contentVisible=!0;this.markedContentStack=r||[];this.optionalContentConfig=a;this.cachedPatterns=new Map;this.annotationCanvasMap=o;this.viewportScale=1;this.outputScaleX=1;this.outputScaleY=1;this.pageColors=l;this._cachedScaleForStroking=[-1,0];this._cachedGetSinglePixelWidth=null;this._cachedBitmapsMap=new Map;this.dependencyTracker=h??null;this.imagesTracker=c??null}getObject(t,e,i=null){if("string"==typeof e){this.dependencyTracker?.recordNamedDependency(t,e);return e.startsWith("g_")?this.commonObjs.get(e):this.objs.get(e)}return i}beginDrawing({transform:t,viewport:e,transparency:i=!1,background:n=null}){const s=this.ctx.canvas.width,a=this.ctx.canvas.height,r=this.ctx.fillStyle;this.ctx.fillStyle=n||"#ffffff";this.ctx.fillRect(0,0,s,a);this.ctx.fillStyle=r;if(i){const t=this.transparentCanvasEntry=this.canvasFactory.create(s,a);this.compositeCtx=this.ctx;({canvas:this.transparentCanvas,context:this.ctx}=t);this.ctx.save();this.ctx.transform(...getCurrentTransform(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[3]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=getCurrentTransform(this.ctx)}executeOperatorList(t,e,i,n,s){const a=t.argsArray,r=t.fnArray;let o=e||0;const l=a.length;if(l===o)return o;const h=l-o>10&&"function"==typeof i,c=h?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g,m;for(;;){if(void 0!==n){if(o===n.nextBreakPoint){n.breakIt(o,i);return o}if(n.shouldSkip(o)){if(++o===l)return o;continue}}if(!s||s(o)){g=r[o];m=a[o]??null;if(g!==B.dependency)null===m?this[g](o):this[g](o,...m);else for(const t of m){this.dependencyTracker?.recordNamedData(t,o);const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,i);return o}}}o++;if(o===l)return o;if(h&&++d>10){if(Date.now()>c){i();return o}d=0}}}#is(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.canvasFactory.destroy(this.transparentCanvasEntry);this.transparentCanvas=null;this.transparentCanvasEntry=null}}endDrawing(){this.#is();for(const t of this.smaskGroupCanvases)this.canvasFactory.destroy(t);this.smaskGroupCanvases.length=0;this._clearPreparedSMask();this.tempSMask=null;this.smaskStack.length=0;for(const t of this.#es)this.#ns(t);this.#es.length=0;this.#Xn=null;this.#qn=null;this.#Yn=null;this.#Qn=null;this.#Jn=1;this.#ts=null;this.#Kn=0;this.#$n=0;this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#ss()}#ss(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,n=t.height??t.displayHeight,s=[];let a=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),o=i,l=n;for(;a>2&&o>1||r>2&&l>1;){let t=o,e=l;if(a>2&&o>1){t=Math.ceil(o/2);a/=o/t}if(r>2&&l>1){e=Math.ceil(l/2);r/=l/e}s.push({newWidth:t,newHeight:e});o=t;l=e}if(0===s.length)return{img:t,paintWidth:i,paintHeight:n,tmpCanvas:null};if(1===s.length){const{newWidth:e,newHeight:a}=s[0],r=this.canvasFactory.create(e,a);r.context.drawImage(t,0,0,i,n,0,0,e,a);return{img:r.canvas,paintWidth:e,paintHeight:a,tmpCanvas:r}}let h=this.canvasFactory.create(1,1),c=this.canvasFactory.create(1,1),d=i,u=n,p=t;for(const{newWidth:t,newHeight:e}of s){this.canvasFactory.reset(c,t,e);c.context.drawImage(p,0,0,d,u,0,0,t,e);[h,c]=[c,h];p=h.canvas;d=t;u=e}this.canvasFactory.destroy(c);return{img:h.canvas,paintWidth:d,paintHeight:u,tmpCanvas:h}}_createMaskCanvas(t,e){const n=this.ctx,{width:s,height:a}=e,r=this.current.fillColor,o=this.current.patternFill,l=getCurrentTransform(n);let h,c,d,u;if((e.bitmap||e.data)&&e.count>1){const i=e.bitmap||e.data.buffer;c=JSON.stringify(o?l:[l.slice(0,4),r]);h=this._cachedBitmapsMap.getOrInsertComputed(i,makeMap);const n=h.get(c);if(n&&!o){const e=Math.round(Math.min(l[0],l[2])+l[4]),i=Math.round(Math.min(l[1],l[3])+l[5]);this.dependencyTracker?.recordDependencies(t,lt);return{canvas:n,offsetX:e,offsetY:i}}d=n}if(!d){u=this.canvasFactory.create(s,a);putBinaryImageMask(u.context,e)}let p=Util.transform(l,[1/s,0,0,-1/a,0,0]);p=Util.transform(p,[1,0,0,1,0,-a]);const g=i.slice();Util.axialAlignedBoundingBox([0,0,s,a],p,g);const[m,f,b,y]=g,v=Math.round(b-m)||1,A=Math.round(y-f)||1,w=this.canvasFactory.create(v,A),x=w.context,C=m,E=f;x.translate(-C,-E);x.transform(...p);let S=null;if(!d){const t=this._scaleImage(u.canvas,getCurrentTransformInverse(x));d=t.img;S=t.tmpCanvas;if(d!==u.canvas){this.canvasFactory.destroy(u);u=null}if(h&&o){h.set(c,d);S=null;u=null}}x.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(x),e.interpolate);drawImageAtIntegerCoords(x,d,0,0,d.width,d.height,0,0,s,a);S&&this.canvasFactory.destroy(S);u&&this.canvasFactory.destroy(u);x.globalCompositeOperation="source-in";const T=Util.transform(getCurrentTransformInverse(x),[1,0,0,1,-C,-E]);x.fillStyle=o?r.getPattern(n,this,T,wt,t):r;x.fillRect(0,0,s,a);h&&!o&&h.set(c,w.canvas);this.dependencyTracker?.recordDependencies(t,lt);return{canvas:w.canvas,canvasEntry:h&&!o?null:w,offsetX:Math.round(C),offsetY:Math.round(E)}}setLineWidth(t,e){this.dependencyTracker?.recordSimpleData("lineWidth",t);e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=e;this.ctx.lineWidth=e}setLineCap(t,e){this.dependencyTracker?.recordSimpleData("lineCap",t);this.ctx.lineCap=Mt[e]}setLineJoin(t,e){this.dependencyTracker?.recordSimpleData("lineJoin",t);this.ctx.lineJoin=Dt[e]}setMiterLimit(t,e){this.dependencyTracker?.recordSimpleData("miterLimit",t);this.ctx.miterLimit=e}setDash(t,e,i){this.dependencyTracker?.recordSimpleData("dash",t);const n=this.ctx;if(void 0!==n.setLineDash){n.setLineDash(e);n.lineDashOffset=i}}setRenderingIntent(t,e){}setFlatness(t,e){}setGState(t,e){for(const[i,n]of e)switch(i){case"LW":this.setLineWidth(t,n);break;case"LC":this.setLineCap(t,n);break;case"LJ":this.setLineJoin(t,n);break;case"ML":this.setMiterLimit(t,n);break;case"D":this.setDash(t,n[0],n[1]);break;case"RI":this.setRenderingIntent(t,n);break;case"FL":this.setFlatness(t,n);break;case"Font":this.setFont(t,n[0],n[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",t);this.current.strokeAlpha=n;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",t);this.ctx.globalAlpha=this.current.fillAlpha=n;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",t);this.ctx.globalCompositeOperation=n;break;case"SMask":this.dependencyTracker?.recordSimpleData("SMask",t);this.current.activeSMask=n?this.tempSMask:null;this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation);this.tempSMask=null;this.checkSMaskState(t);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",t);this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){if(this.smaskPreparedEntry){this.canvasFactory.destroy(this.smaskPreparedEntry);this.smaskPreparedEntry=null}this.smaskPreparedFor=null;this.smaskPreparedOffsetX=0;this.smaskPreparedOffsetY=0;this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(t){if(t!==this.smaskPreparedFor){this._clearPreparedSMask();this._prepareSMaskCanvas(t)}}checkSMaskState(t){const e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode(t):!this.current.activeSMask&&e?this.endSMaskMode():this.current.activeSMask&&e&&this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(t){const{canvas:e,subtype:i,backdrop:n,transferMap:s}=t,a="Luminosity"===i||"Alpha"===i&&s;if(!(a||"Luminosity"===i&&n)){this.smaskPreparedFor=t;return}let r;if("Luminosity"===i&&n){const[t,e,i]=getRGBA(n),a=Math.round(.3*t+.59*e+.11*i);r=s?.[a]??a}else r=s?.[0]??0;const{width:o,height:l}=this.ctx.canvas,h=o*l<4*(e.width*e.height),c=a?{url:"Alpha"===i?this.filterFactory.addAlphaFilter(s):this.filterFactory.addLuminosityFilter(s),subtype:i,transferMap:s}:null,d="Luminosity"===i?n:null;let u,p,g;if(h){u=this._bakeSMaskCanvas(e,t.offsetX,t.offsetY,o,l,d,c);p=0;g=0}else{u=this._bakeSMaskCanvas(e,0,0,e.width,e.height,d,c);p=t.offsetX;g=t.offsetY}this.smaskPreparedEntry=u;this.smaskPreparedFor=t;this.smaskPreparedOffsetX=p;this.smaskPreparedOffsetY=g;this.smaskPreparedOOBAlpha=h||0===r?null:r}_bakeSMaskCanvas(t,e,i,n,s,a,r){a||r||unreachable("_bakeSMaskCanvas with neither backdrop nor filter");const o=this.canvasFactory.create(n,s),l=o.context;l.drawImage(t,e,i);if(a){l.globalCompositeOperation="destination-atop";l.fillStyle=a;l.fillRect(0,0,n,s)}if(!r)return o;const h=this.canvasFactory.create(n,s),c=h.context;c.filter=r.url;const d=FeatureTest.isCanvasFilterSupported&&"none"!==c.filter&&""!==c.filter;c.drawImage(o.canvas,0,0);FeatureTest.isCanvasFilterSupported&&(c.filter="none");if(!d){const t=c.getImageData(0,0,n,s),{data:e}=t,{transferMap:i}=r;if("Luminosity"===r.subtype)for(let t=0,n=e.length;t<n;t+=4){const n=.3*e[t]+.59*e[t+1]+.11*e[t+2]+.5|0;e[t]=e[t+1]=e[t+2]=0;e[t+3]=i?.[n]??n}else for(let t=3,n=e.length;t<n;t+=4)e[t]=i[e[t]];c.putImageData(t,0,0)}this.canvasFactory.destroy(o);return h}beginSMaskMode(t){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:e,height:i}=this.ctx.canvas,n=this.canvasFactory.create(e,i);this.smaskScratchCanvas=n;this.suspendedCtx=this.ctx;const s=this.ctx=n.context;s.setTransform(this.suspendedCtx.getTransform());copyCtxState(this.suspendedCtx,s);mirrorContextOperations(s,this.suspendedCtx);this._ensurePreparedSMask(this.current.activeSMask);this.setGState(t,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null;this.canvasFactory.destroy(this.smaskScratchCanvas);this.smaskScratchCanvas=null;this._clearPreparedSMask()}#as(t,e=null,i=1){const{width:n,height:s}=t,a=e??this.canvasFactory.create(n,s),r=a.context,o=(i=Math.round(255*i)/255)<1;o&&void 0===this.#Zn&&(this.#Zn=FeatureTest.isCanvasFilterSupported?new Map:"none");let l="none";o&&this.#Zn instanceof Map&&(l=this.#Zn.getOrInsertComputed(i,()=>this.filterFactory.addKnockoutFilter(i)));if(!o||"none"!==l){if(e){r.save();r.setTransform(1,0,0,1,0,0);r.clearRect(0,0,n,s);r.restore()}r.filter=l;r.drawImage(t,0,0);r.filter="none";return a}const h=t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,n,s),c=r.createImageData(n,s),d=h.data,u=c.data,p=i>0?1/i:1e6;for(let t=3,e=d.length;t<e;t+=4)u[t]=Math.min(Math.round(d[t]*p),255);r.putImageData(c,0,0);return a}#rs(t,e,i,n){let s=t?.[e]??null;if(s&&(s.canvas.width!==i||s.canvas.height!==n)){this.canvasFactory.destroy(s);s=null}if(!s){s=this.canvasFactory.create(i,n);t&&(t[e]=s);return s}const a=s.context;a.save();a.setTransform(1,0,0,1,0,0);a.clearRect(0,0,i,n);a.restore();return s}#os(t,e,i={}){const{backdropCanvas:n=null,destTransform:s=[1,0,0,1,0,0],backdropOffset:a=[0,0],reuseMaskEntry:r=null,poolMeta:o=null,sourceAlpha:l=1,sourceFilter:h="none",knockoutAlpha:c=1}=i,{width:d,height:u}=e,p=this.#as(e,r,c),g=t.globalCompositeOperation;t.save();t.setTransform(...s);t.globalAlpha=1;FeatureTest.isCanvasFilterSupported&&(t.filter="none");t.globalCompositeOperation="destination-out";t.drawImage(p.canvas,0,0);if(n){const[e,i]=a,s=this.#rs(o,"knockoutBackdropEntry",d,u),r=s.context;r.drawImage(n,e,i,d,u,0,0,d,u);r.globalCompositeOperation="destination-in";r.drawImage(p.canvas,0,0);r.globalCompositeOperation="source-over";t.globalCompositeOperation="destination-over";t.drawImage(s.canvas,0,0);o||this.canvasFactory.destroy(s)}t.globalCompositeOperation=g;t.globalAlpha=l;FeatureTest.isCanvasFilterSupported&&(t.filter=h??"none");t.drawImage(e,0,0);t.restore();r||this.canvasFactory.destroy(p)}#ls(t=1){if(0===this.#$n||this.#Kn>0||!this.contentVisible)return!1;this.#Kn++;this.#Jn=t;const e=this.#es.at(-1),{canvas:i}=this.ctx,n=this.#rs(e,"knockoutTempEntry",i.width,i.height);this.#Xn=n;const s=n.context;s.save();s.setTransform(this.ctx.getTransform());copyCtxState(this.ctx,s);this.#Qn=s.globalCompositeOperation;s.globalCompositeOperation="source-over";mirrorContextOperations(s,this.ctx);this.#ts=e;this.#qn=this.ctx;this.#Yn=this.suspendedCtx;this.ctx=s;this.inSMaskMode&&(this.suspendedCtx=s);return!0}#hs(t){if(!t)return;const e=this.#Xn,i=this.#qn,n=this.#Yn,s=e.context;this.#Xn=null;this.#qn=null;this.#Yn=null;this.inSMaskMode&&this.suspendedCtx===s&&this.ctx!==s&&this.endSMaskMode();this.inSMaskMode&&(this.suspendedCtx=n);this.ctx._removeMirroring();this.ctx.globalCompositeOperation=this.#Qn;this.#Qn=null;copyCtxState(this.ctx,i);this.ctx=i;const a=this.#ts;this.#ts=null;const r=this.#Jn;this.#Jn=1;try{this.#os(n??i,e.canvas,{backdropCanvas:a?.backdropCtx?.canvas??null,backdropOffset:a?.backdropCtx?[a.offsetX,a.offsetY]:[0,0],reuseMaskEntry:a?.knockoutMaskEntry??null,poolMeta:a,knockoutAlpha:r})}finally{s.restore();this.#Kn--;a||this.canvasFactory.destroy(e)}}compose(t){if(!this.current.activeSMask)return;t=t?[Math.floor(t[0]),Math.floor(t[1]),Math.ceil(t[2]),Math.ceil(t[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx,n=this.#Kn>0&&i===this.ctx;this.composeSMask(n?null:i,e,this.ctx,t);if(!n){this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}}composeSMask(t,e,i,n){const s=n[0],a=n[1],r=n[2]-s,o=n[3]-a;if(0===r||0===o)return;const l=this.smaskPreparedEntry;if(l){let t=s,n=a,h=r,c=o;const d=this.smaskPreparedOOBAlpha,u=null!==d;if(u){t=Math.max(s,e.offsetX);n=Math.max(a,e.offsetY);h=Math.min(s+r,e.offsetX+e.canvas.width)-t;c=Math.min(a+o,e.offsetY+e.canvas.height)-n}if(h>0&&c>0){const e=t-this.smaskPreparedOffsetX,s=n-this.smaskPreparedOffsetY;i.save();i.globalAlpha=1;i.setTransform(1,0,0,1,0,0);const a=new Path2D;a.rect(t,n,h,c);i.clip(a);i.globalCompositeOperation="destination-in";i.drawImage(l.canvas,e,s,h,c,t,n,h,c);i.restore()}u&&d<255&&this._applySMaskOOBAlpha(i,s,a,r,o,t,n,t+h,n+c,d)}else this.genericComposeSMask(e,i,r,o,s,a);if(t){t.save();t.globalAlpha=1;t.globalCompositeOperation=e.blendMode||"source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,s,a,r,o,s,a,r,o);t.restore()}}_applySMaskOOBAlpha(t,e,i,n,s,a,r,o,l,h){const c=a<o&&r<l;if(c&&a===e&&r===i&&o===e+n&&l===i+s)return;const d=new Path2D;d.rect(e,i,n,s);c&&d.rect(a,r,o-a,l-r);t.save();t.globalAlpha=h/255;t.setTransform(1,0,0,1,0,0);t.clip(d,"evenodd");t.globalCompositeOperation="destination-in";t.fillStyle="#000000";t.fillRect(e,i,n,s);t.restore()}genericComposeSMask(t,e,i,n,s,a){const{context:r,offsetX:o,offsetY:l}=t;e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);const h=new Path2D;h.rect(s,a,i,n);e.clip(h);e.globalCompositeOperation="destination-in";e.drawImage(r.canvas,s-o,a-l,i,n,s,a,i,n);e.restore()}save(t){this.inSMaskMode&©CtxState(this.ctx,this.suspendedCtx);this.ctx.save();const e=this.current;this.stateStack.push(e);this.current=e.clone();this.dependencyTracker?.save(t)}restore(t){this.dependencyTracker?.restore(t);if(0!==this.stateStack.length){this.current=this.stateStack.pop();this.ctx.restore();if(this.inSMaskMode){copyCtxState(this.suspendedCtx,this.ctx);this.ctx.setTransform(this.suspendedCtx.getTransform())}this.checkSMaskState(t);this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}else this.inSMaskMode&&this.endSMaskMode()}transform(t,e,i,n,s,a,r){this.dependencyTracker?.recordIncrementalData("transform",t);this.ctx.transform(e,i,n,s,a,r);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i,n){let[s]=i;if(!n){s||=i[0]=new Path2D;e!==B.stroke&&e!==B.closeStroke&&(this.current.tilingPatternDims=null);this[e](t,s);return}if(null!==this.dependencyTracker){const i=e===B.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(t).recordBBox(t,this.ctx,n[0]-i,n[2]+i,n[1]-i,n[3]+i).recordDependencies(t,["transform"])}s instanceof Path2D||(s=i[0]=makePathFromDrawOPS(s));Util.axialAlignedBoundingBox(n,getCurrentTransform(this.ctx),this.current.minMax);const a=this.current.tilingPatternDims;if(a&&e!==B.stroke&&e!==B.closeStroke&&this.current.fillColor instanceof TilingPattern){const t=Util.intersect(this.current.clipBox,this.current.minMax);t?this.current.fillColor.updatePatternDims(t,a):this.current.tilingPatternDims=null}this[e](t,s);this._pathStartIdx=t}closePath(t){this.ctx.closePath()}stroke(t,e,i=!0){const n=i&&this.#ls(this.current.strokeAlpha),s=this.ctx,a=this.current.strokeColor;s.globalAlpha=this.current.strokeAlpha;if(this.contentVisible)if("object"==typeof a&&a?.getPattern){const i=a.isModifyingCurrentTransform()?s.getTransform():null;s.save();s.strokeStyle=a.getPattern(s,this,getCurrentTransformInverse(s),xt,t);if(i){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(i));e=t}this.rescaleAndStroke(e,!1);s.restore()}else this.rescaleAndStroke(e,!0);this.dependencyTracker?.recordDependencies(t,it);i&&this.consumePath(t,e,this.current.getClippedPathBoundingBox(xt,getCurrentTransform(this.ctx)));s.globalAlpha=this.current.fillAlpha;this.#hs(n)}closeStroke(t,e){this.stroke(t,e)}fill(t,e,i=!0){const n=i&&this.#ls(this.current.fillAlpha),s=this.ctx,a=this.current.fillColor,r=this.current.patternFill;let o=!1;const l=this.current.getClippedPathBoundingBox();this.dependencyTracker?.recordDependencies(t,nt);if(r){const r=this.current.tilingPatternDims,h=r&&a.canSkipPatternCanvas(r);if(h){a.drawPattern(this,e,this.pendingEOFill,h,t);this.pendingEOFill=!1;i&&this.consumePath(t,e,l);this.current.tilingPatternDims=null;this.#hs(n);return}const c=a.isModifyingCurrentTransform()?s.getTransform():null;this.dependencyTracker?.save(t);s.save();s.fillStyle=a.getPattern(s,this,getCurrentTransformInverse(s),wt,t);if(c){const t=new Path2D;t.addPath(e,s.getTransform().invertSelf().multiplySelf(c));e=t}o=!0}if(this.contentVisible&&null!==l)if(this.pendingEOFill){s.fill(e,"evenodd");this.pendingEOFill=!1}else s.fill(e);if(o){s.restore();this.dependencyTracker?.restore(t)}i&&this.consumePath(t,e,l);this.#hs(n)}eoFill(t,e){this.pendingEOFill=!0;this.fill(t,e)}fillStroke(t,e){const i=this.#ls(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(t,e,!1);this.stroke(t,e,!1);this.consumePath(t,e);this.#hs(i)}eoFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}closeFillStroke(t,e){this.fillStroke(t,e)}closeEOFillStroke(t,e){this.pendingEOFill=!0;this.fillStroke(t,e)}endPath(t,e){this.consumePath(t,e)}rawFillPath(t,e){const i=this.#ls(this.current.fillAlpha);this.ctx.fill(e);this.dependencyTracker?.recordDependencies(t,at).recordOperation(t);this.#hs(i)}clip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=Pt}eoClip(t){this.dependencyTracker?.recordFutureForcedDependency("clipMode",t);this.pendingClip=It}beginText(t){this.current.textMatrix=null;this.current.textMatrixScale=1;this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0;this.dependencyTracker?.recordOpenMarker(t).resetIncrementalData("sameLineText").resetIncrementalData("moveText",t)}endText(t){const e=this.pendingTextPaths,i=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;void 0!==e&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",t);i.recordCloseMarker(t)}if(void 0!==e){const t=new Path2D,n=i.getTransform().invertSelf();for(const{transform:i,x:s,y:a,fontSize:r,path:o}of e)o&&t.addPath(o,new DOMMatrix(i).preMultiplySelf(n).translate(s,a).scale(r,-r));i.clip(t)}delete this.pendingTextPaths}setCharSpacing(t,e){this.dependencyTracker?.recordSimpleData("charSpacing",t);this.current.charSpacing=e}setWordSpacing(t,e){this.dependencyTracker?.recordSimpleData("wordSpacing",t);this.current.wordSpacing=e}setHScale(t,e){this.dependencyTracker?.recordSimpleData("hScale",t);this.current.textHScale=e/100}setLeading(t,e){this.dependencyTracker?.recordSimpleData("leading",t);this.current.leading=-e}setFont(t,e,i){this.dependencyTracker?.recordSimpleData("font",t).recordSimpleDataFromNamed("fontObj",e,t);const s=this.commonObjs.get(e),a=this.current;if(!s)throw new Error(`Can't find font for ${e}`);a.fontMatrix=s.fontMatrix||n;0!==a.fontMatrix[0]&&0!==a.fontMatrix[3]||warn("Invalid font matrix for font "+e);if(i<0){i=-i;a.fontDirection=-1}else a.fontDirection=1;this.current.font=s;this.current.fontSize=i;if(s.isType3Font)return;const r=s.loadedName||"sans-serif",o=s.systemFontInfo?.css||`"${r}", ${s.fallbackName}`;let l="normal";s.black?l="900":s.bold&&(l="bold");const h=s.italic?"italic":"normal",c=MathClamp(i,16,100);this.current.fontSizeScale=i/c;this.ctx.font=`${h} ${l} ${c}px ${o}`}setTextRenderingMode(t,e){this.dependencyTracker?.recordSimpleData("textRenderingMode",t);this.current.textRenderingMode=e}setTextRise(t,e){this.dependencyTracker?.recordSimpleData("textRise",t);this.current.textRise=e}moveText(t,e,i){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",t);this.current.x=this.current.lineX+=e;this.current.y=this.current.lineY+=i}setLeadingMoveText(t,e,i){this.setLeading(t,-i);this.moveText(t,e,i)}setTextMatrix(t,e){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",t);const{current:i}=this;i.textMatrix=e;i.textMatrixScale=Math.hypot(e[0],e[1]);i.x=i.lineX=0;i.y=i.lineY=0}nextLine(t){this.moveText(t,0,this.current.leading);this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??t)}#cs(t,e,i){const n=new Path2D;n.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return n}paintChar(t,e,i,n,s,a){const r=this.ctx,o=this.current,l=o.font,h=o.textRenderingMode,c=o.fontSize/o.fontSizeScale,d=h&E,u=!!(h&S),p=o.patternFill&&!l.missingFile,g=o.patternStroke&&!l.missingFile;let m;(l.disableFontFace||u||p||g)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,e));if(m&&(l.disableFontFace||p||g)){r.save();r.translate(i,n);r.scale(c,-c);this.dependencyTracker?.recordCharacterBBox(t,r,l);let e;if(d===A||d===x)if(s){e=r.getTransform();r.setTransform(...s);const t=this.#cs(m,e,s);r.fill(t)}else r.fill(m);if(d===w||d===x)if(a){e||=r.getTransform();r.setTransform(...a);const{a:t,b:i,c:n,d:s}=e,o=Util.inverseTransform(a),l=Util.transform([t,i,n,s,0,0],o);Util.singularValueDecompose2dScale(l,_t);r.lineWidth*=Math.max(_t[0],_t[1])/c;r.stroke(this.#cs(m,e,a))}else{r.lineWidth/=c;r.stroke(m)}r.restore()}else{if(d===A||d===x){r.fillText(e,i,n);this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,n,()=>r.measureText(e))}if(d===w||d===x){this.dependencyTracker&&this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,n,()=>r.measureText(e)).recordDependencies(t,it);r.strokeText(e,i,n)}}if(u){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(r),x:i,y:n,fontSize:c,path:m});this.dependencyTracker?.recordCharacterBBox(t,r,l,c,i,n)}}get isFontSubpixelAAEnabled(){const t=this.canvasFactory.create(10,10),e=t.context;e.scale(1.5,1);e.fillText("I",0,10);const i=e.getImageData(0,0,10,10).data;this.canvasFactory.destroy(t);let n=!1;for(let t=3;t<i.length;t+=4)if(i[t]>0&&i[t]<255){n=!0;break}return shadow(this,"isFontSubpixelAAEnabled",n)}showText(t,e){if(this.dependencyTracker){this.dependencyTracker.recordDependencies(t,rt).resetBBox(t);this.current.textRenderingMode&S&&this.dependencyTracker.recordFutureForcedDependency("textClip",t).inheritPendingDependenciesAsFutureForcedDependencies()}const i=this.current,n=i.font;if(n.isType3Font){const n=this.#ls(i.fillAlpha);this.showType3Text(t,e);this.dependencyTracker?.recordShowTextOperation(t);this.#hs(n);return}const s=i.fontSize;if(0===s){this.dependencyTracker?.recordOperation(t);return}const a=this.#ls(i.fillAlpha),r=this.ctx,o=i.fontSizeScale,l=i.charSpacing,h=i.wordSpacing,c=i.fontDirection,d=i.textHScale*c,u=e.length,p=n.vertical,g=p?1:-1,m=n.defaultVMetrics,f=s*i.fontMatrix[0],b=i.textRenderingMode===A&&!n.disableFontFace&&!i.patternFill;r.save();i.textMatrix&&r.transform(...i.textMatrix);r.translate(i.x,i.y+i.textRise);c>0?r.scale(d,-1):r.scale(d,1);let y,v;const C=i.textRenderingMode&E,T=C===A||C===x,k=C===w||C===x;let _=i.lineWidth;const M=i.textMatrixScale;0===M||0===_?k&&(_=this.getSinglePixelWidth()):_/=M;if(1!==o){r.scale(o,o);_/=o}r.lineWidth=_;if(T&&i.patternFill){r.save();const e=i.fillColor.getPattern(r,this,getCurrentTransformInverse(r),wt,t);y=getCurrentTransform(r);r.restore();r.fillStyle=e}if(k&&i.patternStroke){r.save();const e=i.strokeColor.getPattern(r,this,getCurrentTransformInverse(r),xt,t);v=getCurrentTransform(r);r.restore();r.strokeStyle=e}if(n.isInvalidPDFjsFont){const n=[];let s=0;for(const t of e){n.push(t.unicode);s+=t.width}const o=n.join("");r.fillText(o,0,0);if(null!==this.dependencyTracker){const e=r.measureText(o);this.dependencyTracker.recordBBox(t,this.ctx,-e.actualBoundingBoxLeft,e.actualBoundingBoxRight,-e.actualBoundingBoxAscent,e.actualBoundingBoxDescent).recordShowTextOperation(t)}i.x+=s*f*d;r.restore();this.compose();this.#hs(a);return}let D,P=0;for(D=0;D<u;++D){const i=e[D];if("number"==typeof i){P+=g*i*s/1e3;continue}let a=!1;const d=(i.isSpace?h:0)+l,u=i.fontChar,A=i.accent;let w,x,C,E=i.width;if(p){const t=i.vmetric||m,e=-(i.vmetric?t[1]:.5*E)*f,n=t[2]*f;E=t?-t[0]:E;w=e/o;x=(P+n)/o}else{w=P/o;x=0}if(n.remeasure&&E>0){C=r.measureText(u);const t=1e3*C.width/s*o;if(E<t&&this.isFontSubpixelAAEnabled){const e=E/t;a=!0;r.save();r.scale(e,1);w/=e}else E!==t&&(w+=(E-t)/2e3*s/o)}if(this.contentVisible&&(i.isInFont||n.missingFile))if(b&&!A){r.fillText(u,w,x);this.dependencyTracker?.recordCharacterBBox(t,r,C?{bbox:null}:n,s/o,w,x,()=>C??r.measureText(u))}else{this.paintChar(t,u,w,x,y,v);if(A){const e=w+s*A.offset.x/o,i=x-s*A.offset.y/o;this.paintChar(t,A.fontChar,e,i,y,v)}}P+=p?E*f-d*c:E*f+d*c;a&&r.restore()}p?i.y-=P:i.x+=P*d;r.restore();this.compose();this.dependencyTracker?.recordShowTextOperation(t);this.#hs(a)}showType3Text(t,e){const i=this.ctx,s=this.current,a=s.font,r=s.fontSize,o=s.fontDirection,l=a.vertical?1:-1,h=s.charSpacing,c=s.wordSpacing,d=s.textHScale*o,u=s.fontMatrix||n,p=e.length;let g,m,f,b;if(s.textRenderingMode===C||0===r)return;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null;i.save();s.textMatrix&&i.transform(...s.textMatrix);i.translate(s.x,s.y+s.textRise);i.scale(d,o);const y=this.dependencyTracker;this.dependencyTracker=y?new CanvasNestedDependencyTracker(y,t):null;for(g=0;g<p;++g){m=e[g];if("number"==typeof m){b=l*m*r/1e3;this.ctx.translate(b,0);s.x+=b*d;continue}const t=(m.isSpace?c:0)+h,n=a.charProcOperatorList[m.operatorListId];if(n){if(this.contentVisible){this.save();if(n.fnArray[0]===B.setCharWidth){s.fillAlpha=s.strokeAlpha=1;i.globalAlpha=1}i.scale(r,r);i.transform(...u);this.executeOperatorList(n);this.restore()}}else warn(`Type3 character "${m.operatorListId}" is not available.`);const o=[m.width,0];Util.applyTransform(o,u);f=o[0]*r+t;i.translate(f,0);s.x+=f*d}i.restore();y&&(this.dependencyTracker=y)}setCharWidth(t,e,i){}setCharWidthAndBounds(t,e,i,n,s,a,r){const o=new Path2D;o.rect(n,s,a-n,r-s);this.ctx.clip(o);this.dependencyTracker?.recordBBox(t,this.ctx,n,a,s,r).recordClipBox(t,this.ctx,n,a,s,r);this.endPath(t)}getColorN_Pattern(t,e){let i;if("TilingPattern"===e[0]){const t=this.baseTransform||getCurrentTransform(this.ctx),n={createCanvasGraphics:(t,e)=>new CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new CanvasNestedDependencyTracker(this.dependencyTracker,e,!0):null)};i=new TilingPattern(e,this.ctx,n,t)}else i=this._getPattern(t,e[1],e[2]);return i}setStrokeColorN(t,...e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.current.strokeColor=this.getColorN_Pattern(t,e);this.current.patternStroke=!0}setFillColorN(t,...e){this.dependencyTracker?.recordSimpleData("fillColor",t);const i=this.current.fillColor=this.getColorN_Pattern(t,e);this.current.patternFill=!0;this.current.tilingPatternDims=i instanceof TilingPattern?[0,0,0,0]:null}setStrokeRGBColor(t,e){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor=e;this.current.patternStroke=!1}setStrokeTransparent(t){this.dependencyTracker?.recordSimpleData("strokeColor",t);this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor=e;this.current.patternFill=!1;this.current.tilingPatternDims=null}setFillTransparent(t){this.dependencyTracker?.recordSimpleData("fillColor",t);this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1;this.current.tilingPatternDims=null}_getPattern(t,e,i=null){let n;if(this.cachedPatterns.has(e))n=this.cachedPatterns.get(e);else{n=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t,e));this.cachedPatterns.set(e,n)}i&&(n.matrix=i);return n}shadingFill(t,e){if(!this.contentVisible)return;const n=this.#ls(this.current.fillAlpha),s=this.ctx;this.save(t);const a=this._getPattern(t,e);s.fillStyle=a.getPattern(s,this,getCurrentTransformInverse(s),Ct,t);const r=getCurrentTransformInverse(s);if(r){const{width:t,height:e}=s.canvas,n=i.slice();Util.axialAlignedBoundingBox([0,0,t,e],r,n);const[a,o,l,h]=n;this.ctx.fillRect(a,o,l-a,h-o)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.dependencyTracker?.resetBBox(t).recordFullPageBBox(t).recordDependencies(t,ot).recordDependencies(t,nt).recordOperation(t);this.compose(this.current.getClippedPathBoundingBox());this.restore(t);this.#hs(n)}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e,i){if(this.contentVisible){this.save(t);this.baseTransformStack.push(this.baseTransform);e&&this.transform(t,...e);this.baseTransform=getCurrentTransform(this.ctx);if(i){Util.axialAlignedBoundingBox(i,this.baseTransform,this.current.minMax);const[e,n,s,a]=i,r=new Path2D;r.rect(e,n,s-e,a-n);this.ctx.clip(r);this.dependencyTracker?.recordClipBox(t,this.ctx,e,s,n,a);this.endPath(t)}}}paintFormXObjectEnd(t){if(this.contentVisible){this.restore(t);this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t,e){if(!this.contentVisible)return;this.save(t);const{inSMaskMode:n}=this;if(n){this.endSMaskMode();this.current.activeSMask=null}const s=this.ctx;if(!(e.needsIsolation&&(e.isolated||e.hasSoftMask)||e.knockout||e.isGray||0!==this.#$n||1!==s.globalAlpha||"source-over"!==s.globalCompositeOperation||n)){if(e.bbox){let t=new Path2D;const[i,n,a,r]=e.bbox;t.rect(i,n,a-i,r-n);if(e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix));t=i}s.clip(t)}this.groupStack.push(null);this.#es.push(null);this.groupLevel++;return}e.isolated||e.knockout||0!==this.#$n||info("TODO: Fully support non-isolated non-knockout groups.");const a=getCurrentTransform(s);e.matrix&&s.transform(...e.matrix);const r=[0,0,s.canvas.width,s.canvas.height];let o;if(e.bbox){o=i.slice();Util.axialAlignedBoundingBox(e.bbox,getCurrentTransform(s),o);o=Util.intersect(o,r)||[0,0,0,0]}else o=r;const l=Math.floor(o[0]),h=Math.floor(o[1]),c=Math.max(Math.ceil(o[2])-l,1),d=Math.max(Math.ceil(o[3])-h,1);this.current.startNewPathAndClipBox([0,0,c,d]);const u=this.canvasFactory.create(c,d);e.smask&&this.smaskGroupCanvases.push(u);const p=u.context,g=e.knockout&&!e.isolated?s:null,m=!e.isolated&&!e.knockout&&!e.smask&&e.needsIsolation&&this.#$n>0,f=e.knockout?this.canvasFactory.create(c,d):null,b=this.#$n;e.knockout?this.#$n++:this.#$n=0;p.translate(-l,-h);p.transform(...a);if(!e.isolated&&!e.smask&&n&&e.needsIsolation){p.save();p.setTransform(1,0,0,1,0,0);p.drawImage(s.canvas,-l,-h);p.restore()}if(e.bbox){let t=new Path2D;const[i,n,s,a]=e.bbox;t.rect(i,n,s-i,a-n);if(e.matrix){const i=new Path2D;i.addPath(t,new DOMMatrix(e.matrix));t=i}p.clip(t)}e.smask&&this.smaskStack.push({canvas:u.canvas,context:p,offsetX:l,offsetY:h,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null});if(!e.smask||this.dependencyTracker){s.setTransform(1,0,0,1,0,0);s.translate(l,h);s.save()}copyCtxState(s,p);this.ctx=p;this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(s);this.setGState(t,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]);this.groupStack.push(s);this.#es.push({backdropCtx:g,savedKnockoutLevel:b,offsetX:l,offsetY:h,hasInnerBackdrop:m,knockoutMaskEntry:f,knockoutTempEntry:null,knockoutBackdropEntry:null});this.groupLevel++}endGroup(t,e){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,s=this.groupStack.pop(),a=this.#es.pop();a&&(this.#$n=a.savedKnockoutLevel);if(null!==s){e.isGray&&this.#ds(n);this.ctx=s;this.ctx.imageSmoothingEnabled=!1;this.dependencyTracker?.popBaseTransform();if(e.smask){this.tempSMask=this.smaskStack.pop();this.restore(t);if(this.dependencyTracker){this.ctx.restore();this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform())}this.#ns(a)}else{this.ctx.restore();const e=getCurrentTransform(this.ctx);this.restore(t);this.ctx.save();this.ctx.setTransform(...e);const r=i.slice();Util.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],e,r);const o=this.#es.at(-1);if(this.#$n>0)if(a.hasInnerBackdrop){const{width:t,height:i}=n.canvas,r=this.canvasFactory.create(t,i),o=r.context;o.drawImage(s.canvas,a.offsetX,a.offsetY,t,i,0,0,t,i);o.globalCompositeOperation="source-over";o.drawImage(n.canvas,0,0);const l=this.#as(n.canvas);o.globalCompositeOperation="destination-in";o.drawImage(l.canvas,0,0);const h=this.ctx.globalCompositeOperation,c=this.ctx.globalAlpha,d=this.ctx.filter;this.ctx.save();this.ctx.setTransform(...e);this.ctx.globalAlpha=1;FeatureTest.isCanvasFilterSupported&&(this.ctx.filter="none");this.ctx.globalCompositeOperation="destination-out";this.ctx.drawImage(l.canvas,0,0);this.ctx.globalCompositeOperation=h;this.ctx.globalAlpha=c;FeatureTest.isCanvasFilterSupported&&(this.ctx.filter=d??"none");this.ctx.drawImage(r.canvas,0,0);this.ctx.restore();this.canvasFactory.destroy(l);this.canvasFactory.destroy(r)}else{const t=o?.backdropCtx??null;this.#os(this.ctx,n.canvas,{backdropCanvas:t?.canvas??null,destTransform:e,backdropOffset:t?[o.offsetX+a.offsetX,o.offsetY+a.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else this.ctx.drawImage(n.canvas,0,0);this.ctx.restore();this.canvasFactory.destroy({canvas:n.canvas,context:n});this.#ns(a);this.compose(r)}}else this.restore(t)}#ds(t){const{canvas:e}=t,{width:i,height:n}=e;if(FeatureTest.isCanvasFilterSupported){t.save();t.setTransform(1,0,0,1,0,0);t.filter="grayscale(1)";t.globalAlpha=1;t.globalCompositeOperation="copy";t.drawImage(e,0,0);t.restore();return}const s=t.getImageData(0,0,i,n),{data:a}=s;for(let t=0,e=a.length;t<e;t+=4){const e=.2126*a[t]+.7152*a[t+1]+.0722*a[t+2]+.5|0;a[t]=a[t+1]=a[t+2]=e}t.putImageData(s,0,0)}#ns(t){if(t){if(t.knockoutMaskEntry){this.canvasFactory.destroy(t.knockoutMaskEntry);t.knockoutMaskEntry=null}if(t.knockoutTempEntry){this.canvasFactory.destroy(t.knockoutTempEntry);t.knockoutTempEntry=null}if(t.knockoutBackdropEntry){this.canvasFactory.destroy(t.knockoutBackdropEntry);t.knockoutBackdropEntry=null}}}beginAnnotation(t,e,i,n,s,a,r){this.#is();resetCtxToDefault(this.ctx);this.ctx.save();this.save(t);this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(i){const s=i[2]-i[0],o=i[3]-i[1];if(a&&this.annotationCanvasMap){(n=n.slice())[4]-=i[0];n[5]-=i[1];(i=i.slice())[0]=i[1]=0;i[2]=s;i[3]=o;Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx),_t);const{viewportScale:t}=this,a=Math.ceil(s*this.outputScaleX*t),l=Math.ceil(o*this.outputScaleY*t);this.annotationCanvas=this.canvasFactory.create(a,l);const{canvas:h,context:c}=this.annotationCanvas;if(r){const t=this.annotationCanvasMap.getOrInsertComputed(e,makeArr);h.setAttribute("data-canvas-name",r);const i=t.findIndex(t=>t.getAttribute("data-canvas-name")===r);-1===i?t.push(h):t[i]=h}else this.annotationCanvasMap.set(e,h);this.annotationCanvas.savedCtx=this.ctx;this.ctx=c;this.ctx.save();this.ctx.setTransform(_t[0],0,0,-_t[1],0,o*_t[1]);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath(t);const e=new Path2D;e.rect(i[0],i[1],s,o);this.ctx.clip(e)}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.baseTransformStack.push(this.baseTransform);this.transform(t,...n);this.transform(t,...s);this.baseTransform=getCurrentTransform(this.ctx)}endAnnotation(t){if(this.annotationCanvas){this.ctx.restore();this.#ss();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(t,e){if(!this.contentVisible)return;const i=e.count;(e=this.getObject(t,e.data,e)).count=i;const n=this.#ls(this.current.fillAlpha),s=this.ctx,a=this._createMaskCanvas(t,e),r=a.canvas;s.save();s.setTransform(1,0,0,1,0,0);s.drawImage(r,a.offsetX,a.offsetY);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,a.offsetX,a.offsetX+r.width,a.offsetY,a.offsetY+r.height).recordOperation(t);s.restore();a.canvasEntry&&this.canvasFactory.destroy(a.canvasEntry);this.compose();this.#hs(n)}paintImageMaskXObjectRepeat(t,e,i,n=0,s=0,a,r){if(!this.contentVisible)return;e=this.getObject(t,e.data,e);const o=this.#ls(this.current.fillAlpha),l=this.ctx;l.save();const h=getCurrentTransform(l);l.transform(i,n,s,a,0,0);const c=this._createMaskCanvas(t,e);l.setTransform(1,0,0,1,c.offsetX-h[4],c.offsetY-h[5]);this.dependencyTracker?.resetBBox(t);for(let e=0,o=r.length;e<o;e+=2){const o=Util.transform(h,[i,n,s,a,r[e],r[e+1]]);l.drawImage(c.canvas,o[4],o[5]);this.dependencyTracker?.recordBBox(t,this.ctx,o[4],o[4]+c.canvas.width,o[5],o[5]+c.canvas.height)}l.restore();c.canvasEntry&&this.canvasFactory.destroy(c.canvasEntry);this.compose();this.dependencyTracker?.recordOperation(t);this.#hs(o)}paintImageMaskXObjectGroup(t,e){if(!this.contentVisible)return;const i=this.#ls(this.current.fillAlpha),n=this.ctx,s=this.current.fillColor,a=this.current.patternFill;this.dependencyTracker?.resetBBox(t).recordDependencies(t,lt);for(const i of e){const{data:e,width:r,height:o,transform:l}=i,h=this.canvasFactory.create(r,o),c=h.context;c.save();putBinaryImageMask(c,this.getObject(t,e,i));c.globalCompositeOperation="source-in";c.fillStyle=a?s.getPattern(c,this,getCurrentTransformInverse(n),wt,t):s;c.fillRect(0,0,r,o);c.restore();n.save();n.transform(...l);n.scale(1,-1);drawImageAtIntegerCoords(n,h.canvas,0,0,r,o,0,-1,1,1);this.canvasFactory.destroy(h);this.dependencyTracker?.recordBBox(t,n,0,r,0,o);n.restore()}this.compose();this.dependencyTracker?.recordOperation(t);this.#hs(i)}paintImageXObject(t,e){if(!this.contentVisible)return;const i=this.getObject(t,e);i?this.paintInlineImageXObject(t,i):warn("Dependent image isn't ready yet")}paintImageXObjectRepeat(t,e,i,n,s){if(!this.contentVisible)return;const a=this.getObject(t,e);if(!a){warn("Dependent image isn't ready yet");return}const r=a.width,o=a.height,l=[];for(let t=0,e=s.length;t<e;t+=2)l.push({transform:[i,0,0,n,s[t],s[t+1]],x:0,y:0,w:r,h:o});this.paintInlineImageXObjectGroup(t,a,l)}applyTransferMapsToCanvas(t){if("none"!==this.current.transferMaps){t.filter=this.current.transferMaps;t.drawImage(t.canvas,0,0);t.filter="none"}return t.canvas}applyTransferMapsToBitmap(t){if("none"===this.current.transferMaps)return{img:t.bitmap,canvasEntry:null};const{bitmap:e,width:i,height:n}=t,s=this.canvasFactory.create(i,n),a=s.context;a.filter=this.current.transferMaps;a.drawImage(e,0,0);a.filter="none";return{img:s.canvas,canvasEntry:s}}paintInlineImageXObject(t,e){if(!this.contentVisible)return;const i=e.width,n=e.height,s=this.#ls(this.current.fillAlpha),a=this.ctx;this.save(t);const{filter:r}=a;"none"!==r&&""!==r&&(a.filter="none");a.scale(1/i,-1/n);let o,l=null;if(e.bitmap){const t=this.applyTransferMapsToBitmap(e);o=t.img;l=t.canvasEntry}else{const t=this.canvasFactory.create(i,n);putBinaryImageData(t.context,e);o=this.applyTransferMapsToCanvas(t.context);l=t}const h=this._scaleImage(o,getCurrentTransformInverse(a));a.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(a),e.interpolate);if(this.dependencyTracker){this.dependencyTracker.resetBBox(t).recordBBox(t,a,0,i,-n,0).recordDependencies(t,st).recordOperation(t);this.imagesTracker?.record(a,i,n,this.dependencyTracker.clipBox)}drawImageAtIntegerCoords(a,h.img,0,0,h.paintWidth,h.paintHeight,0,-n,i,n);h.tmpCanvas&&this.canvasFactory.destroy(h.tmpCanvas);l&&this.canvasFactory.destroy(l);this.compose();this.restore(t);this.#hs(s)}paintInlineImageXObjectGroup(t,e,i){if(!this.contentVisible)return;const n=this.#ls(this.current.fillAlpha),s=this.ctx;let a,r=null;if(e.bitmap)a=e.bitmap;else{const t=e.width,i=e.height,n=this.canvasFactory.create(t,i);putBinaryImageData(n.context,e);a=this.applyTransferMapsToCanvas(n.context);r=n}this.dependencyTracker?.resetBBox(t);for(const e of i){s.save();s.transform(...e.transform);s.scale(1,-1);drawImageAtIntegerCoords(s,a,e.x,e.y,e.w,e.h,0,-1,1,1);this.dependencyTracker?.recordBBox(t,s,0,1,-1,0);s.restore()}r&&this.canvasFactory.destroy(r);this.dependencyTracker?.recordOperation(t);this.compose();this.#hs(n)}paintSolidColorImageMask(t){if(!this.contentVisible)return;const e=this.#ls(this.current.fillAlpha);this.dependencyTracker?.resetBBox(t).recordBBox(t,this.ctx,0,1,0,1).recordDependencies(t,nt).recordOperation(t);this.ctx.fillRect(0,0,1,1);this.compose();this.#hs(e)}markPoint(t,e){}markPointProps(t,e,i){}beginMarkedContent(t,e){this.dependencyTracker?.beginMarkedContent(t);this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e,i){this.dependencyTracker?.beginMarkedContent(t);"OC"===e?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(i)}):this.markedContentStack.push({visible:!0});this.contentVisible=this.isContentVisible()}endMarkedContent(t){this.dependencyTracker?.endMarkedContent(t);this.markedContentStack.pop();this.contentVisible=this.isContentVisible()}beginCompat(t){}endCompat(t){}consumePath(t,e,i){const n=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath();this.pendingClip||this.compose(i);const s=this.ctx;if(this.pendingClip){n||(this.pendingClip===It?s.clip(e,"evenodd"):s.clip(e));this.pendingClip=null;this.dependencyTracker?.bboxToClipBoxDropOperation(t).recordFutureForcedDependency("clipPath",t)}else this.dependencyTracker?.recordOperation(t);this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=getCurrentTransform(this.ctx);if(0===t[1]&&0===t[2])this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),i=Math.hypot(t[0],t[2]),n=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(i,n)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(-1===this._cachedScaleForStroking[0]){const{lineWidth:t}=this.current,{a:e,b:i,c:n,d:s}=this.ctx.getTransform();let a,r;if(0===i&&0===n){const i=Math.abs(e),n=Math.abs(s);if(i===n)if(0===t)a=r=1/i;else{const e=i*t;a=r=e<1?1/e:1}else if(0===t){a=1/i;r=1/n}else{const e=i*t,s=n*t;a=e<1?1/e:1;r=s<1?1/s:1}}else{const o=Math.abs(e*s-i*n),l=Math.hypot(e,i),h=Math.hypot(n,s);if(0===t){a=h/o;r=l/o}else{const e=t*o;a=h>e?h/e:1;r=l>e?l/e:1}}this._cachedScaleForStroking[0]=a;this._cachedScaleForStroking[1]=r}return this._cachedScaleForStroking}rescaleAndStroke(t,e){const{ctx:i,current:{lineWidth:n}}=this,[s,a]=this.getScaleForStroking();if(s===a){i.lineWidth=(n||1)*s;i.stroke(t);return}const r=i.getLineDash();e&&i.save();i.scale(s,a);kt.a=1/s;kt.d=1/a;const o=new Path2D;o.addPath(t,kt);if(r.length>0){const t=Math.max(s,a);i.setLineDash(r.map(e=>e/t));i.lineDashOffset/=t}i.lineWidth=n||1;i.stroke(o);e&&i.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in B)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[B[t]]=CanvasGraphics.prototype[t]);class BasePDFStream{#us=null;#ps=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(t,e,i){this._source=t;this.#us=e;this.#ps=i}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){assert(!this._fullReader,"BasePDFStream.getFullReader can only be called once.");return this._fullReader=new this.#us(this)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new this.#ps(this,t,e);this._rangeReaders.add(i);return i}cancelAllRequests(t){this._fullReader?.cancel(t);for(const e of new Set(this._rangeReaders))e.cancel(t)}}class BasePDFStreamReader{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(t){this._stream=t}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}class BasePDFStreamRangeReader{_stream=null;constructor(t,e,i){this._stream=t}async read(){unreachable("Abstract method `read` called")}cancel(t){unreachable("Abstract method `cancel` called")}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const n=e[t];void 0!==n&&i.append(t,n)}return i}function getResponseOrigin(t){return URL.parse(t)?.origin??null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:n}){const s={contentLength:0,isRangeSupported:!1},a=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(a))return s;s.contentLength=a;if(a<=2*i)return s;if(n||!e)return s;if("bytes"!==t.get("Accept-Ranges"))return s;"identity"===(t.get("Content-Encoding")||"identity")&&(s.isRangeSupported=!0);return s}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const n=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=n.exec(t));){let[,t,n,s]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[n,s]}const s=[];for(let t=0;t<e.length&&t in e;++t){let[i,n]=e[t];n=rfc2616unquote(n);if(i){n=unescape(n);0===t&&(n=rfc5987decode(n))}s.push(n)}return s.join("")}(t);if(i)return fixupEncoding(rfc2047decode(i));i=toParamRegExp("filename","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=rfc2047decode(t);return fixupEncoding(t)}function toParamRegExp(t,e){return new RegExp("(?:^|;)\\s*"+t+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',e)}function textdecode(t,i){if(t){if(!/^[\x00-\xFF]+$/.test(i))return i;try{const n=new TextDecoder(t,{fatal:!0}),s=stringToBytes(i);i=n.decode(s);e=!1}catch{}}return i}function fixupEncoding(t){if(e&&/[\x80-\xff]/.test(t)){t=textdecode("utf-8",t);e&&(t=textdecode("iso-8859-1",t))}return t}function rfc2616unquote(t){if(t.startsWith('"')){const e=t.slice(1).split('\\"');for(let t=0;t<e.length;++t){const i=e[t].indexOf('"');if(-1!==i){e[t]=e[t].slice(0,i);e.length=t+1}e[t]=e[t].replaceAll(/\\(.)/g,"$1")}t=e.join('"')}return t}function rfc5987decode(t){const e=t.indexOf("'");return-1===e?t:textdecode(t.slice(0,e),t.slice(e+1).replace(/^[^']*'/,""))}function rfc2047decode(t){return!t.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(t)?t:t.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(t,e,i,n){if("q"===i||"Q"===i)return textdecode(e,n=(n=n.replaceAll("_"," ")).replaceAll(/=([0-9a-f]{2})/gi,function(t,e){return String.fromCharCode(parseInt(e,16))}));try{n=atob(n)}catch{}return textdecode(e,n)})}return""}(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(isPdfFile(t))return t}return null}function createResponseError(t,e){return new ResponseException(`Unexpected server response (${t}) while retrieving PDF "${e.href}".`,t,404===t||0===t&&"file:"===e.protocol)}function ensureResponseOrigin(t,e){if(t!==e)throw new Error(`Expected range response-origin "${t}" to match "${e}".`)}function fetchUrl(t,e,i,n){return fetch(t,{method:"GET",headers:e,signal:n.signal,mode:"cors",credentials:i?"include":"same-origin",redirect:"follow"})}function ensureResponseStatus(t,e){if(200!==t&&206!==t)throw createResponseError(t,e)}function getArrayBuffer(t){if(t instanceof Uint8Array)return t.buffer;if(t instanceof ArrayBuffer)return t;throw new Error(`getArrayBuffer - unexpected data: ${t}`)}class PDFFetchStream extends BasePDFStream{_responseOrigin=null;constructor(t){super(t,PDFFetchStreamReader,PDFFetchStreamRangeReader);const{httpHeaders:e,url:i}=t;assert(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs.");this.headers=createHeaders(!0,e)}}class PDFFetchStreamReader extends BasePDFStreamReader{_abortController=new AbortController;_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,rangeChunkSize:n,url:s,withCredentials:a}=t._source;this._isStreamingSupported=!i;const r=new Headers(t.headers);fetchUrl(s,r,a,this._abortController).then(i=>{t._responseOrigin=getResponseOrigin(i.url);ensureResponseStatus(i.status,s);this._reader=i.body.getReader();const a=i.headers,{contentLength:r,isRangeSupported:o}=validateRangeRequestCapabilities({responseHeaders:a,isHttp:!0,rangeChunkSize:n,disableRange:e});this._contentLength=r;this._isRangeSupported=o;this._filename=extractFilenameFromHeader(a);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this._callOnProgress();return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader extends BasePDFStreamRangeReader{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n,withCredentials:s}=t._source,a=new Headers(t.headers);a.append("Range",`bytes=${e}-${i-1}`);fetchUrl(n,a,s,this._abortController).then(e=>{ensureResponseOrigin(getResponseOrigin(e.url),t._responseOrigin);ensureResponseStatus(e.status,n);this._reader=e.body.getReader();this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}function transport_stream_getArrayBuffer(t){return t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function endRequests(){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}class PDFDataTransportStream extends BasePDFStream{_progressiveDone=!1;_queuedChunks=[];constructor(t){super(t,PDFDataTransportStreamReader,PDFDataTransportStreamRangeReader);const{pdfDataRangeTransport:e}=t,{initialData:i,progressiveDone:n}=e;if(i?.length>0){const t=transport_stream_getArrayBuffer(i);this._queuedChunks.push(t)}this._progressiveDone=n;e.transportReady(t=>{switch(t.type){case"range":case"progressiveRead":this.#gs(t.begin,t.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone();this._progressiveDone=!0}})}#gs(t,e){const i=transport_stream_getArrayBuffer(e);if(void 0===t)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const e=this._rangeReaders.keys().find(e=>e._begin===t);assert(e,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");e._enqueue(i)}}getFullReader(){const t=super.getFullReader();this._queuedChunks=null;return t}getRangeReader(t,e){const i=super.getRangeReader(t,e);if(i){i.onDone=()=>this._rangeReaders.delete(i);this._source.pdfDataRangeTransport.requestDataRange(t,e)}return i}cancelAllRequests(t){super.cancelAllRequests(t);this._source.pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader extends BasePDFStreamReader{#ms=endRequests.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(t){super(t);const{pdfDataRangeTransport:e,disableRange:i,disableStream:n}=t._source,{length:s,contentDispositionFilename:a}=e;this._queuedChunks=t._queuedChunks||[];for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._done=t._progressiveDone;this._contentLength=s;this._isStreamingSupported=!n;this._isRangeSupported=!i;isPdfFile(a)&&(this._filename=a);this._headersCapability.resolve();const r=this._loaded;Promise.resolve().then(()=>{r>0&&this._loaded===r&&this._callOnProgress()})}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength;this._callOnProgress()}}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ms()}progressiveDone(){this._done||=!0;0===this._queuedChunks.length&&this.#ms()}}class PDFDataTransportStreamRangeReader extends BasePDFStreamRangeReader{#ms=endRequests.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(t,e,i){super(t,e,i);this._begin=e}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});this.#ms()}this._done=!0;this.onDone?.()}}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ms();this.onDone?.()}}class PDFNetworkStream extends BasePDFStream{#fs=new WeakMap;_responseOrigin=null;constructor(t){super(t,PDFNetworkStreamReader,PDFNetworkStreamRangeReader);const{httpHeaders:e,url:i}=t;this.url=i;this.isHttp=/https?:/.test(i.protocol);this.headers=createHeaders(this.isHttp,e)}_request(t){const e=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};this.#fs.set(e,i);e.open("GET",this.url);e.withCredentials=this._source.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);i.validateStatus=t=>206===t||200===t}else i.validateStatus=t=>200===t;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>t.onError(e.status);e.onreadystatechange=this.#bs.bind(this,e);e.onprogress=this.#ys.bind(this,e);e.send(null);return e}#ys(t,e){const i=this.#fs.get(t);i?.onProgress?.(e)}#bs(t,e){const i=this.#fs.get(t);if(!i)return;if(t.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==t.readyState)return;if(!this.#fs.has(t))return;this.#fs.delete(t);if(0===t.status&&this.isHttp){i.onError(t.status);return}const n=t.status||200;if(!i.validateStatus(n)){i.onError(t.status);return}const s=function network_getArrayBuffer(t){return"string"!=typeof t?t:stringToBytes(t).buffer}(t.response);if(206===n){const e=t.getResponseHeader("Content-Range");if(/bytes \d+-\d+\/\d+/.test(e))i.onDone(s);else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else s?i.onDone(s):i.onError(t.status)}_abortRequest(t){if(this.#fs.has(t)){this.#fs.delete(t);t.abort()}}getRangeReader(t,e){const i=super.getRangeReader(t,e);i&&(i.onClosed=()=>this._rangeReaders.delete(i));return i}}class PDFNetworkStreamReader extends BasePDFStreamReader{#ms=endRequests.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(t){super(t);this._fullRequestXhr=t._request({onHeadersReceived:this.#vs.bind(this),onDone:this.#As.bind(this),onError:this.#ws.bind(this),onProgress:this.#ys.bind(this)})}#vs(){const t=this._stream,{disableRange:e,rangeChunkSize:i}=t._source,n=this._fullRequestXhr;t._responseOrigin=getResponseOrigin(n.responseURL);const s=n.getAllResponseHeaders(),a=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]}):[]),{contentLength:r,isRangeSupported:o}=validateRangeRequestCapabilities({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:i,disableRange:e});this._contentLength=r;this._isRangeSupported=o;this._filename=extractFilenameFromHeader(a);this._isRangeSupported&&t._abortRequest(n);this._headersCapability.resolve()}#As(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._cachedChunks.push(t);this._done=!0;0===this._cachedChunks.length&&this.#ms()}#ws(t){this._storedError=createResponseError(t,this._stream.url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}#ys(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);this.#ms();this._stream._abortRequest(this._fullRequestXhr);this._fullRequestXhr=null}}class PDFNetworkStreamRangeReader extends BasePDFStreamRangeReader{#ms=endRequests.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(t,e,i){super(t,e,i);this._requestXhr=t._request({begin:e,end:i,onHeadersReceived:this.#vs.bind(this),onDone:this.#As.bind(this),onError:this.#ws.bind(this),onProgress:null})}#vs(){const t=getResponseOrigin(this._requestXhr?.responseURL);try{ensureResponseOrigin(t,this._stream._responseOrigin)}catch(t){this._storedError=t;this.#ws(0)}}#As(t){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunk=t;this._done=!0;this.#ms();this.onClosed?.()}#ws(t){this._storedError??=createResponseError(t,this._stream.url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this.#ms();this._stream._abortRequest(this._requestXhr);this.onClosed?.()}}function getReadableStream(t,e=null){const i=process.getBuiltinModule("fs"),{Readable:n}=process.getBuiltinModule("stream"),s=i.createReadStream(t,e);return n.toWeb(s)}class PDFNodeStream extends BasePDFStream{constructor(t){super(t,PDFNodeStreamReader,PDFNodeStreamRangeReader);const{url:e}=t;assert("file:"===e.protocol,"PDFNodeStream only supports file:// URLs.")}}class PDFNodeStreamReader extends BasePDFStreamReader{_reader=null;constructor(t){super(t);const{disableRange:e,disableStream:i,rangeChunkSize:n,url:s}=t._source;this._isStreamingSupported=!i;process.getBuiltinModule("fs/promises").lstat(s).then(t=>{const i=getReadableStream(s);this._reader=i.getReader();const{size:a}=t;this._contentLength=a;this._isRangeSupported=!e&&a>2*n;!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."));this._headersCapability.resolve()}).catch(t=>{"ENOENT"===t.code&&(t=createResponseError(0,s));this._headersCapability.reject(t)})}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this._callOnProgress();return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class PDFNodeStreamRangeReader extends BasePDFStreamRangeReader{_readCapability=Promise.withResolvers();_reader=null;constructor(t,e,i){super(t,e,i);const{url:n}=t._source;try{const t=getReadableStream(n,{start:e,end:i-1});this._reader=t.getReader();this._readCapability.resolve()}catch(t){this._readCapability.reject(t)}}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t)}}class GlobalWorkerOptions{static#xs=null;static#Cs="";static get workerPort(){return this.#xs}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#xs=t}static get workerSrc(){return this.#Cs}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#Cs=t}}class Metadata{#Es;#Ss;constructor({parsedData:t,rawData:e}){this.#Es=t;this.#Ss=e}getRaw(){return this.#Ss}get(t){return this.#Es.get(t)??null}[Symbol.iterator](){return this.#Es.entries()}}const Ft=Symbol("INTERNAL");class OptionalContentGroup{#Ts=!1;#ks=!1;#_s=!1;#Ms=!0;constructor(t,{name:e,intent:i,usage:n,rbGroups:s}){this.#Ts=!!(t&o);this.#ks=!!(t&l);this.name=e;this.intent=i;this.usage=n;this.rbGroups=s}get visible(){if(this.#_s)return this.#Ms;if(!this.#Ms)return!1;const{print:t,view:e}=this.usage;return this.#Ts?"OFF"!==e?.viewState:!this.#ks||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Ft&&unreachable("Internal method `_setVisible` called.");this.#_s=i;this.#Ms=e}get serializable(){return{userSet:this.#_s,visible:this.#Ms}}}class OptionalContentConfig{#Ds=null;#Ps=new Map;#Is=null;#Fs=null;#Bs;creator=null;name=null;constructor(t,e=o,i=null){this.#Bs=t;this.renderingIntent=e;if(null!==t){this.name=t.name;this.creator=t.creator;this.#Fs=t.order;for(const i of t.groups)this.#Ps.set(i.id,new OptionalContentGroup(e,i));if(i){i.size!==this.#Ps.size&&unreachable("Incorrect serialized groupState.");for(const[t,e]of i)this.#Ps.get(t)._setVisible(Ft,e.visible,e.userSet)}else{if("OFF"===t.baseState)for(const t of this.#Ps.values())t._setVisible(Ft,!1);for(const e of t.on)this.#Ps.get(e)._setVisible(Ft,!0);for(const e of t.off)this.#Ps.get(e)._setVisible(Ft,!1)}this.#Is=this.getHash()}}#Ls(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n<e;n++){const e=t[n];let s;if(Array.isArray(e))s=this.#Ls(e);else{if(!this.#Ps.has(e)){warn(`Optional content group not found: ${e}`);return!0}s=this.#Ps.get(e).visible}switch(i){case"And":if(!s)return!1;break;case"Or":if(s)return!0;break;case"Not":return!s;default:return!0}}return"And"===i}isVisible(t){if(0===this.#Ps.size)return!0;if(!t){info("Optional content group not defined.");return!0}if("OCG"===t.type){if(!this.#Ps.has(t.id)){warn(`Optional content group not found: ${t.id}`);return!0}return this.#Ps.get(t.id).visible}if("OCMD"===t.type){if(t.expression)return this.#Ls(t.expression);if(!t.policy||"AnyOn"===t.policy){for(const e of t.ids){if(!this.#Ps.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#Ps.get(e).visible)return!0}return!1}if("AllOn"===t.policy){for(const e of t.ids){if(!this.#Ps.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#Ps.get(e).visible)return!1}return!0}if("AnyOff"===t.policy){for(const e of t.ids){if(!this.#Ps.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(!this.#Ps.get(e).visible)return!0}return!1}if("AllOff"===t.policy){for(const e of t.ids){if(!this.#Ps.has(e)){warn(`Optional content group not found: ${e}`);return!0}if(this.#Ps.get(e).visible)return!1}return!0}warn(`Unknown optional content policy ${t.policy}.`);return!0}warn(`Unknown group type ${t.type}.`);return!0}setVisibility(t,e=!0,i=!0){const n=this.#Ps.get(t);if(n){if(i&&e&&n.rbGroups.length)for(const e of n.rbGroups)for(const i of e)i!==t&&this.#Ps.get(i)?._setVisible(Ft,!1,!0);n._setVisible(Ft,!!e,!0);this.#Ds=null}else warn(`Optional content group not found: ${t}`)}setOCGState({state:t,preserveRB:e}){let i;for(const n of t){switch(n){case"ON":case"OFF":case"Toggle":i=n;continue}const t=this.#Ps.get(n);if(t)switch(i){case"ON":this.setVisibility(n,!0,e);break;case"OFF":this.setVisibility(n,!1,e);break;case"Toggle":this.setVisibility(n,!t.visible,e)}}this.#Ds=null}get hasInitialVisibility(){return null===this.#Is||this.getHash()===this.#Is}getOrder(){return this.#Ps.size?this.#Fs?this.#Fs.slice():[...this.#Ps.keys()]:null}getGroup(t){return this.#Ps.get(t)||null}getHash(){if(null!==this.#Ds)return this.#Ds;const t=new MurmurHash3_64;for(const[e,i]of this.#Ps)t.update(`${e}:${i.visible}`);return this.#Ds=t.hexdigest()}[Symbol.iterator](){return this.#Ps.entries()}get serializable(){const t=new Map;for(const[e,i]of this.#Ps)t.set(e,i.serializable);return{data:this.#Bs,renderingIntent:this.renderingIntent,groupState:t}}static fromSerializable({data:t,renderingIntent:e,groupState:i}){return new OptionalContentConfig(t,e,i)}}class PagesMapper{#Os=null;#Rs=null;#Ns=0;#Us=null;#Hs=null;get pagesNumber(){return this.#Ns}set pagesNumber(t){if(this.#Ns!==t){this.#Ns=t;this.#Os=null;this.#Rs=null}}#zs(){if(this.#Os)return;const t=this.#Ns,e=this.#Os=new Uint32Array(t);for(let i=0;i<t;i++)e[i]=i+1;this.#Rs=new Int32Array(e)}#Gs(){const t=new Map,e=this.#Os;for(let i=0,n=this.#Ns;i<n;i++){const n=e[i],s=t.get(n);s?s.push(i+1):t.set(n,[i+1])}return t}movePages(t,e,i){this.#zs();const n=this.#Os,s=this.#Gs(),a=e.length,r=new Uint32Array(a);let o=0;for(let t=0;t<a;t++){const s=e[t]-1;r[t]=n[s];s<i&&o++}const l=this.#Ns,h=l-a,c=MathClamp(i-o,0,h);for(let e=0,i=0;e<l;e++)t.has(e+1)||(n[i++]=n[e]);n.copyWithin(c+a,c,h);n.set(r,c);this.#Ws(s);n.every((t,e)=>t===e+1)&&(this.#Os=null)}deletePages(t){this.#zs();const e=this.#Os,i=this.#Gs();this.#Hs={pageNumberToId:e.slice(),pagesNumber:this.#Ns,prevPageNumbers:this.#Rs.slice()};const n=this.#Ns-t.length;this.#Ns=n;const s=this.#Os=new Uint32Array(n);this.#Rs=new Int32Array(n);let a=0,r=0;for(const i of t){const t=i-1;if(t!==a){s.set(e.subarray(a,t),r);r+=t-a}a=t+1}a<e.length&&s.set(e.subarray(a),r);this.#Ws(i,new Set(t))}cancelDelete(){if(this.#Hs){this.#Os=this.#Hs.pageNumberToId;this.#Ns=this.#Hs.pagesNumber;this.#Rs=this.#Hs.prevPageNumbers;this.#Hs=null}}cleanSavedData(){this.#Hs=null}copyPages(t){this.#zs();this.#Us={pageNumbers:t,pageIds:t.map(t=>this.#Os[t-1])}}cancelCopy(){this.#Us=null}pastePages(t){this.#zs();const e=this.#Os,i=this.#Gs(),{pageNumbers:n,pageIds:s}=this.#Us,a=this.#Ns+n.length;this.#Ns=a;const r=this.#Os=new Uint32Array(a);this.#Rs=new Int32Array(a);r.set(e.subarray(0,t),0);r.set(s,t);r.set(e.subarray(t),t+n.length);this.#Ws(i,null,t,n);this.#Us=null}#Ws(t,e=null,i=-1,n=null){const s=this.#Rs,a=this.#Os,r=i+(n?.length??0),o=new Map;for(let l=0,h=this.#Ns;l<h;l++){if(l>=i&&l<r){s[l]=-n[l-i];continue}const h=a[l],c=t.get(h);let d=o.get(h)||0;if(e&&c)for(;d<c.length&&e.has(c[d]);)d++;s[l]=c?.[d];o.set(h,d+1)}}hasBeenAltered(){return null!==this.#Os}getPageMappingForSaving(t=null){t??=this.#Gs();let e=0;for(const i of t.values())e=Math.max(e,i.length);const i=new Array(e);for(let t=0;t<e;t++)i[t]={document:null,pageIndices:[],includePages:[]};for(const[e,n]of t)for(let t=0,s=n.length;t<s;t++)i[t].includePages.push([e-1,n[t]-1]);for(const{includePages:t,pageIndices:e}of i){t.sort((t,e)=>t[0]-e[0]);for(let i=0,n=t.length;i<n;i++){e.push(t[i][1]);t[i]=t[i][0]}}return i}extractPages(t){t=Array.from(t).sort((t,e)=>t-e);const e=new Map;for(let i=0,n=t.length;i<n;i++){const n=this.getPageId(t[i]);e.getOrInsertComputed(n,makeArr).push(i+1)}return this.getPageMappingForSaving(e)}getPrevPageNumber(t){return this.#Rs?.[t-1]??0}getPageNumber(t){if(!this.#Os)return t;const e=this.#Os;for(let i=0,n=this.#Ns;i<n;i++)if(e[i]===t)return i+1;return 0}getPageId(t){return this.#Os?.[t-1]??t}getMapping(){return this.#Os?.subarray(0,this.pagesNumber)}}const Bt=Symbol("INITIAL_DATA"),dataObj=()=>({...Promise.withResolvers(),data:Bt});class PDFObjects{#Vs=new Map;get(t,e=null){if(e){const i=this.#Vs.getOrInsertComputed(t,dataObj);i.promise.then(()=>e(i.data));return null}const i=this.#Vs.get(t);if(!i||i.data===Bt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Vs.get(t);return!!e&&e.data!==Bt}delete(t){const e=this.#Vs.get(t);if(!e||e.data===Bt)return!1;this.#Vs.delete(t);return!0}resolve(t,e=null){const i=this.#Vs.getOrInsertComputed(t,dataObj);if(i.data!==Bt)throw new Error(`Object already resolved ${t}.`);i.data=e;i.resolve()}clear(){for(const{data:t}of this.#Vs.values())t?.bitmap?.close();this.#Vs.clear()}*[Symbol.iterator](){for(const[t,{data:e}]of this.#Vs)e!==Bt&&(yield[t,e])}}class TextLayer{#js=Promise.withResolvers();#_t=null;#$s=!1;#Ks=!!globalThis.FontInspector?.enabled;#Xs=null;#qs=null;#Ys=null;#Qs=0;#Js=0;#Zs=null;#ta=null;#ea=0;#ia=0;#na=Object.create(null);#sa=[];#aa=null;#ra=[];#oa=new WeakMap;#la=null;static#ha=new Map;static#ca=new Map;static#da=new WeakMap;static#ua=null;static#pa=new Set;constructor({textContentSource:t,images:e,container:i,viewport:n}){if(t instanceof ReadableStream)this.#aa=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#aa=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#_t=this.#ta=i;this.#Xs=e;this.#ia=n.scale*OutputScale.pixelRatio;this.#ea=n.rotation;this.#Ys={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:a,pageX:r,pageY:o}=n.rawDims;this.#la=[1,0,0,-1,-r,o+a];this.#Js=s;this.#Qs=a;TextLayer.#ga();i.style.setProperty("--min-font-size",TextLayer.#ua);setLayerDimensions(i,n);this.#js.promise.finally(()=>{TextLayer.#pa.delete(this);this.#Ys=null;this.#na=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){this.#Xs&&this.#_t.append(this.#Xs.render());const pump=()=>{this.#Zs.read().then(({value:t,done:e})=>{if(e)this.#js.resolve();else{this.#qs??=t.lang;Object.assign(this.#na,t.styles);this.#ma(t.items);pump()}},this.#js.reject)};this.#Zs=this.#aa.getReader();TextLayer.#pa.add(this);pump();return this.#js.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*OutputScale.pixelRatio,n=t.rotation;if(n!==this.#ea){e?.();this.#ea=n;setLayerDimensions(this.#ta,{rotation:n})}if(i!==this.#ia){e?.();this.#ia=i;const t={div:null,properties:null,ctx:TextLayer.#fa(this.#qs)};for(const e of this.#ra){t.properties=this.#oa.get(e);t.div=e;this.#ba(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Zs?.cancel(t).catch(()=>{});this.#Zs=null;this.#js.reject(t)}get textDivs(){return this.#ra}get textContentItemsStr(){return this.#sa}#ma(t){if(this.#$s)return;this.#Ys.ctx??=TextLayer.#fa(this.#qs);const e=this.#ra,i=this.#sa;for(const n of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#$s=!0;return}if(void 0!==n.str){i.push(n.str);this.#ya(n)}else if("beginMarkedContentProps"===n.type||"beginMarkedContent"===n.type){const t=this.#_t;this.#_t=document.createElement("span");this.#_t.classList.add("markedContent");n.id&&this.#_t.setAttribute("id",`${n.id}`);"Artifact"===n.tag&&(this.#_t.ariaHidden=!0);t.append(this.#_t)}else"endMarkedContent"===n.type&&(this.#_t=this.#_t.parentNode)}}#ya(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#ra.push(e);const n=Util.transform(this.#la,t.transform);let s=Math.atan2(n[1],n[0]);const a=this.#na[t.fontName];a.vertical&&(s+=Math.PI/2);let r=this.#Ks&&a.fontSubstitution||a.fontFamily;r=TextLayer.fontFamilyMap.get(r)||r;const o=Math.hypot(n[2],n[3]),l=o*TextLayer.#va(r,a,this.#qs);let h,c;if(0===s){h=n[4];c=n[5]-l}else{h=n[4]+l*Math.sin(s);c=n[5]-l*Math.cos(s)}const d=e.style;d.left=`${(100*h/this.#Js).toFixed(2)}%`;d.top=`${(100*c/this.#Qs).toFixed(2)}%`;d.setProperty("--font-height",`${o.toFixed(2)}px`);d.fontFamily=r;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ks&&(e.dataset.fontName=a.fontSubstitutionLoadedName||t.fontName);0!==s&&(i.angle=s*(180/Math.PI));let u=!1;if(t.str.length>1)u=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(u=!0)}u&&(i.canvasWidth=a.vertical?t.height:t.width);this.#oa.set(e,i);this.#Ys.div=e;this.#Ys.properties=i;this.#ba(this.#Ys);i.hasText&&this.#_t.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#_t.append(t)}}#ba(t){const{div:e,properties:i,ctx:n}=t,{style:s}=e;if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=s,{canvasWidth:a,fontSize:r}=i;TextLayer.#Aa(n,r*this.#ia,t);const{width:o}=n.measureText(e.textContent);o>0&&s.setProperty("--scale-x",a*this.#ia/o)}0!==i.angle&&s.setProperty("--rotate",`${i.angle}deg`)}static cleanup(){if(!(this.#pa.size>0)){this.#ha.clear();for(const{canvas:t}of this.#ca.values())t.remove();this.#ca.clear()}}static#fa(t=null){let e=this.#ca.get(t||="");if(!e){const i=document.createElement("canvas");i.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#ca.set(t,e);this.#da.set(e,{size:0,family:""})}return e}static#Aa(t,e,i){const n=this.#da.get(t);if(e!==n.size||i!==n.family){t.font=`${e}px ${i}`;n.size=e;n.family=i}}static#ga(){if(null!==this.#ua)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#ua=t.getBoundingClientRect().height;t.remove()}static#va(t,e,i){const n=this.#ha.get(t);if(n)return n;const s=this.#fa(i);s.canvas.width=s.canvas.height=30;this.#Aa(s,30,t);const a=s.measureText(""),r=a.fontBoundingBoxAscent,o=Math.abs(a.fontBoundingBoxDescent);s.canvas.width=s.canvas.height=0;let l=.8;if(r)l=r/(r+o);else{FeatureTest.platform.isFirefox&&warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");e.ascent?l=e.ascent:e.descent&&(l=1+e.descent)}this.#ha.set(t,l);return l}}function getDocument(e={}){const i=new PDFDocumentLoadingTask,{docId:n}=i,s=e.url?function getUrlProp(e){if(e instanceof URL)return e;if("string"==typeof e){if(t){if(/^[a-z][a-z0-9\-+.]+:/i.test(e))return new URL(e);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(e))}const i=URL.parse(e,window.location);if(i)return i}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(e.url):null,a=e.data?function getDataProp(e){if(t&&"undefined"!=typeof Buffer&&e instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if("string"==typeof e)return stringToBytes(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||"object"==typeof e&&!isNaN(e?.length))return new Uint8Array(e);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(e.data):null,r=e.httpHeaders||null,o=!0===e.withCredentials,l=e.password??null,h=e.range instanceof PDFDataRangeTransport?e.range:null,c=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536;let d=e.worker instanceof PDFWorker?e.worker:null;const u=e.verbosity,p="string"!=typeof e.docBaseUrl||isDataScheme(e.docBaseUrl)?null:e.docBaseUrl,g=getFactoryUrlProp(e.cMapUrl),m=!1!==e.cMapPacked,f=getFactoryUrlProp(e.iccUrl),b=getFactoryUrlProp(e.standardFontDataUrl),y=getFactoryUrlProp(e.wasmUrl),v=!0!==e.stopAtErrors,A=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,w="boolean"==typeof e.isOffscreenCanvasSupported?e.isOffscreenCanvasSupported:!t,x="boolean"==typeof e.isImageDecoderSupported?e.isImageDecoderSupported:!t,C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,E="boolean"==typeof e.disableFontFace?e.disableFontFace:t,S=!0===e.fontExtraProperties,T=!0===e.enableXfa,k=e.ownerDocument||globalThis.document,_=!0===e.disableRange,M=!0===e.disableStream,D=!0===e.disableAutoFetch,P=!0===e.pdfBug,I=e.CanvasFactory||(t?NodeCanvasFactory:DOMCanvasFactory),F=e.FilterFactory||(t?NodeFilterFactory:DOMFilterFactory),B=e.BinaryDataFactory||(t?NodeBinaryDataFactory:DOMBinaryDataFactory),L=!0===e.enableHWA,O=!0===e.enableWebGPU?function initGPU(){return At.init()}():Promise.resolve(!1),R=!1!==e.useWasm,N=e.pagesMapper||new PagesMapper,U="boolean"==typeof e.useSystemFonts?e.useSystemFonts:!t&&!E,H="boolean"==typeof e.useWorkerFetch?e.useWorkerFetch:!!(B===DOMBinaryDataFactory&&g&&m&&b&&y&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI)&&isValidFetchUrl(y,document.baseURI));setVerbosityLevel(u);const z={canvasFactory:new I({ownerDocument:k,enableHWA:L}),filterFactory:new F({docId:n,ownerDocument:k}),binaryDataFactory:H?null:new B({cMapUrl:g,standardFontDataUrl:b,wasmUrl:y})};if(!d){d=PDFWorker.create({verbosity:u,port:GlobalWorkerOptions.workerPort});i._worker=d}const G={docId:n,apiVersion:"6.1.200",data:a,password:l,disableAutoFetch:D,rangeChunkSize:c,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:A,disableFontFace:E,ignoreErrors:v,isOffscreenCanvasSupported:w,isImageDecoderSupported:x,canvasMaxAreaInBytes:C,fontExtraProperties:S,useSystemFonts:U,useWasm:R,useWorkerFetch:H,cMapUrl:g,cMapPacked:m,iccUrl:f,standardFontDataUrl:b,wasmUrl:y,hasGPU:!1}},W={ownerDocument:k,pdfBug:P,styleElement:null,enableHWA:L,loadingParams:{disableAutoFetch:D,enableXfa:T}};Promise.all([d.promise,O]).then(function([,e]){if(d.destroyed)throw new Error("Worker was destroyed");G.evaluatorOptions.hasGPU=e;const l=d.messageHandler.sendWithPromise("GetDocRequest",G,a?[a.buffer]:null);let u;if(a);else if(h)u=new PDFDataTransportStream({pdfDataRangeTransport:h,disableRange:_,disableStream:M});else{if(!s)throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");{const e=function getNetworkStream(e){return isValidFetchUrl(e)?PDFFetchStream:t?PDFNodeStream:PDFNetworkStream}(s);u=new e({url:s,httpHeaders:r,withCredentials:o,rangeChunkSize:c,disableRange:_,disableStream:M})}}return l.then(t=>{if(d.destroyed)throw new Error("Worker was destroyed");const e=new MessageHandler(n,t,d.port),s=new WorkerTransport(e,i,u,W,z,N);i._transport=s;if(i.destroyed)throw new Error("Loading aborted");e.send("Ready",null)})}).catch(i._capability.reject).finally(i._setupCapability.resolve);return i}class PDFDocumentLoadingTask{static#Sn=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId="d"+PDFDocumentLoadingTask.#Sn++;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;this._capability.promise.catch(()=>{});try{this._worker?.port&&(this._worker._pendingDestroy=!0);await this._setupCapability.promise;await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}async getData(){return this._transport.getData()}}class PDFDataRangeTransport{#js=Promise.withResolvers();#wa=null;constructor(t,e,i=!1,n=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=n}onDataRange(t,e){this.#wa({type:"range",begin:t,chunk:e})}onDataProgressiveRead(t){this.#js.promise.then(()=>{this.#wa({type:"progressiveRead",chunk:t})})}onDataProgressiveDone(){this.#js.promise.then(()=>{this.#wa({type:"progressiveDone"})})}transportReady(t){this.#wa=t;this.#js.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(t){return this._transport.getAttachmentContent(t)}getAnnotationsByType(t,e){return this._transport.getAnnotationsByType(t,e)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(t){return this._transport.extractPages(t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(t){return this._transport.getRawData(t)}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#xa=!1;#Ca=null;constructor(t,e,i,n,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._intentStates=new Map;this.destroyed=!1;this.recordedBBoxes=null;this.#Ca=n;this.imageCoordinates=null}clone(t){const e=new PDFPageProxy(t,this._pageInfo,this._transport,this.#Ca,this._pdfBug);e.clonedFromIndex=this.clonedFromIndex??this._pageIndex;this._transport.updatePage(e);return e}get pageNumber(){return this._pageIndex+1}set pageNumber(t){this._pageIndex=t-1;this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:n=0,dontFlip:s=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:n,dontFlip:s})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,canvas:e=t.canvas,viewport:i,intent:n="display",annotationMode:s=g.ENABLE,transform:a=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:h=null,pageColors:c=null,printAnnotationStorage:d=null,isEditing:u=!1,recordImages:p=!1,recordOperations:m=!1,operationsFilter:f=null}){this._stats?.time("Overall");const b=this._transport.getRenderingIntent(n,s,d,u),{renderingIntent:y,cacheKey:v}=b;this.#xa=!1;o||=this._transport.getOptionalContentConfig(y);const A=this._intentStates.getOrInsertComputed(v,makeObj);if(A.streamReaderCancelTimeout){clearTimeout(A.streamReaderCancelTimeout);A.streamReaderCancelTimeout=null}const w=!!(y&l);if(!A.displayReadyCapability){A.displayReadyCapability=Promise.withResolvers();A.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(b)}const x=!(!this._pdfBug||!globalThis.StepperManager?.enabled),C=!!e&&!this.recordedBBoxes&&(m||x),E=!!e&&!this.imageCoordinates&&p,complete=t=>{A.renderTasks.delete(k);if(C){const t=k.gfx?.dependencyTracker.take();if(t){k.stepper?.setOperatorBBoxes(t,k.gfx.dependencyTracker.takeDebugMetadata());m&&(this.recordedBBoxes=t)}}E&&!t&&(this.imageCoordinates=k.gfx?.imagesTracker.take());w&&(this.#xa=!0);this.#Ea();if(t){k.capability.reject(t);this._abortOperatorList({intentState:A,reason:t instanceof Error?t:new Error(t)})}else k.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}};let S=null,T=null;(C||E)&&(T=new CanvasBBoxTracker(e,A.operatorList.length));C&&(S=new CanvasDependencyTracker(T,x));const k=new InternalRenderTask({callback:complete,params:{canvas:e,canvasContext:t,dependencyTracker:S??T,imagesTracker:E?new CanvasImagesTracker(e):null,viewport:i,transform:a,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:A.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!w,pdfBug:this._pdfBug,pageColors:c,enableHWA:this._transport.enableHWA,operationsFilter:f});(A.renderTasks||=new Set).add(k);const _=k.task;Promise.all([A.displayReadyCapability.promise,o]).then(([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");k.initializeGraphics({transparency:t,optionalContentConfig:e});k.operatorListChanged()}}).catch(complete);return _}getOperatorList({intent:t="display",annotationMode:e=g.ENABLE,printAnnotationStorage:i=null,isEditing:n=!1}={}){const s=this._transport.getRenderingIntent(t,e,i,n,!0),a=this._intentStates.getOrInsertComputed(s.cacheKey,makeObj);let r;if(!a.opListReadCapability){r=Object.create(null);r.operatorListChanged=function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(r)}};a.opListReadCapability=Promise.withResolvers();(a.renderTasks||=new Set).add(r);a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(s)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#Ca.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}async getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(t=>XfaText.textContent(t));const e=this.streamTextContent(t),i={items:[],styles:Object.create(null),lang:null};for await(const t of e){i.lang??=t.lang;Object.assign(i.styles,t.styles);i.items.push(...t.items)}return i}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#xa=!1;return Promise.all(t)}cleanup(t=!1){this.#xa=!0;const e=this.#Ea();t&&e&&(this._stats&&=new StatTimer);return e}#Ea(){if(!this.#xa||this.destroyed)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#xa=!1;return!0}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,n=t.length;i<n;i++){e.operatorList.fnArray.push(t.fnArray[i]);e.operatorList.argsArray.push(t.argsArray[i])}e.operatorList.lastChunk=t.lastChunk;e.operatorList.separateAnnots=t.separateAnnots;for(const t of e.renderTasks)t.operatorListChanged();t.lastChunk&&this.#Ea()}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:i,modifiedIds:n}){const{map:s,transfer:a}=i,r=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#Ca.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:s,modifiedIds:n},void 0,a).getReader(),o=this._intentStates.get(e);o.streamReader=r;const pump=()=>{r.read().then(({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}},t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#Ea()}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}})};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}t.streamReader.cancel(new AbortException(e.message)).catch(()=>{});t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class PDFWorker{#js=Promise.withResolvers();#Sa=null;#xs=null;#Ta=null;static#ka=0;static#_a=!1;static#Ma=new WeakMap;static{if(t){this.#_a=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{const i=URL.parse(t);if(!i?.origin||"null"===i.origin)return!1;const n=new URL(e,i);return i.origin===n.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;if(e){if(PDFWorker.#Ma.has(e))throw new Error("Cannot use more than one PDFWorker per port.");PDFWorker.#Ma.set(e,this);this.#Da(e)}else this.#Pa()}get promise(){return this.#js.promise}#Ia(){this.#js.resolve();this.#Sa.send("configure",{verbosity:this.verbosity})}get port(){return this.#xs}get messageHandler(){return this.#Sa}#Da(t){this.#xs=t;this.#Sa=new MessageHandler("main","worker",t);this.#Sa.on("ready",()=>{});this.#Ia()}#Pa(){if(PDFWorker.#_a||PDFWorker.#Fa){this.#Ba();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{n.abort();i.destroy();e.terminate();this.destroyed?this.#js.reject(new Error("Worker was destroyed")):this.#Ba()},n=new AbortController;e.addEventListener("error",()=>{this.#Ta||terminateEarly()},{signal:n.signal});i.on("test",t=>{n.abort();if(!this.destroyed&&t){this.#Sa=i;this.#xs=e;this.#Ta=e;this.#Ia()}else terminateEarly()});i.on("ready",t=>{n.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this.#Ba()}});const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this.#Ba()}#Ba(){if(!PDFWorker.#_a){warn("Setting up fake worker.");PDFWorker.#_a=!0}PDFWorker._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this.#js.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this.#xs=e;const i="fake"+PDFWorker.#ka++,n=new MessageHandler(i+"_worker",i,e);t.setup(n,e);this.#Sa=new MessageHandler(i,i+"_worker",e);this.#Ia()}).catch(t=>{this.#js.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0;this.#Ta?.terminate();this.#Ta=null;PDFWorker.#Ma.delete(this.#xs);this.#xs=null;this.#Sa?.destroy();this.#Sa=null}static create(t){const e=this.#Ma.get(t?.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Fa(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Fa)return this.#Fa;return(await import(
|
|
27
|
+
/*webpackIgnore: true*/
|
|
28
|
+
/*@vite-ignore*/
|
|
29
|
+
this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#La=null;#Oa=new Map;#Ra=null;#Na=new Map;#Ua=new Map;#Ha=new Map;#za=null;constructor(t,e,i,n,s,a){this.messageHandler=t;this.loadingTask=e;this.#Ra=i;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement});this.enableHWA=n.enableHWA;this.loadingParams=n.loadingParams;this._params=n;this.canvasFactory=s.canvasFactory;this.filterFactory=s.filterFactory;this.binaryDataFactory=s.binaryDataFactory;this.pagesMapper=a;this.destroyed=!1;this.destroyCapability=null;this.setupMessageHandler()}updatePage(t){const{_pageIndex:e}=t;this.#Na.set(e,t);this.#Ua.set(e,Promise.resolve(t))}#Ga(t,e=null){return this.#Oa.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#ys({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?MathClamp(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=g.ENABLE,i=null,n=!1,s=!1){let a=o,m=Q;switch(t){case"any":a=r;break;case"display":break;case"print":a=l;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=a&l&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case g.DISABLE:a+=d;break;case g.ENABLE:break;case g.ENABLE_FORMS:a+=h;break;case g.ENABLE_STORAGE:a+=c;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(a+=u);s&&(a+=p);const{ids:b,hash:y}=f.modifiedIds;return{renderingIntent:a,cacheKey:[a,m.hash,y].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#za?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Na.values())t.push(e._destroy());this.#Na.clear();this.#Ua.clear();this.#Ha.clear();Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then(()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Oa.clear();this.filterFactory.destroy();TextLayer.cleanup();this.#Ra?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()},this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this.#Ra,"GetReader - no `BasePDFStream` instance available.");this.#La=this.#Ra.getFullReader();this.#La.onProgress=t=>this.#ys(t);e.onPull=()=>{this.#La.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{this.#La.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this.#La.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:n}=this.#La;e&&i&&(this.#La.onProgress=null);return{isStreamingSupported:e,isRangeSupported:i,contentLength:n}});t.on("GetRangeReader",(t,e)=>{assert(this.#Ra,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#Ra.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{i.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}}else e.close()});t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages;this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))});t.on("DocException",t=>{e._capability.reject(wrapReason(t))});t.on("PasswordRequest",t=>{this.#za=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#za.reject(t):this.#za.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#za.reject(t)}return this.#za.promise});t.on("DataLoaded",t=>{this.#ys({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#Na.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)});t.on("commonobj",([e,i,n])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":if("error"in n){const t=n.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const s=new FontInfo(n),a=this._params.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,r=new FontFaceObject(s,a,n.charProcOperatorList,n.extra);this.fontLoader.bind(r).catch(()=>t.sendWithPromise("FontFallback",{id:e})).finally(()=>{r.fontExtraProperties||r.clearData();this.commonObjs.resolve(e,r)});break;case"CopyLocalImage":const{imageRef:o}=n;assert(o,"The imageRef must be defined.");for(const t of this.#Na.values())for(const[,i]of t.objs){if(i?.ref!==o)continue;if(!i.dataLen)return null;const t=structuredClone(i);this.commonObjs.resolve(e,t);return i.dataLen}break;case"FontPath":this.commonObjs.resolve(e,new FontPathInfo(n));break;case"Image":this.commonObjs.resolve(e,n);break;case"Pattern":const l=new PatternInfo(n);this.commonObjs.resolve(e,l.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null});t.on("obj",([t,e,i,n])=>{if(this.destroyed)return;const s=this.#Na.get(e);if(!s.objs.has(t))if(0!==s._intentStates.size)switch(i){case"Image":case"Pattern":s.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${i}`)}else n?.bitmap?.close()});t.on("DocProgress",t=>{this.destroyed||this.#ys(t)});t.on("FetchBinaryData",async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(t)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this.#La?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}extractPages(t){const e={pageInfos:t};let i;const n=globalThis.ImageBitmap;if("function"==typeof n){const e=Array.isArray(t)?t:[t];for(const t of e)t?.image instanceof n&&(i||=[]).push(t.image)}if(this.annotationStorage.size>0){const t=this.annotationStorage.serializable;let{map:n}=t;t.transfer?.length&&(i?i.push(...t.transfer):i=t.transfer);const s=this.pagesMapper.getMapping();if(s){const t=new Map;for(const[e,i]of n){if(void 0!==i?.pageIndex&&i.pageIndex>=0&&i.pageIndex<s.length){const n=s[i.pageIndex]-1;if(n!==i.pageIndex){t.set(e,{...i,pageIndex:n});continue}}t.set(e,i)}n=t}e.annotationStorage=n}return this.messageHandler.sendWithPromise("ExtractPages",e,i).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.pagesMapper.getPageId(t)-1,n=this.#Ua.get(e);if(n)return n;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:i}).then(t=>{if(this.destroyed)throw new Error("Transport destroyed");t.refStr&&this.#Ha.set(t.refStr,i);const n=new PDFPageProxy(e,t,this,this.pagesMapper,this._params.pdfBug);this.#Na.set(e,n);return n});this.#Ua.set(e,s);return s}async getPageIndex(t){if(!isRefProxy(t))throw new Error("Invalid pageIndex request.");const e=await this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}),i=this.pagesMapper.getPageNumber(e+1);if(0===i)throw new Error("GetPageIndex: page has been removed.");return i-1}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(t+1)-1,intent:e})}getFieldObjects(){return this.#Ga("GetFieldObjects")}hasJSActions(){return this.#Ga("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAttachmentContent(t){return this.messageHandler.sendWithPromise("GetAttachmentContent",t)}getAnnotationsByType(t,e){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:t,pageIndexesToSkip:e})}getDocJSActions(){return this.#Ga("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(t+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Ga("GetOptionalContentConfig").then(e=>new OptionalContentConfig(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata";return this.#Oa.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,null).then(t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this.#La?.filename??null,contentLength:this.#La?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(t){return this.messageHandler.sendWithPromise("GetRawData",t)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Na.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Oa.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`,i=this.#Ha.get(e);if(i>=0){const t=this.pagesMapper.getPageNumber(i+1);if(0!==t)return t}return null}}class RenderTask{_internalRenderTask=null;onContinue=null;onError=null;constructor(t){this._internalRenderTask=t}get promise(){return this._internalRenderTask.capability.promise}cancel(t=0){this._internalRenderTask.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this._internalRenderTask.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this._internalRenderTask;return t.form||t.canvas&&e?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class InternalRenderTask{#Wa=null;static#Va=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:n,annotationCanvasMap:s,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null,enableHWA:u=!1,operationsFilter:p=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=n;this.annotationCanvasMap=s;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=c;this.pageColors=d;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvas;this._canvasContext=e.canvas?null:e.canvasContext;this._enableHWA=u;this._dependencyTracker=e.dependencyTracker;this._imagesTracker=e.imagesTracker;this._operationsFilter=p}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Va.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Va.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{viewport:i,transform:n,background:s,dependencyTracker:a,imagesTracker:r}=this.params,o=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new CanvasGraphics(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors,a,r);this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:s});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Wa){window.cancelAnimationFrame(this.#Wa);this.#Wa=null}InternalRenderTask.#Va.delete(this._canvas);t||=new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e);this.callback(t);this.task.onError?.(t)}operatorListChanged(){if(this.graphicsReady){this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length);this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Wa=window.requestAnimationFrame(()=>{this.#Wa=null;this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Va.delete(this._canvas);this.callback()}}}}}const Lt="6.1.200",Ot="6353acefe";class ColorPicker{#ja=null;#$a=null;#Ka;#Xa=null;#qa=!1;#Ya=!1;#r=null;#Qa;#Ja=null;#y=null;static#Za=null;static get _keyboardManager(){return shadow(this,"_keyboardManager",new KeyboardManager([[["Escape"],ColorPicker.prototype._hideDropdownFromKeyboard],[["Space"],ColorPicker.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight"],ColorPicker.prototype._moveToNext],[["ArrowUp","ArrowLeft"],ColorPicker.prototype._moveToPrevious],[["Home"],ColorPicker.prototype._moveToBeginning],[["End"],ColorPicker.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){if(t){this.#Ya=!1;this.#r=t}else this.#Ya=!0;this.#y=t?._uiManager||e;this.#Qa=this.#y._eventBus;this.#Ka=t?.color?.toUpperCase()||this.#y?.highlightColors.values().next().value||"#FFFF98";ColorPicker.#Za||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#ja=document.createElement("button");t.className="colorPicker";t.tabIndex="0";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button");t.ariaHasPopup="true";this.#r&&(t.ariaControls=`${this.#r.id}_colorpicker_dropdown`);const e=this.#y._signal;t.addEventListener("click",this.#tr.bind(this),{signal:e});t.addEventListener("keydown",this.#er.bind(this),{signal:e});const i=this.#$a=document.createElement("span");i.className="swatch";i.ariaHidden="true";i.style.backgroundColor=this.#Ka;t.append(i);return t}renderMainDropdown(){const t=this.#Xa=this.#ir();t.ariaOrientation="horizontal";t.ariaLabelledBy="highlightColorPickerLabel";return t}#ir(){const t=document.createElement("div"),e=this.#y._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.className="dropdown";t.role="listbox";t.ariaMultiSelectable="false";t.ariaOrientation="vertical";t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");this.#r&&(t.id=`${this.#r.id}_colorpicker_dropdown`);for(const[i,n]of this.#y.highlightColors){const s=document.createElement("button");s.tabIndex="0";s.role="option";s.setAttribute("data-color",n);s.title=i;s.setAttribute("data-l10n-id",ColorPicker.#Za[i]);const a=document.createElement("span");s.append(a);a.className="swatch";a.style.backgroundColor=n;s.ariaSelected=n===this.#Ka;s.addEventListener("click",this.#nr.bind(this,n),{signal:e});t.append(s)}t.addEventListener("keydown",this.#er.bind(this),{signal:e});return t}#nr(t,e){e.stopPropagation();this.#Qa.dispatch("switchannotationeditorparams",{source:this,type:y.HIGHLIGHT_COLOR,value:t});this.updateColor(t)}_colorSelectFromKeyboard(t){if(t.target===this.#ja){this.#tr(t);return}const e=t.target.getAttribute("data-color");e&&this.#nr(e,t)}_moveToNext(t){this.#sr?t.target!==this.#ja?t.target.nextSibling?.focus():this.#Xa.firstElementChild?.focus():this.#tr(t)}_moveToPrevious(t){if(t.target!==this.#Xa?.firstElementChild&&t.target!==this.#ja){this.#sr||this.#tr(t);t.target.previousSibling?.focus()}else this.#sr&&this._hideDropdownFromKeyboard()}_moveToBeginning(t){this.#sr?this.#Xa.firstElementChild?.focus():this.#tr(t)}_moveToEnd(t){this.#sr?this.#Xa.lastElementChild?.focus():this.#tr(t)}#er(t){ColorPicker._keyboardManager.exec(this,t)}#tr(t){if(this.#sr){this.hideDropdown();return}this.#qa=0===t.detail;if(!this.#Ja){this.#Ja=new AbortController;window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#y.combinedSignal(this.#Ja)})}this.#ja.ariaExpanded="true";if(this.#Xa){this.#Xa.classList.remove("hidden");return}const e=this.#Xa=this.#ir();this.#ja.append(e)}#p(t){this.#Xa?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#Xa?.classList.add("hidden");this.#ja.ariaExpanded="false";this.#Ja?.abort();this.#Ja=null}get#sr(){return this.#Xa&&!this.#Xa.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#Ya)if(this.#sr){this.hideDropdown();this.#ja.focus({preventScroll:!0,focusVisible:this.#qa})}else this.#r?.unselect()}updateColor(t){this.#$a&&(this.#$a.style.backgroundColor=t);if(!this.#Xa)return;const e=this.#y.highlightColors.values();for(const i of this.#Xa.children)i.ariaSelected=e.next().value===t.toUpperCase()}destroy(){this.#ja?.remove();this.#ja=null;this.#$a=null;this.#Xa?.remove();this.#Xa=null}}class BasicColorPicker{#ar=null;#rr=!1;#r=null;#y=null;static#Za=null;constructor(t){this.#r=t;this.#y=t._uiManager;BasicColorPicker.#Za||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#ar)return this.#ar;const{editorType:t,colorType:e,colorAndOpacityType:i,opacityType:n,color:s,opacity:a}=this.#r,r=this.#rr=FeatureTest.isAlphaColorInputSupported&&void 0!==n,o=this.#ar=document.createElement("input");o.type="color";if(r){o.setAttribute("alpha","");const t=Util.hexNums[Math.round(255*(a??1))];o.value=(s||"#000000")+t}else o.value=s||"#000000";o.className="basicColorPicker";o.tabIndex=0;o.setAttribute("data-l10n-id",BasicColorPicker.#Za[t]);o.addEventListener("input",()=>{if(r){const t=getRGBA(o.value);if(!t)return;const[s,a,r,l]=t,h=Util.makeHexColor(s,a,r);if(void 0!==i)this.#y.updateParams(i,{color:h,opacity:l});else{this.#y.updateParams(e,h);this.#y.updateParams(n,l)}}else this.#y.updateParams(e,o.value)},{signal:this.#y._signal});return o}update(t){if(this.#ar)if(this.#rr){const e=Util.hexNums[Math.round(255*this.#r.opacity)];this.#ar.value=t+e}else this.#ar.value=t}updateOpacity(t){if(!this.#ar||!this.#rr)return;const e=Util.hexNums[Math.round(255*t)];this.#ar.value=this.#r.color+e}destroy(){this.#ar?.remove();this.#ar=null}hideDropdown(){}}function makeColorComp(t){return Math.floor(255*MathClamp(t,0,1)).toString(16).padStart(2,"0")}function scaleAndClamp(t){return 255*MathClamp(t,0,1)}class ColorConverters{static CMYK_G([t,e,i,n]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,i+n),1-Math.min(1,e+n)]}static CMYK_rgb([t,e,i,n]){return[scaleAndClamp(1-Math.min(1,t+n)),scaleAndClamp(1-Math.min(1,i+n)),scaleAndClamp(1-Math.min(1,e+n))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const n=1-t,s=1-e,a=1-i;return["CMYK",n,s,a,Math.min(n,s,a)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");n.setAttribute("version","1.1");if(!i){n.setAttribute("width",`${t}px`);n.setAttribute("height",`${e}px`)}n.setAttribute("preserveAspectRatio","none");n.setAttribute("viewBox",`0 0 ${t} ${e}`);return n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(a,t)}}const Rt=new WeakSet,Nt=60*(new Date).getTimezoneOffset()*1e3;class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case k.LINK:return new LinkAnnotationElement(t);case k.TEXT:return new TextAnnotationElement(t);case k.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case k.POPUP:return new PopupAnnotationElement(t);case k.FREETEXT:return new FreeTextAnnotationElement(t);case k.LINE:return new LineAnnotationElement(t);case k.SQUARE:return new SquareAnnotationElement(t);case k.CIRCLE:return new CircleAnnotationElement(t);case k.POLYLINE:return new PolylineAnnotationElement(t);case k.CARET:return new CaretAnnotationElement(t);case k.INK:return new InkAnnotationElement(t);case k.POLYGON:return new PolygonAnnotationElement(t);case k.HIGHLIGHT:return new HighlightAnnotationElement(t);case k.UNDERLINE:return new UnderlineAnnotationElement(t);case k.SQUIGGLY:return new SquigglyAnnotationElement(t);case k.STRIKEOUT:return new StrikeOutAnnotationElement(t);case k.STAMP:return new StampAnnotationElement(t);case k.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);case k.RICHMEDIA:case k.SCREEN:return new MediaAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#or=null;#lr=!1;#hr=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableComment=t.enableComment;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;this.hasOwnCommentButton=!1;e&&(this.contentElement=this.container=this._createContainer(i));n&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:t,richText:e}){return!(!t?.str&&!e?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){const{data:t}=this,e=this.annotationStorage?.getEditor(t.id);return e?e.getData():t}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){const t=this.annotationStorage?.getEditor(this.data.id);if(t)return t.commentButtonPositionInPage;const{quadPoints:e,inkLists:i,rect:n}=this.data;let s=-1/0,a=-1/0;if(e?.length>=8){for(let t=0;t<e.length;t+=8)if(e[t+1]>a){a=e[t+1];s=e[t+2]}else e[t+1]===a&&(s=Math.max(s,e[t+2]));return[s,a]}if(i?.length>=1){for(const t of i)for(let e=0,i=t.length;e<i;e+=2)if(t[e+1]>a){a=t[e+1];s=t[e]}else t[e+1]===a&&(s=Math.max(s,t[e]));if(s!==1/0)return[s,a]}return n?[n[2],n[3]]:null}_normalizePoint(t){const{page:{view:e},viewport:{rawDims:{pageWidth:i,pageHeight:n,pageX:s,pageY:a}}}=this.parent;t[1]=e[3]-t[1]+e[1];t[0]=100*(t[0]-s)/i;t[1]=100*(t[1]-a)/n;return t}get commentText(){const{data:t}=this;return this.annotationStorage.getRawValue(`${f}${t.id}`)?.popup?.contents||t.contentsObj?.str||""}set commentText(t){const{data:e}=this,i={deleted:!t,contents:t||""};this.annotationStorage.updateEditor(e.id,{popup:i})||this.annotationStorage.setValue(`${f}${e.id}`,{id:e.id,annotationType:e.annotationType,page:this.parent.page,popup:i,popupRef:e.popupRef,modificationDate:new Date});t||this.removePopup()}removePopup(){(this.#hr?.popup||this.popup)?.remove();this.#hr=this.popup=null}updateEdited(t){if(!this.container)return;t.rect&&(this.#or||={rect:this.data.rect.slice(0)});const{rect:e,popup:i}=t;e&&this.#cr(e);let n=this.#hr?.popup||this.popup;if(!n&&i?.text){this._createPopup(i);n=this.#hr.popup}if(n){n.updateEdited(t);if(i?.deleted){n.remove();this.#hr=null;this.popup=null}}}resetEdited(){if(this.#or){this.#cr(this.#or.rect);this.#hr?.popup.resetEdited();this.#or=null}}#cr(t){const{container:{style:e},data:{rect:i,rotation:n},parent:{viewport:{rawDims:{pageWidth:s,pageHeight:a,pageX:r,pageY:o}}}}=this;i?.splice(0,4,...t);e.left=100*(t[0]-r)/s+"%";e.top=100*(a-t[3]+o)/a+"%";if(0===n){e.width=100*(t[2]-t[0])/s+"%";e.height=100*(t[3]-t[1])/a+"%"}else this.setRotation(n)}_createContainer(t){const{data:e,parent:{page:i,viewport:n}}=this,s=document.createElement("section");s.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||this instanceof LinkAnnotationElement||this instanceof MediaAnnotationElement||(s.tabIndex=0);const{style:a}=s;a.zIndex=this.parent.zIndex;this.parent.zIndex+=2;e.alternativeText&&(s.title=e.alternativeText);e.noRotate&&s.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,s);return s}const{width:r,height:o}=this;if(!t&&e.borderStyle.width>0){a.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--total-scale-factor)) / calc(${i}px * var(--total-scale-factor))`;a.borderRadius=e}switch(e.borderStyle.style){case _:a.borderStyle="solid";break;case M:a.borderStyle="dashed";break;case D:warn("Unimplemented border style: beveled");break;case P:warn("Unimplemented border style: inset");break;case I:a.borderBottomStyle="solid"}const n=e.borderColor||null;if(n){this.#lr=!0;a.borderColor=Util.makeHexColor(...n)}else a.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=n.rawDims;a.left=100*(l[0]-d)/h+"%";a.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.width=100*r/h+"%";a.height=100*o/c+"%"}else this.setRotation(p,s);return s}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:n}=this.parent.viewport.rawDims;let{width:s,height:a}=this;t%180!=0&&([s,a]=[a,s]);e.style.width=100*s/i+"%";e.style.height=100*a/n+"%";e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const n=i.detail[t],s=n[0],a=n.slice(1);i.target.style[e]=ColorConverters[`${s}_HTML`](a);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${s}_rgb`](a)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const n of Object.keys(e.detail)){const s=t[n]||i[n];s?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[n,s]of Object.entries(e)){const a=i[n];if(a){a({detail:{[n]:s},target:t});delete e[n]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,n,s]=this.data.rect.map(t=>Math.fround(t));if(8===t.length){const[a,r,o,l]=t.subarray(2,6);if(n===a&&s===r&&e===o&&i===l)return}const{style:r}=this.container;let o;if(this.#lr){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;o=["url('data:image/svg+xml;utf8,",`<svg xmlns="${a}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${t}" stroke-width="${e}">`];this.container.classList.add("hasBorder")}const l=n-e,h=s-i,{svgFactory:c}=this,d=c.createElement("svg");d.classList.add("quadrilateralsContainer");d.setAttribute("width",0);d.setAttribute("height",0);d.role="none";const u=c.createElement("defs");d.append(u);const p=c.createElement("clipPath"),g=`clippath_${this.data.id}`;p.setAttribute("id",g);p.setAttribute("clipPathUnits","objectBoundingBox");u.append(p);for(let i=2,n=t.length;i<n;i+=8){const n=t[i],a=t[i+1],r=t[i+2],d=t[i+3],u=c.createElement("rect"),g=(r-e)/l,m=(s-a)/h,f=(n-r)/l,b=(a-d)/h;u.setAttribute("x",g);u.setAttribute("y",m);u.setAttribute("width",f);u.setAttribute("height",b);p.append(u);o?.push(`<rect vector-effect="non-scaling-stroke" x="${g}" y="${m}" width="${f}" height="${b}"/>`)}if(this.#lr){o.push("</g></svg>')");r.backgroundImage=o.join("")}this.container.append(d);this.container.style.clipPath=`url(#${g})`}_createPopup(t=null){const{data:e}=this;let i,n;if(t){i={str:t.text};n=t.date}else{i=e.contentsObj;n=e.modificationDate}this.#hr=new PopupAnnotationElement({data:{color:e.color,titleObj:e.titleObj,modificationDate:n,contentsObj:i,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#hr||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#hr}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const n=this._fieldObjects[t];if(n)for(const{page:t,id:s,exportValues:a}of n){if(-1===t)continue;if(s===e)continue;const n="string"==typeof a?a:null,r=document.querySelector(`[data-element-id="${s}"]`);!r||Rt.has(r)?i.push({id:s,exportValue:n,domElement:r}):warn(`_getElementsByName - element not allowed: ${s}`)}return i}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,s=n.getAttribute("data-element-id");s!==e&&(Rt.has(n)&&i.push({id:s,exportValue:t,domElement:n}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e,mustEnterInEditMode:!0})})}updateOC(t){if(!this.data.oc||!t)return;t.isVisible(this.data.oc)?this.show():this.hide()}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(...e)}}class EditorAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.editor=t.editor}render(){this.container.className="editorAnnotation";return this.container}createOrUpdatePopup(){const{editor:t}=this;t.hasComment&&this._createPopup(t.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(t){this.editor.comment=t;t||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id);this.container.remove();this.container=null;this.removePopup()}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let n=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);n=!0}else if(t.action){this._bindNamedAction(i,t.action,t.overlaidText);n=!0}else if(t.attachment){this.#dr(i,t.attachmentId,t.attachment,t.overlaidText,t.attachmentDest);n=!0}else if(t.setOCGState){this.#ur(i,t.setOCGState,t.overlaidText);n=!0}else if(t.dest){this._bindLink(i,t.dest,t.overlaidText);n=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);n=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);n=!0}else if(this.isTooltipOnly&&!n){this._bindLink(i,"");n=!0}}this.container.classList.add("linkAnnotation");if(n){this.contentElement=i;this.container.append(i)}return this.container}#pr(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e,i=""){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#pr();i&&(t.title=i)}_bindNamedAction(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};i&&(t.title=i);this.#pr()}#dr(t,e,i,n="",s=null){t.href=this.linkService.getAnchorUrl("");i.description?t.title=i.description:n&&(t.title=n);const openAttachment=async()=>{const t=await this.linkService.getAttachmentContent(e);t&&this.downloadManager?.openOrDownloadData(t,i.filename,s)};t.onclick=()=>{openAttachment();return!1};this.#pr()}#ur(t,e,i=""){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};i&&(t.title=i);this.#pr()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const s=i.get(n);s&&(t[s]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}});return!1})}e.overlaidText&&(t.title=e.overlaidText);t.onclick||(t.onclick=()=>!1);this.#pr()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#pr();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:n,include:s}=e,a=[];if(0!==t.length||0!==n.length){const e=new Set(n);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===s&&a.push(i)}else for(const t of Object.values(this._fieldObjects))a.push(...t);const r=this.annotationStorage,o=[];for(const t of a){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;r.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";r.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(Rt.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}_getKeyModifier(t){return FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,n,s){i.includes("mouse")?t.addEventListener(i,t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})}):t.addEventListener(i,t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:n,value:s(t)}})})}_setEventListeners(t,e,i,n){for(const[s,a]of i)if("Action"===a||this.data.actions?.[a]){"Focus"!==a&&"Blur"!==a||(e||={focused:!1});this._setEventListener(t,e,s,a,n);"Focus"!==a||this.data.actions?.Blur?"Blur"!==a||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,n=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(s*n))||1);r=Math.min(n,roundToOneDecimal(e/s))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(n,roundToOneDecimal(t/s))}a.fontSize=`calc(${r}px * var(--total-scale-factor))`;a.color=Util.makeHexColor(...i);null===this.data.textAlignment||this.data.comb||(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,n){const s=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=i);s.setValue(a.id,{[n]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let s=n.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&s.length>a&&(s=s.slice(0,a));let r=n.formattedValue||this.data.textContent?.join("\n")||null;r&&this.data.comb&&(r=r.replaceAll(/\s+/g,""));const o={userValue:s,formattedValue:r,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=r??s;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type=this.data.password?"password":"text";i.setAttribute("value",r??s);this.data.doNotScroll&&(i.style.overflowX="hidden")}if(this.data.hasOwnCanvas){this.container.classList.add("hasOwnCanvas");t.has(e)&&this.container.classList.add("sandboxModified")}Rt.add(i);this.contentElement=i;i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=0;const{datetimeFormat:l,datetimeType:h,timeStep:c}=this.data,d=!!h&&this.enableScripting;l&&(i.title=l);this._setRequired(i,this.data.required);a&&(i.maxLength=a);i.addEventListener("input",n=>{t.setValue(e,{value:n.target.value});this.setPropertyOnSiblings(i,"value",n.target.value,"value");o.formattedValue=null});i.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null});let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",t=>{if(o.focused)return;const{target:e}=t;if(d){e.type=h;c&&(e.step=c)}if(o.userValue){const t=o.userValue;if(d)if("time"===h){const i=new Date(t),n=[i.getHours(),i.getMinutes(),i.getSeconds()];e.value=n.map(t=>t.toString().padStart(2,"0")).join(":")}else e.value=new Date(t-Nt).toISOString().split("date"===h?"T":".",1)[0];else e.value=t}o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)});i.addEventListener("updatefromsandbox",i=>{this.container.classList.add("sandboxModified");const n={value(i){o.userValue=i.detail.value??"";d||t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:n}=i.detail;o.formattedValue=n;null!=n&&i.target!==document.activeElement&&(i.target.value=n);const s={formattedValue:n};d&&(s.value=n);t.setValue(e,s)},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:n}=i.detail,{target:s}=i;if(0===n){s.removeAttribute("maxLength");return}s.setAttribute("maxLength",n);let a=o.userValue;if(a&&!(a.length<=n)){a=a.slice(0,n);s.value=o.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:s.selectionStart,selEnd:s.selectionEnd}})}}};this._dispatchEventFromSandbox(n,i)});i.addEventListener("keydown",t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:n}=t.target;if(o.lastCommittedValue!==n){o.lastCommittedValue=n;o.userValue=n;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}});const n=blurListener;blurListener=null;i.addEventListener("blur",t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{target:i}=t;let{value:s}=i;if(d){if(s&&"time"===h){const t=s.split(":").map(t=>parseInt(t,10));s=new Date(2e3,0,1,t[0],t[1],t[2]||0).valueOf();i.step=""}else{s.includes("T")||(s=`${s}T00:00`);s=new Date(s).valueOf()}i.type="text"}o.userValue=s;o.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});n(t)});this.data.actions?.Keystroke&&i.addEventListener("beforeinput",t=>{o.lastCommittedValue=null;const{data:i,target:n}=t,{value:s,selectionStart:a,selectionEnd:r}=n;let l=a,h=r;switch(t.inputType){case"deleteWordBackward":{const t=s.substring(0,a).match(/\w*\W*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=s.substring(a).match(/^\W*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":a===r&&(l-=1);break;case"deleteContentForward":a===r&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,change:i||"",willCommit:!1,selStart:l,selEnd:h}})});this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.value)}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;i.classList.add("comb");i.style.setProperty("--comb-width",`calc(${t}px * var(--total-scale-factor))`);const e=this.data.textAlignment;if(1===e||2===e){const setCombOffset=()=>{const t=a-i.value.length;i.style.setProperty("--comb-offset",`${1===e?t>>1:t}`)};setCombOffset();for(const t of["input","blur","resetform","updatefromsandbox"])i.addEventListener(t,setCombOffset)}}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof n){n="Off"!==n;t.setValue(i,{value:n})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const s=document.createElement("input");Rt.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="checkbox";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.setAttribute("exportValue",e.exportValue);s.tabIndex=0;s.addEventListener("change",n=>{const{name:s,checked:a}=n.target;for(const n of this._getElementsByName(s,i)){const i=a&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=i);t.setValue(n.id,{value:i})}t.setValue(i,{value:a})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue});if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",e=>{const n={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let n=t.getValue(i,{value:null!==e.buttonValue&&e.fieldValue===e.buttonValue}).value;if("string"==typeof n){n=n!==e.buttonValue;t.setValue(i,{value:n})}if(n)for(const n of this._getElementsByName(e.fieldName,i))t.setValue(n.id,{value:!1});const s=document.createElement("input");Rt.add(s);s.setAttribute("data-element-id",i);s.disabled=e.readOnly;this._setRequired(s,this.data.required);s.type="radio";s.name=e.fieldName;n&&s.setAttribute("checked",!0);s.tabIndex=0;s.addEventListener("change",e=>{const{name:n,checked:s}=e.target;for(const e of this._getElementsByName(n,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:s})});s.addEventListener("resetform",t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue});if(this.enableScripting&&this.hasJSActions){const n=e.buttonValue;s.addEventListener("updatefromsandbox",e=>{const s={value:e=>{const s=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=s&&n.id===i;n.domElement&&(n.domElement.checked=e);t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(s,e)});this._setEventListeners(s,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],t=>t.target.checked)}this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",t=>{this._dispatchEventFromSandbox({},t)})}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");Rt.add(n);n.setAttribute("data-element-id",e);n.disabled=this.data.readOnly;this._setRequired(n,this.data.required);n.name=this.data.fieldName;n.tabIndex=0;let s=this.data.combo&&this.data.options.length>0;if(!this.data.combo){n.size=this.data.options.length;this.data.multiSelect&&(n.multiple=!0)}n.addEventListener("resetform",t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e});const fixDisplayValue=(t,e)=>{const i=e.replaceAll(" "," ");t.textContent=i;i!==e&&t.setAttribute("display-value",e)};for(const t of this.data.options){const e=document.createElement("option");fixDisplayValue(e,t.displayValue);e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);s=!1}n.append(e)}let a=null;if(s){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);n.prepend(t);a=()=>{t.remove();n.removeEventListener("input",a);a=null};n.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:s}=n;return s?Array.prototype.filter.call(i,t=>t.selected).map(t=>t[e]):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,t=>({displayValue:t.getAttribute("display-value")||t.textContent,exportValue:t.value}))};if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",i=>{const s={value(i){a?.();const s=i.detail.value,o=new Set(Array.isArray(s)?s:[s]);for(const t of n.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){n.multiple=!0},remove(i){const s=n.options,a=i.detail.remove;s[a].selected=!1;n.remove(a);if(s.length>0){-1===Array.prototype.findIndex.call(s,t=>t.selected)&&(s[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},clear(i){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(i){const{index:s,displayValue:a,exportValue:o}=i.detail.insert,l=n.children[s],h=document.createElement("option");fixDisplayValue(h,a);h.value=o;l?l.before(h):n.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},items(i){const{items:s}=i.detail;for(;0!==n.length;)n.remove(0);for(const t of s){const{displayValue:e,exportValue:i}=t,s=document.createElement("option");fixDisplayValue(s,e);s.value=i;n.append(s)}n.options.length>0&&(n.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});r=getValue(!1)},indices(i){const n=new Set(i.detail.indices);for(const t of i.target.options)t.selected=n.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(s,i)});n.addEventListener("input",i=>{const n=getValue(!0),s=getValue(!1);t.setValue(e,{value:n});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,change:s,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})});this._setEventListeners(n,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],t=>t.target.value)}else n.addEventListener("input",function(i){t.setValue(e,{value:getValue(!0)})});this.data.combo&&this._setTextStyle(n);this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i,parent:n}=t,s=!!n._commentManager;super(t,{isRenderable:!s&&AnnotationElement._hasPopupData(e)});this.elements=i;if(s&&AnnotationElement._hasPopupData(e)){const t=this.popup=this.#gr();for(const e of i)e.popup=t}else this.popup=null}#gr(){return new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){const{container:t}=this;t.classList.add("popupAnnotation");t.role="comment";const e=this.popup=this.#gr(),i=[];for(const t of this.elements){t.popup=e;t.container.ariaHasPopup="dialog";i.push(t.data.id);t.addHighlightArea()}this.container.setAttribute("aria-controls",i.map(t=>`${m}${t}`).join(","));return this.container}}class PopupElement{#$=null;#mr=this.#er.bind(this);#fr=this.#br.bind(this);#yr=this.#vr.bind(this);#Ar=this.#wr.bind(this);#xr=null;#_t=null;#Cr=null;#Er=null;#Sr=null;#Tr=null;#kr=null;#_r=!1;#Mr=null;#Dr=null;#F=null;#Pr=null;#Ir=null;#we=null;#Fr=null;#be=null;#Br=null;#or=null;#Lr=!1;#Or=null;#Rr=null;constructor({container:t,color:e,elements:i,titleObj:n,modificationDate:s,contentsObj:a,richText:r,parent:o,rect:l,parentRect:h,open:c,commentManager:d=null}){this.#_t=t;this.#Br=n;this.#Cr=a;this.#be=r;this.#Tr=o;this.#xr=e;this.#Fr=l;this.#kr=h;this.#Sr=i;this.#$=d;this.#Or=i[0];this.#Er=PDFDateString.toDateObject(s);this.trigger=i.flatMap(t=>t.getElementsToTriggerPopup());if(!d){this.#Nr();this.#_t.hidden=!0;c&&this.#wr()}}#Nr(){if(this.#Dr)return;this.#Dr=new AbortController;const{signal:t}=this.#Dr;for(const e of this.trigger){e.addEventListener("click",this.#Ar,{signal:t});e.addEventListener("pointerenter",this.#yr,{signal:t});e.addEventListener("pointerleave",this.#fr,{signal:t});e.classList.add("popupTriggerArea")}for(const e of this.#Sr)e.container?.addEventListener("keydown",this.#mr,{signal:t})}#Ur(){const t=this.#Sr.find(t=>t.hasCommentButton);t&&(this.#Ir=t._normalizePoint(t.commentButtonPosition))}renderCommentButton(){if(this.#Pr){this.#Pr.parentNode||this.#Or.container.after(this.#Pr);return}this.#Ir||this.#Ur();if(!this.#Ir)return;const{signal:t}=this.#Dr=new AbortController,e=this.#Or.hasOwnCommentButton,togglePopup=()=>{this.#$.toggleCommentPopup(this,!0,void 0,!e)},showPopup=()=>{this.#$.toggleCommentPopup(this,!1,!0,!e)},hidePopup=()=>{this.#$.toggleCommentPopup(this,!1,!1)};if(e){this.#Pr=this.#Or.container;for(const e of this.trigger){e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.addEventListener("keydown",this.#mr,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});e.classList.add("popupTriggerArea")}}else{const e=this.#Pr=document.createElement("button");e.className="annotationCommentButton";const i=this.#Or.container;e.style.zIndex=parseInt(i.style.zIndex,10)+1;e.tabIndex=0;e.ariaHasPopup="dialog";e.ariaControls="commentPopup";e.setAttribute("data-l10n-id","pdfjs-show-comment-button");this.#Hr();this.#zr();e.addEventListener("keydown",this.#mr,{signal:t});e.addEventListener("click",togglePopup,{signal:t});e.addEventListener("pointerenter",showPopup,{signal:t});e.addEventListener("pointerleave",hidePopup,{signal:t});i.after(e)}}#zr(){if(this.#Or.extraPopupElement&&!this.#Or.editor)return;this.#Pr||this.renderCommentButton();const[t,e]=this.#Ir,{style:i}=this.#Pr;i.left=`calc(${t}%)`;i.top=`calc(${e}% - var(--comment-button-dim))`}#Hr(){if(!this.#Or.extraPopupElement){this.#Pr||this.renderCommentButton();this.#Pr.style.backgroundColor=this.commentButtonColor||""}}get commentButtonColor(){const{color:t,opacity:e}=this.#Or.commentData;return t?this.#Tr._commentManager.makeCommentColor(t,e):null}focusCommentButton(){setTimeout(()=>{this.#Pr?.focus()},0)}getData(){const{richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}=this.#Or.commentData;return{contentsObj:{str:this.comment},richText:t,color:e,opacity:i,creationDate:n,modificationDate:s}}get elementBeforePopup(){return this.#Pr}get comment(){this.#Rr||=this.#Or.commentText;return this.#Rr}set comment(t){t!==this.comment&&(this.#Or.commentText=this.#Rr=t)}focus(){this.#Or.container?.focus()}get parentBoundingClientRect(){return this.#Or.layer.getBoundingClientRect()}setCommentButtonStates({selected:t,hasPopup:e}){if(this.#Pr){this.#Pr.classList.toggle("selected",t);this.#Pr.ariaExpanded=e}}setSelectedCommentButton(t){this.#Pr.classList.toggle("selected",t)}get commentPopupPosition(){if(this.#we)return this.#we;const{x:t,y:e,height:i}=this.#Pr.getBoundingClientRect(),{x:n,y:s,width:a,height:r}=this.#Or.layer.getBoundingClientRect();return[(t-n)/a,(e+i-s)/r]}set commentPopupPosition(t){this.#we=t}hasDefaultPopupPosition(){return null===this.#we}get commentButtonPosition(){return this.#Ir}get commentButtonWidth(){return this.#Pr.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(t){const[e,i]=this.#we||this.commentButtonPosition.map(t=>t/100),n=this.parentBoundingClientRect,{x:s,y:a,width:r,height:o}=n;this.#$.showDialog(null,this,s+e*r,a+i*o,{...t,parentDimensions:n})}render(){if(this.#Mr)return;const t=this.#Mr=document.createElement("div");t.className="popup";if(this.#xr){const e=t.style.outlineColor=Util.makeHexColor(...this.#xr);t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`}const e=document.createElement("span");e.className="header";if(this.#Br?.str){const t=document.createElement("span");t.className="title";e.append(t);({dir:t.dir,str:t.textContent}=this.#Br)}t.append(e);if(this.#Er){const t=document.createElement("time");t.className="popupDate";t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#Er.valueOf()}));t.dateTime=this.#Er.toISOString();e.append(t)}renderRichText({html:this.#Gr||this.#Cr.str,dir:this.#Cr?.dir,className:"popupContent"},t);this.#_t.append(t)}get#Gr(){const t=this.#be,e=this.#Cr;return!t?.str||e?.str&&e.str!==t.str?null:this.#be.html||null}get#Wr(){return this.#Gr?.attributes?.style?.fontSize||0}get#Vr(){return this.#Gr?.attributes?.style?.color||null}#jr(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},n={style:{color:this.#Vr,fontSize:this.#Wr?`calc(${this.#Wr}px * var(--total-scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:n});return i}#er(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||("Enter"===t.key||"Escape"===t.key&&this.#_r)&&this.#wr()}updateEdited({rect:t,popup:e,deleted:i}){if(this.#$){if(i){this.remove();this.#Rr=null}else if(e)if(e.deleted)this.remove();else{this.#Hr();this.#Rr=e.text}if(t){this.#Ir=null;this.#Ur();this.#zr()}}else if(i||e?.deleted)this.remove();else{this.#Nr();this.#or||={contentsObj:this.#Cr,richText:this.#be};t&&(this.#F=null);if(e&&e.text){this.#be=this.#jr(e.text);this.#Er=PDFDateString.toDateObject(e.date);this.#Cr=null}this.#Mr?.remove();this.#Mr=null}}resetEdited(){if(this.#or){({contentsObj:this.#Cr,richText:this.#be}=this.#or);this.#or=null;this.#Mr?.remove();this.#Mr=null;this.#F=null}}remove(){this.#Dr?.abort();this.#Dr=null;this.#Mr?.remove();this.#Mr=null;this.#Lr=!1;this.#_r=!1;this.#Pr?.remove();this.#Pr=null;if(this.trigger)for(const t of this.trigger)t.classList.remove("popupTriggerArea")}#$r(){if(null!==this.#F)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:i,pageX:n,pageY:s}}}=this.#Tr;let a=!!this.#kr,r=a?this.#kr:this.#Fr;for(const t of this.#Sr)if(!r||null!==Util.intersect(t.data.rect,r)){r=t.data.rect;a=!0;break}const o=Util.normalizeRect([r[0],t[3]-r[1]+t[1],r[2],t[3]-r[3]+t[1]]),l=a?r[2]-r[0]+5:0,h=o[0]+l,c=o[1];this.#F=[100*(h-n)/e,100*(c-s)/i];const{style:d}=this.#_t;d.left=`${this.#F[0]}%`;d.top=`${this.#F[1]}%`}#wr(){if(this.#$)this.#$.toggleCommentPopup(this,!1);else{this.#_r=!this.#_r;if(this.#_r){this.#vr();this.#_t.addEventListener("click",this.#Ar);this.#_t.addEventListener("keydown",this.#mr)}else{this.#br();this.#_t.removeEventListener("click",this.#Ar);this.#_t.removeEventListener("keydown",this.#mr)}}}#vr(){this.#Mr||this.render();if(this.isVisible)this.#_r&&this.#_t.classList.add("focused");else{this.#$r();this.#_t.hidden=!1;this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)+1e3}}#br(){this.#_t.classList.remove("focused");if(!this.#_r&&this.isVisible){this.#_t.hidden=!0;this.#_t.style.zIndex=parseInt(this.#_t.style.zIndex,10)-1e3}}forceHide(){this.#Lr=this.isVisible;this.#Lr&&(this.#_t.hidden=!0)}maybeShow(){if(!this.#$){this.#Nr();if(this.#Lr){this.#Mr||this.#vr();this.#Lr=!1;this.#_t.hidden=!1}}}get isVisible(){return!this.#$&&!1===this.#_t.hidden}}class FreeTextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.textContent=t.data.textContent;this.textPosition=t.data.textPosition;this.annotationEditorType=b.FREETEXT}render(){this.container.classList.add("freeTextAnnotation");if(this.textContent){const t=this.contentElement=document.createElement("div");t.classList.add("annotationTextContent");t.setAttribute("role","comment");for(const e of this.textContent){const i=document.createElement("span");i.textContent=e;t.append(i)}this.container.append(t)}if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this._editOnDoubleClick();return this.container}}class LineAnnotationElement extends AnnotationElement{#Kr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=this.#Kr=this.svgFactory.createElement("svg:line");s.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]);s.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]);s.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]);s.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]);s.setAttribute("stroke-width",t.borderStyle.width||1);s.setAttribute("stroke","transparent");s.setAttribute("fill","transparent");n.append(s);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Kr}addHighlightArea(){this.container.classList.add("highlightArea")}}class SquareAnnotationElement extends AnnotationElement{#Xr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#Xr=this.svgFactory.createElement("svg:rect");a.setAttribute("x",s/2);a.setAttribute("y",s/2);a.setAttribute("width",e-s);a.setAttribute("height",i-s);a.setAttribute("stroke-width",s||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");n.append(a);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Xr}addHighlightArea(){this.container.classList.add("highlightArea")}}class CircleAnnotationElement extends AnnotationElement{#qr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const{data:t,width:e,height:i}=this,n=this.svgFactory.create(e,i,!0),s=t.borderStyle.width,a=this.#qr=this.svgFactory.createElement("svg:ellipse");a.setAttribute("cx",e/2);a.setAttribute("cy",i/2);a.setAttribute("rx",e/2-s/2);a.setAttribute("ry",i/2-s/2);a.setAttribute("stroke-width",s||1);a.setAttribute("stroke","transparent");a.setAttribute("fill","transparent");n.append(a);this.container.append(n);if(!t.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#qr}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolylineAnnotationElement extends AnnotationElement{#Yr=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="polylineAnnotation";this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:i,popupRef:n},width:s,height:a}=this;if(!e)return this.container;const r=this.svgFactory.create(s,a,!0);let o=[];for(let i=0,n=e.length;i<n;i+=2){const n=e[i]-t[0],s=t[3]-e[i+1];o.push(`${n},${s}`)}o=o.join(" ");const l=this.#Yr=this.svgFactory.createElement(this.svgElementName);l.setAttribute("points",o);l.setAttribute("stroke-width",i.width||1);l.setAttribute("stroke","transparent");l.setAttribute("fill","transparent");r.append(l);this.container.append(r);if(!n&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}getElementsToTriggerPopup(){return this.#Yr}addHighlightArea(){this.container.classList.add("highlightArea")}}class PolygonAnnotationElement extends PolylineAnnotationElement{constructor(t){super(t);this.containerClassName="polygonAnnotation";this.svgElementName="svg:polygon"}}class CaretAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("caretAnnotation");if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}return this.container}}class InkAnnotationElement extends AnnotationElement{#Qr=null;#Jr=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="inkAnnotation";this.svgElementName="svg:polyline";this.annotationEditorType="InkHighlight"===this.data.it?b.HIGHLIGHT:b.INK}#Zr(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:i,borderStyle:n,popupRef:s}}=this,{transform:a,width:r,height:o}=this.#Zr(e,t),l=this.svgFactory.create(r,o,!0),h=this.#Qr=this.svgFactory.createElement("svg:g");l.append(h);h.setAttribute("stroke-width",n.width||1);h.setAttribute("stroke-linecap","round");h.setAttribute("stroke-linejoin","round");h.setAttribute("stroke-miterlimit",10);h.setAttribute("stroke","transparent");h.setAttribute("fill","transparent");h.setAttribute("transform",a);for(let t=0,e=i.length;t<e;t++){const e=this.svgFactory.createElement(this.svgElementName);this.#Jr.push(e);e.setAttribute("points",i[t].join(","));h.append(e)}if(!s&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.append(l);this._editOnDoubleClick();return this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:i,rect:n}=t,s=this.#Qr;e>=0&&s.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#Jr.length;t<e;t++)this.#Jr[t].setAttribute("points",i[t].join(","));if(n){const{transform:t,width:e,height:i}=this.#Zr(this.data.rotation,n);s.parentElement.setAttribute("viewBox",`0 0 ${e} ${i}`);s.setAttribute("transform",t)}}getElementsToTriggerPopup(){return this.#Jr}addHighlightArea(){this.container.classList.add("highlightArea")}}class HighlightAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0});this.annotationEditorType=b.HIGHLIGHT}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("highlightAnnotation");this._editOnDoubleClick();if(t){const e=document.createElement("mark");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class UnderlineAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("underlineAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class SquigglyAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("squigglyAnnotation");if(t){const e=document.createElement("u");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StrikeOutAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:t,popupRef:e}}=this;if(!e&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this.container.classList.add("strikeoutAnnotation");if(t){const e=document.createElement("s");e.classList.add("overlaidText");e.textContent=t;this.container.append(e)}return this.container}}class StampAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});this.annotationEditorType=b.STAMP}render(){this.container.classList.add("stampAnnotation");this.container.setAttribute("role","img");if(!this.data.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}this._editOnDoubleClick();return this.container}}class FileAttachmentAnnotationElement extends AnnotationElement{#to=null;constructor(t){super(t,{isRenderable:!0});const{fileId:e,file:i}=this.data;this.filename=i.filename;this.content=i.content;this.fileId=e;this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,attachmentId:this.fileId,...i})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let i;if(e.hasAppearance||0===e.fillAlpha)i=document.createElement("div");else{i=document.createElement("img");i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`;e.fillAlpha&&e.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(100*e.fillAlpha)}%);`)}i.addEventListener("dblclick",this.#eo.bind(this));this.#to=i;const{isMac:n}=FeatureTest.platform;t.addEventListener("keydown",t=>{"Enter"===t.key&&(n?t.metaKey:t.ctrlKey)&&this.#eo()});if(!e.popupRef&&this.hasPopupData){this.hasOwnCommentButton=!0;this._createPopup()}else i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#to}addHighlightArea(){this.container.classList.add("highlightArea")}async#eo(){const{fileId:t,filename:e,content:i}=this,n=await this.linkService.getAttachmentContent(t)||i;n&&this.downloadManager?.openOrDownloadData(n,e)}}class MediaAnnotationElement extends AnnotationElement{#O=new AbortController;#io=null;#no=null;constructor(t){super(t,{isRenderable:!!t.data.richMedia})}render(){this.container.classList.add("mediaAnnotation");const{filename:t}=this.data.richMedia,e=document.createElement("button");e.className="mediaPlayButton";e.type="button";e.title=e.ariaLabel=t;e.addEventListener("click",()=>this.#so(e),{signal:this.#O.signal});this.container.append(e);return this.container}async#so(t){const{fileId:e,filename:i,contentType:n}=this.data.richMedia;t.disabled=!0;let s;try{s=await this.linkService.getAttachmentContent(e)}catch{return}finally{t.disabled=!1}if(!s||!t.isConnected)return;const{signal:a}=this.#O,r=URL.createObjectURL(new Blob([s],{type:n}));this.#io=r;const o=n.startsWith("audio/"),l=document.createElement(o?"audio":"video");this.#no=l;l.className="mediaContent";this._setBackgroundColor(l);l.src=r;l.title=i;l.controls=!0;l.autoplay=!0;l.tabIndex=0;if(o){let t=!1,e=!1;const updateControls=()=>{l.controls=t||e};this.container.addEventListener("pointerenter",()=>{t=!0;updateControls()},{signal:a});this.container.addEventListener("pointerleave",()=>{t=!1;updateControls()},{signal:a});this.container.addEventListener("focusin",()=>{e=!0;updateControls()},{signal:a});this.container.addEventListener("focusout",()=>{e=!1;updateControls()},{signal:a})}l.addEventListener("emptied",()=>this.#ao(r),{once:!0,signal:a});t.replaceWith(l);l.play().catch(()=>{})}#ao(t=this.#io){if(t&&t===this.#io){URL.revokeObjectURL(t);this.#io=null}}destroy(){this.#O.abort();if(this.#no){this.#no.pause();this.#no.removeAttribute("src");this.#no.load();this.#no=null}this.#ao()}}class AnnotationLayer{#ro=null;#oo=null;#W=null;#lo=new Map;#ho=null;#co=null;#Sr=[];#do=!1;zIndex=0;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:n,page:s,viewport:a,structTreeLayer:r,commentManager:o,linkService:l,annotationStorage:h}){this.div=t;this.#ro=e;this.#oo=i;this.#ho=r||null;this.#co=l||null;this.#W=h||new AnnotationStorage;this.page=s;this.viewport=a;this._annotationEditorUIManager=n;this._commentManager=o||null}hasEditableAnnotations(){return this.#lo.size>0}async render(t){const{annotations:e,optionalContentConfig:i}=t,n=this.div;setLayerDimensions(n,this.viewport);const s=new Map,a=[],r={data:null,layer:n,linkService:this.#co,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:this.#W,enableComment:!0===t.enableComment,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===k.POPUP;if(e){const e=s.get(t.id);if(!e)continue;if(!this._commentManager){a.push(t);continue}r.elements=e}else if(t.rect[2]===t.rect[0]||t.rect[3]===t.rect[1])continue;r.data=t;const n=AnnotationElementFactory.create(r);if(!n.isRenderable)continue;if(!e){this.#Sr.push(n);t.popupRef&&s.getOrInsertComputed(t.popupRef,makeArr).push(n)}const o=n.render();t.hidden&&(o.style.visibility="hidden");n.updateOC(i);if(n._isEditable){this.#lo.set(n.data.id,n);this._annotationEditorUIManager?.renderAnnotationElement(n)}}await this.#uo();for(const t of a){const e=r.elements=s.get(t.id);r.data=t;const i=AnnotationElementFactory.create(r);if(!i.isRenderable)continue;const n=i.render();i.contentElement.id=`${m}${t.id}`;t.hidden&&(n.style.visibility="hidden");e.at(-1).container.after(n)}this.#po()}async#uo(){if(0===this.#Sr.length)return;this.div.replaceChildren();const t=[];if(!this.#do){this.#do=!0;for(const{contentElement:e,data:{id:i}}of this.#Sr){const n=e.id=`${m}${i}`;t.push(this.#ho?.getAriaAttributes(n).then(t=>{if(t)for(const[i,n]of t)e.setAttribute(i,n)}))}}this.#Sr.sort(({data:{rect:[t,e,i,n]}},{data:{rect:[s,a,r,o]}})=>{if(t===i&&e===n)return 1;if(s===r&&a===o)return-1;const l=(e+n)/2,h=(a+o)/2;if(l>=o&&h<=e)return-1;if(h>=n&&l<=a)return 1;return(t+i)/2-(s+r)/2});const e=document.createDocumentFragment();for(const t of this.#Sr){e.append(t.container);this._commentManager?(t.extraPopupElement?.popup||t.popup)?.renderCommentButton():t.extraPopupElement&&e.append(t.extraPopupElement.render())}this.div.append(e);await Promise.all(t);if(this.#ro)for(const t of this.#Sr)this.#ro.addPointerInTextLayer(t.contentElement,!1)}async addLinkAnnotations(t){const e={data:null,layer:this.div,linkService:this.#co,svgFactory:new DOMSVGFactory,parent:this};for(const i of t){i.borderStyle||=AnnotationLayer._defaultBorderStyle;e.data=i;const t=AnnotationElementFactory.create(e);if(t.isRenderable){t.render();t.contentElement.id=`${m}${i.id}`;this.#Sr.push(t)}}await this.#uo()}update({viewport:t,optionalContentConfig:e}){const i=this.div;this.viewport=t;setLayerDimensions(i,{rotation:t.rotation});for(const t of this.#Sr)t.updateOC(e);this.#po();i.hidden=!1}destroy(){for(const t of this.#Sr){t.destroy?.();this.#ro?.removePointerInTextLayer(t.contentElement)}this.#Sr.length=0;this.#lo.clear();this.div.replaceChildren()}#po(){if(!this.#oo)return;const t=this.div;for(const[e,i]of this.#oo){const n=t.querySelector(`[data-annotation-id="${e}"]`);if(!n)continue;if(Array.isArray(i))for(const t of i){t.className="annotationContent";t.ariaHidden=!0}else{i.className="annotationContent";i.ariaHidden=!0}const s=[];for(const t of n.children)"CANVAS"===t.nodeName&&s.push(t);for(const t of s)t.remove();const a=Array.isArray(i)?i[0]:i,{firstChild:r}=n;r?r.classList.contains("annotationContent")?r.after(a):r.before(a):n.append(a);if(Array.isArray(i)){let t=a;for(let e=1,n=i.length;e<n;e++){t.after(i[e]);t=i[e]}}this.#oo.delete(e);const o=this.#lo.get(e);if(o)if(o._hasNoCanvas){this._annotationEditorUIManager?.setMissingCanvas(e,n.id,i);o._hasNoCanvas=!1}else o.canvas=i}}refreshCanvases(){this.#po()}getEditableAnnotations(){return this.#lo.values()}getEditableAnnotation(t){return this.#lo.get(t)}addFakeAnnotation(t){const{div:e}=this,{id:i,rotation:n}=t,s=new EditorAnnotationElement({data:{id:i,rect:t.getPDFRect(),rotation:n},editor:t,layer:e,parent:this,enableComment:!!this._commentManager,linkService:this.#co,annotationStorage:this.#W});s.render();s.contentElement.id=`${m}${i}`;s.createOrUpdatePopup();this.#Sr.push(s);return s}removeAnnotation(t){const e=this.#Sr.findIndex(e=>e.data.id===t);if(e<0)return;const[i]=this.#Sr.splice(e,1);this.#ro?.removePointerInTextLayer(i.contentElement)}updateFakeAnnotations(t){if(0!==t.length){for(const e of t)e.updateFakeAnnotationElement(this);this.#uo()}}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}static get _defaultBorderStyle(){return shadow(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:_,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}const Ut=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#go="";#mo=`${this.id}-editor`;#fo=null;#Wr;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter"],t.commitOrRemove],[["Escape"],t.commitOrRemove],[["ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=b.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.color=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#Wr=t.fontSize||FreeTextEditor._defaultFontSize;this.annotationElementId||this._uiManager.a11yAlert(AnnotationEditor._l10nAlert.freetext);this.canAddComment=!1}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case y.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case y.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case y.FREETEXT_SIZE:this.#bo(e);break;case y.FREETEXT_COLOR:this.#Hr(e)}}static get defaultPropertiesToUpdate(){return[[y.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[y.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[y.FREETEXT_SIZE,this.#Wr],[y.FREETEXT_COLOR,this.color]]}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return y.FREETEXT_COLOR}#bo(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--total-scale-factor))`;this.translate(0,-(t-this.#Wr)*this.parentScale);this.#Wr=t;this.#yo()},e=this.#Wr;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color;this._colorPicker?.update(this.color);super.onUpdatedColor()}#Hr(t){const setColor=t=>{this.color=t;this.onUpdatedColor()},e=this.color;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#Wr)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#fo=new AbortController;const t=this._uiManager.combinedSignal(this.#fo);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t});return!0}disableEditMode(){if(!super.disableEditMode())return!1;this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#mo);this._isDraggable=!0;this.#fo?.abort();this.#fo=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing");return!0}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#vo(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Ao(i));e=i}return t.join("\n")}#yo(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display,s=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=n;e.classList.toggle("hidden",s)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#go,e=this.#go=this.#vo().trimEnd();if(t===e)return;const setText=t=>{this.#go=t;if(t){this.#wo();this._uiManager.rebuild(this);this.#yo()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#yo()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy||this.annotationElementId){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#mo);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#Wr}px * var(--total-scale-factor))`;i.color=this.color;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);if(this._isCopy||this.annotationElementId){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:s}=this._initialData;let[a,r]=this.getInitialTranslation();[a,r]=this.pageTranslationToScreen(a,r);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(s[0]-h)/o;u=e+this.height-(s[1]-c)/l;break;case 90:d=t+(s[0]-h)/o;u=e-(s[1]-c)/l;[a,r]=[r,-a];break;case 180:d=t-this.width+(s[0]-h)/o;u=e-(s[1]-c)/l;[a,r]=[-a,-r];break;case 270:d=t+(s[0]-h-this.height*l)/o;u=e+(s[1]-c-this.width*o)/l;[a,r]=[-r,a]}this.setAt(d*i,u*n,a,r)}else this._moveAfterPaste(t,e);this.#wo();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Ao(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Ut,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const n=FreeTextEditor.#xo(e.getData("text")||"").replaceAll(Ut,"\n");if(!n)return;const s=window.getSelection();if(!s.rangeCount)return;this.editorDiv.normalize();s.deleteFromDocument();const a=s.getRangeAt(0);if(!n.includes("\n")){a.insertNode(document.createTextNode(n));this.editorDiv.normalize();s.collapseToStart();return}const{startContainer:r,startOffset:o}=a,l=[],h=[];if(r.nodeType===Node.TEXT_NODE){const t=r.parentElement;h.push(r.nodeValue.slice(o).replaceAll(Ut,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Ao(i)):e=h}l.push(r.nodeValue.slice(0,o).replaceAll(Ut,""))}else if(r===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Ao(i))}}this.#go=`${l.join("\n")}${n}${h.join("\n")}`;this.#wo();const c=new Range;let d=Math.sumPrecise(l.map(t=>t.length));for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d);c.setEnd(t,d);break}d-=e}s.removeAllRanges();s.addRange(c)}#wo(){this.editorDiv.replaceChildren();if(this.#go)for(const t of this.#go.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#Co(){return this.#go.replaceAll(" "," ")}static#xo(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){const t=FreeTextEditor._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,e,i){let n=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:s,rotation:a,id:r,popupRef:o,richText:l,contentsObj:h,creationDate:c,modificationDate:d},textContent:u,textPosition:p,parent:{page:{pageNumber:g}}}=t;if(!u?.length)return null;n=t={annotationType:b.FREETEXT,color:Array.from(i),fontSize:e,value:u.join("\n"),position:p,pageIndex:g-1,rect:s.slice(0),rotation:a,annotationElementId:r,id:r,deleted:!1,popupRef:o,comment:h?.str||null,richText:l,creationDate:c,modificationDate:d}}const s=await super.deserialize(t,e,i);s.#Wr=t.fontSize;s.color=Util.makeHexColor(...t.color);s.#go=FreeTextEditor.#xo(t.value);s._initialData=n;t.comment&&s.setCommentData(t);return s}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:e,fontSize:this.#Wr,value:this.#Co()});this.addComment(i);if(t){i.isCopy=!0;return i}if(this.annotationElementId&&!this.#Eo(i))return null;i.id=this.annotationElementId;return i}#Eo(t){const{value:e,fontSize:i,color:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some((t,e)=>t!==n[e])||t.pageIndex!==s}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(!e)return null;const{style:i}=e;i.fontSize=`calc(${this.#Wr}px * var(--total-scale-factor))`;i.color=this.color;e.replaceChildren();for(const t of this.#go.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#go}});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r]*n;a[r+1]=i+t[r+1]*s}return a}static _rescaleAndSwap(t,e,i,n,s,a){a||=new Float32Array(t.length);for(let r=0,o=t.length;r<o;r+=2){a[r]=e+t[r+1]*n;a[r+1]=i+t[r]*s}return a}static _translate(t,e,i,n){n||=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s+=2){n[s]=e+t[s];n[s+1]=i+t[s+1]}return n}static svgRound(t){return Math.round(1e4*t)}static _normalizePoint(t,e,i,n,s){switch(s){case 90:return[1-e/i,t/n];case 180:return[1-t/i,1-e/n];case 270:return[e/i,1-t/n];default:return[t/i,e/n]}}static createBezierPoints(t,e,i,n,s,a){return[(t+5*i)/6,(e+5*n)/6,(5*i+s)/6,(5*n+a)/6,(i+s)/2,(n+a)/2]}}class FreeDrawOutliner{#So;#To=[];#ko;#_o;#Mo=[];#Do=new Float32Array(18);#Po;#Io;#Fo;#Bo;#Lo;#Oo;#Ro=[];static#No=8;static#Uo=2;static#Ho=FreeDrawOutliner.#No+FreeDrawOutliner.#Uo;constructor({x:t,y:e},i,n,s,a,r=0){this.#So=i;this.#Oo=s*n;this.#_o=a;this.#Do.set([NaN,NaN,NaN,NaN,t,e],6);this.#ko=r;this.#Bo=FreeDrawOutliner.#No*n;this.#Fo=FreeDrawOutliner.#Ho*n;this.#Lo=n;this.#Ro.push(t,e)}isEmpty(){return isNaN(this.#Do[8])}#zo(){const t=this.#Do.subarray(4,6),e=this.#Do.subarray(16,18),[i,n,s,a]=this.#So;return[(this.#Po+(t[0]-e[0])/2-i)/s,(this.#Io+(t[1]-e[1])/2-n)/a,(this.#Po+(e[0]-t[0])/2-i)/s,(this.#Io+(e[1]-t[1])/2-n)/a]}add({x:t,y:e}){this.#Po=t;this.#Io=e;const[i,n,s,a]=this.#So;let[r,o,l,h]=this.#Do.subarray(8,12);const c=t-l,d=e-h,u=Math.hypot(c,d);if(u<this.#Fo)return!1;const p=u-this.#Bo,g=p/u,m=g*c,f=g*d;let b=r,y=o;r=l;o=h;l+=m;h+=f;this.#Ro?.push(t,e);const v=m/p,A=-f/p*this.#Oo,w=v*this.#Oo;this.#Do.set(this.#Do.subarray(2,8),0);this.#Do.set([l+A,h+w],4);this.#Do.set(this.#Do.subarray(14,18),12);this.#Do.set([l-A,h-w],16);if(isNaN(this.#Do[6])){if(0===this.#Mo.length){this.#Do.set([r+A,o+w],2);this.#Mo.push(NaN,NaN,NaN,NaN,(r+A-i)/s,(o+w-n)/a);this.#Do.set([r-A,o-w],14);this.#To.push(NaN,NaN,NaN,NaN,(r-A-i)/s,(o-w-n)/a)}this.#Do.set([b,y,r,o,l,h],6);return!this.isEmpty()}this.#Do.set([b,y,r,o,l,h],6);if(Math.abs(Math.atan2(y-o,b-r)-Math.atan2(f,m))<Math.PI/2){[r,o,l,h]=this.#Do.subarray(2,6);this.#Mo.push(NaN,NaN,NaN,NaN,((r+l)/2-i)/s,((o+h)/2-n)/a);[r,o,b,y]=this.#Do.subarray(14,18);this.#To.push(NaN,NaN,NaN,NaN,((b+r)/2-i)/s,((y+o)/2-n)/a);return!0}[b,y,r,o,l,h]=this.#Do.subarray(0,6);this.#Mo.push(((b+5*r)/6-i)/s,((y+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a);[l,h,r,o,b,y]=this.#Do.subarray(12,18);this.#To.push(((b+5*r)/6-i)/s,((y+5*o)/6-n)/a,((5*r+l)/6-i)/s,((5*o+h)/6-n)/a,((r+l)/2-i)/s,((o+h)/2-n)/a);return!0}toSVGPath(){if(this.isEmpty())return"";const t=this.#Mo,e=this.#To;if(isNaN(this.#Do[6])&&!this.isEmpty())return this.#Go();const i=[];i.push(`M${t[4]} ${t[5]}`);for(let e=6;e<t.length;e+=6)isNaN(t[e])?i.push(`L${t[e+4]} ${t[e+5]}`):i.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);this.#Wo(i);for(let t=e.length-6;t>=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#Vo(i);return i.join(" ")}#Go(){const[t,e,i,n]=this.#So,[s,a,r,o]=this.#zo();return`M${(this.#Do[2]-t)/i} ${(this.#Do[3]-e)/n} L${(this.#Do[4]-t)/i} ${(this.#Do[5]-e)/n} L${s} ${a} L${r} ${o} L${(this.#Do[16]-t)/i} ${(this.#Do[17]-e)/n} L${(this.#Do[14]-t)/i} ${(this.#Do[15]-e)/n} Z`}#Vo(t){const e=this.#To;t.push(`L${e[4]} ${e[5]} Z`)}#Wo(t){const[e,i,n,s]=this.#So,a=this.#Do.subarray(4,6),r=this.#Do.subarray(16,18),[o,l,h,c]=this.#zo();t.push(`L${(a[0]-e)/n} ${(a[1]-i)/s} L${o} ${l} L${h} ${c} L${(r[0]-e)/n} ${(r[1]-i)/s}`)}newFreeDrawOutline(t,e,i,n,s,a){return new FreeDrawOutline(t,e,i,n,s,a)}getOutlines(){const t=this.#Mo,e=this.#To,i=this.#Do,[n,s,a,r]=this.#So,o=new Float32Array((this.#Ro?.length??0)+2);for(let t=0,e=o.length-2;t<e;t+=2){o[t]=(this.#Ro[t]-n)/a;o[t+1]=(this.#Ro[t+1]-s)/r}o[o.length-2]=(this.#Po-n)/a;o[o.length-1]=(this.#Io-s)/r;if(isNaN(i[6])&&!this.isEmpty())return this.#jo(o);const l=new Float32Array(this.#Mo.length+24+this.#To.length);let h=t.length;for(let e=0;e<h;e+=2)if(isNaN(t[e]))l[e]=l[e+1]=NaN;else{l[e]=t[e];l[e+1]=t[e+1]}h=this.#$o(l,h);for(let t=e.length-6;t>=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#Ko(l,h);return this.newFreeDrawOutline(l,o,this.#So,this.#Lo,this.#ko,this.#_o)}#jo(t){const e=this.#Do,[i,n,s,a]=this.#So,[r,o,l,h]=this.#zo(),c=new Float32Array(36);c.set([NaN,NaN,NaN,NaN,(e[2]-i)/s,(e[3]-n)/a,NaN,NaN,NaN,NaN,(e[4]-i)/s,(e[5]-n)/a,NaN,NaN,NaN,NaN,r,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/s,(e[17]-n)/a,NaN,NaN,NaN,NaN,(e[14]-i)/s,(e[15]-n)/a],0);return this.newFreeDrawOutline(c,t,this.#So,this.#Lo,this.#ko,this.#_o)}#Ko(t,e){const i=this.#To;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#$o(t,e){const i=this.#Do.subarray(4,6),n=this.#Do.subarray(16,18),[s,a,r,o]=this.#So,[l,h,c,d]=this.#zo();t.set([NaN,NaN,NaN,NaN,(i[0]-s)/r,(i[1]-a)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(n[0]-s)/r,(n[1]-a)/o],e);return e+24}}class FreeDrawOutline extends Outline{#So;#Xo=new Float32Array(4);#ko;#_o;#Ro;#Lo;#qo;constructor(t,e,i,n,s,a){super();this.#qo=t;this.#Ro=e;this.#So=i;this.#Lo=n;this.#ko=s;this.#_o=a;this.firstPoint=[NaN,NaN];this.lastPoint=[NaN,NaN];this.#Yo(a);const[r,o,l,h]=this.#Xo;for(let e=0,i=t.length;e<i;e+=2){t[e]=(t[e]-r)/l;t[e+1]=(t[e+1]-o)/h}for(let t=0,i=e.length;t<i;t+=2){e[t]=(e[t]-r)/l;e[t+1]=(e[t+1]-o)/h}}toSVGPath(){const t=[`M${this.#qo[4]} ${this.#qo[5]}`];for(let e=6,i=this.#qo.length;e<i;e+=6)isNaN(this.#qo[e])?t.push(`L${this.#qo[e+4]} ${this.#qo[e+5]}`):t.push(`C${this.#qo[e]} ${this.#qo[e+1]} ${this.#qo[e+2]} ${this.#qo[e+3]} ${this.#qo[e+4]} ${this.#qo[e+5]}`);t.push("Z");return t.join(" ")}serialize([t,e,i,n],s){const a=i-t,r=n-e;let o,l;switch(s){case 0:o=Outline._rescale(this.#qo,t,n,a,-r);l=Outline._rescale(this.#Ro,t,n,a,-r);break;case 90:o=Outline._rescaleAndSwap(this.#qo,t,e,a,r);l=Outline._rescaleAndSwap(this.#Ro,t,e,a,r);break;case 180:o=Outline._rescale(this.#qo,i,e,-a,r);l=Outline._rescale(this.#Ro,i,e,-a,r);break;case 270:o=Outline._rescaleAndSwap(this.#qo,i,n,-a,-r);l=Outline._rescaleAndSwap(this.#Ro,i,n,-a,-r)}return{outline:Array.from(o),points:[Array.from(l)]}}#Yo(t){const i=this.#qo;let n=i[4],s=i[5];const a=[n,s,n,s];let r=n,o=s,l=n,h=s;const c=t?Math.max:Math.min,d=new Float32Array(4);for(let t=6,u=i.length;t<u;t+=6){const u=i[t+4],p=i[t+5];if(isNaN(i[t])){Util.pointBoundingBox(u,p,a);if(o>p){r=u;o=p}else o===p&&(r=c(r,u));if(h<p){l=u;h=p}else h===p&&(l=c(l,u))}else{d.set(e,0);Util.bezierBoundingBox(n,s,...i.slice(t,t+6),d);Util.rectBoundingBox(...d,a);if(o>d[1]){r=d[0];o=d[1]}else o===d[1]&&(r=c(r,d[0]));if(h<d[3]){l=d[2];h=d[3]}else h===d[3]&&(l=c(l,d[2]))}n=u;s=p}const u=this.#Xo;u[0]=a[0]-this.#ko;u[1]=a[1]-this.#ko;u[2]=a[2]-a[0]+2*this.#ko;u[3]=a[3]-a[1]+2*this.#ko;this.firstPoint=[r,o];this.lastPoint=[l,h]}get box(){return this.#Xo}newOutliner(t,e,i,n,s,a=0){return new FreeDrawOutliner(t,e,i,n,s,a)}getNewOutline(t,e){const[i,n,s,a]=this.#Xo,[r,o,l,h]=this.#So,c=s*l,d=a*h,u=i*l+r,p=n*h+o,g=this.newOutliner({x:this.#Ro[0]*c+u,y:this.#Ro[1]*d+p},this.#So,this.#Lo,t,this.#_o,e??this.#ko);for(let t=2;t<this.#Ro.length;t+=2)g.add({x:this.#Ro[t]*c+u,y:this.#Ro[t+1]*d+p});return g.getOutlines()}}class HighlightOutliner{#So;#Qo;#Jo;#Zo=[];#tl=[];constructor(t,i=0,n=0,s=!0){const a=e.slice(),r=1e-4;for(const{x:e,y:n,width:s,height:o}of t){const t=Math.floor((e-i)/r)*r,l=Math.ceil((e+s+i)/r)*r,h=Math.floor((n-i)/r)*r,c=Math.ceil((n+o+i)/r)*r,d=[t,h,c,!0],u=[l,h,c,!1];this.#Zo.push(d,u);Util.rectBoundingBox(t,h,l,c,a)}const o=a[2]-a[0]+2*n,l=a[3]-a[1]+2*n,h=a[0]-n,c=a[1]-n;let d=s?-1/0:1/0,u=1/0;const p=this.#Zo.at(s?-1:-2),g=[p[0],p[2]];for(const t of this.#Zo){const[e,i,n,a]=t;if(!a&&s)if(i<u){u=i;d=e}else i===u&&(d=Math.max(d,e));else if(a&&!s)if(i<u){u=i;d=e}else i===u&&(d=Math.min(d,e));t[0]=(e-h)/o;t[1]=(i-c)/l;t[2]=(n-c)/l}this.#So=new Float32Array([h,c,o,l]);this.#Qo=[d,u];this.#Jo=g}getOutlines(){this.#Zo.sort((t,e)=>t[0]-e[0]||t[1]-e[1]||t[2]-e[2]);const t=[];for(const e of this.#Zo)if(e[3]){t.push(...this.#el(e));this.#il(e)}else{this.#nl(e);t.push(...this.#el(e))}return this.#sl(t)}#sl(t){const e=[],i=new Set;for(const i of t){const[t,n,s]=i;e.push([t,n,i],[t,s,i])}e.sort((t,e)=>t[1]-e[1]||t[0]-e[0]);for(let t=0,n=e.length;t<n;t+=2){const n=e[t][2],s=e[t+1][2];n.push(s);s.push(n);i.add(n);i.add(s)}const n=[];let s;for(;i.size>0;){const t=i.values().next().value;let[e,a,r,o,l]=t;i.delete(t);let h=e,c=a;s=[e,r];n.push(s);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,a,r,o,l]=t;if(h!==e){s.push(h,c,e,c===a?a:r);h=e}c=c===a?r:a}s.push(h,c)}return new HighlightOutline(n,this.#So,this.#Qo,this.#Jo)}#al(t){const e=this.#tl;let i=0,n=e.length-1;for(;i<=n;){const s=i+n>>1,a=e[s][0];if(a===t)return s;a<t?i=s+1:n=s-1}return n+1}#il([,t,e]){const i=this.#al(t);this.#tl.splice(i,0,[t,e])}#nl([,t,e]){const i=this.#al(t);for(let n=i;n<this.#tl.length;n++){const[i,s]=this.#tl[n];if(i!==t)break;if(i===t&&s===e){this.#tl.splice(n,1);return}}for(let n=i-1;n>=0;n--){const[i,s]=this.#tl[n];if(i!==t)break;if(i===t&&s===e){this.#tl.splice(n,1);return}}}#el(t){const[e,i,n]=t,s=[[e,i,n]],a=this.#al(n);for(let t=0;t<a;t++){const[i,n]=this.#tl[t];for(let t=0,a=s.length;t<a;t++){const[,r,o]=s[t];if(!(n<=r||o<=i))if(r>=i)if(o>n)s[t][1]=n;else{if(1===a)return[];s.splice(t,1);t--;a--}else{s[t][2]=i;o>n&&s.push([e,n,o])}}}return s}}class HighlightOutline extends Outline{#So;#rl;constructor(t,e,i,n){super();this.#rl=t;this.#So=e;this.firstPoint=i;this.lastPoint=n}toSVGPath(){const t=[];for(const e of this.#rl){let[i,n]=e;t.push(`M${i} ${n}`);for(let s=2;s<e.length;s+=2){const a=e[s],r=e[s+1];if(a===i){t.push(`V${r}`);n=r}else if(r===n){t.push(`H${a}`);i=a}}t.push("Z")}return t.join(" ")}serialize([t,e,i,n],s){const a=[],r=i-t,o=n-e;for(const e of this.#rl){const i=new Array(e.length);for(let s=0;s<e.length;s+=2){i[s]=t+e[s]*r;i[s+1]=n-e[s+1]*o}a.push(i)}return a}get box(){return this.#So}}class FreeHighlightOutliner extends FreeDrawOutliner{newFreeDrawOutline(t,e,i,n,s,a){return new FreeHighlightOutline(t,e,i,n,s,a)}}class FreeHighlightOutline extends FreeDrawOutline{newOutliner(t,e,i,n,s,a=0){return new FreeHighlightOutliner(t,e,i,n,s,a)}}class HighlightEditor extends AnnotationEditor{#ol=null;#ll=0;#hl;#cl=null;#a=null;#dl=null;#ul=null;#pl=0;#gl=null;#ml=null;#T=null;#fl=!1;#Qo=null;#Jo=null;#bl=null;#ye="";#Oo;#yl="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=b.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=HighlightEditor.prototype;return shadow(this,"_keyboardManager",new KeyboardManager([[["ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"});this.color=t.color||HighlightEditor._defaultColor;this.#Oo=t.thickness||HighlightEditor._defaultThickness;this.opacity=t.opacity||HighlightEditor._defaultOpacity;this.#hl=t.boxes||null;this.#yl=t.methodOfCreation||"";this.#ye=t.text||"";this._isDraggable=!1;this.defaultL10nId="pdfjs-editor-highlight-editor";if(t.highlightId>-1){this.#fl=!0;this.#vl(t);this.#Al()}else if(this.#hl){this.#ol=t.anchorNode;this.#ll=t.anchorOffset;this.#ul=t.focusNode;this.#pl=t.focusOffset;this.#wl();this.#Al();this.rotate(this.rotation)}this.annotationElementId||this._uiManager.a11yAlert(AnnotationEditor._l10nAlert.highlight)}get telemetryInitialData(){return{action:"added",type:this.#fl?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this.#Oo,methodOfCreation:this.#yl}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#wl(){const t=new HighlightOutliner(this.#hl,.001);this.#ml=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#ml.box;const e=new HighlightOutliner(this.#hl,.0025,.001,"ltr"===this._uiManager.direction);this.#dl=e.getOutlines();const{firstPoint:i}=this.#ml;this.#Qo=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height];const{lastPoint:n}=this.#dl;this.#Jo=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#vl({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#ml=t;this.#dl=t.getNewOutline(this.#Oo/2+1.5,.0025);if(e>=0){this.#T=e;this.#cl=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#bl=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#dl.box,path:{d:this.#dl.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#T,{bbox:HighlightEditor.#xl(this.#ml.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#bl,{bbox:HighlightEditor.#xl(this.#dl.box,e),path:{d:this.#dl.toSVGPath()}})}const[n,s,a,r]=t.box;switch(this.rotation){case 0:this.x=n;this.y=s;this.width=a;this.height=r;break;case 90:{const[t,e]=this.parentDimensions;this.x=s;this.y=1-n;this.width=a*e/t;this.height=r*t/e;break}case 180:this.x=1-n;this.y=1-s;this.width=a;this.height=r;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-s;this.y=n;this.width=a*e/t;this.height=r*t/e;break}}const{firstPoint:o}=t;this.#Qo=[(o[0]-n)/a,(o[1]-s)/r];const{lastPoint:l}=this.#dl;this.#Jo=[(l[0]-n)/a,(l[1]-s)/r]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case y.HIGHLIGHT_COLOR:HighlightEditor._defaultColor=e;break;case y.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#Jo}get commentButtonPosition(){return this.#Qo}updateParams(t,e){switch(t){case y.HIGHLIGHT_COLOR:this.#Hr(e);break;case y.HIGHLIGHT_THICKNESS:this.#Cl(e)}}static get defaultPropertiesToUpdate(){return[[y.HIGHLIGHT_COLOR,HighlightEditor._defaultColor],[y.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[y.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[y.HIGHLIGHT_THICKNESS,this.#Oo||HighlightEditor._defaultThickness],[y.HIGHLIGHT_FREE,this.#fl]]}onUpdatedColor(){this.parent?.drawLayer.updateProperties(this.#T,{root:{fill:this.color,"fill-opacity":this.opacity}});this.#a?.updateColor(this.color);super.onUpdatedColor()}#Hr(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.opacity=e;this.onUpdatedColor()},e=this.color,i=this.opacity;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)}#Cl(t){const e=this.#Oo,setThickness=t=>{this.#Oo=t;this.#El(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}get toolbarButtons(){if(this._uiManager.highlightColors){return[["colorPicker",this.#a=new ColorPicker({editor:this})]]}return super.toolbarButtons}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#Sl())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#Sl())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#Tl();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Al();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#Tl();else if(t){this.#Al(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#El(t){if(this.#fl){this.#vl({highlightOutlines:this.#ml.getNewOutline(t/2)});this.fixAndSetPosition();this.setDims()}}#Tl(){if(null!==this.#T&&this.parent){this.parent.drawLayer.remove(this.#T);this.#T=null;this.parent.drawLayer.remove(this.#bl);this.#bl=null}}#Al(t=this.parent){if(null===this.#T){({id:this.#T,clipPathId:this.#cl}=t.drawLayer.draw({bbox:this.#ml.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:this.#fl},path:{d:this.#ml.toSVGPath()}},!1,!0));this.#bl=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#fl},bbox:this.#dl.box,path:{d:this.#dl.toSVGPath()}},this.#fl);this.#gl&&(this.#gl.style.clipPath=this.#cl)}}static#xl([t,e,i,n],s){switch(s){case 90:return[1-e-n,t,n,i];case 180:return[1-t-i,1-e-n,i,n];case 270:return[e,1-t-i,n,i]}return[t,e,i,n]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#fl){t=(t-this.rotation+360)%360;i=HighlightEditor.#xl(this.#ml.box,t)}else i=HighlightEditor.#xl([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#T,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#bl,{bbox:HighlightEditor.#xl(this.#dl.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#ye){t.setAttribute("aria-label",this.#ye);t.setAttribute("role","mark")}this.#fl?t.classList.add("free"):this.div.addEventListener("keydown",this.#kl.bind(this),{signal:this._uiManager._signal});const e=this.#gl=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#cl;this.setDims();bindEvents(this,this.#gl,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#bl,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#bl,{rootClass:{hovered:!1}})}#kl(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#_l(!0);break;case 1:case 3:this.#_l(!1)}}#_l(t){if(!this.#ol)return;const e=window.getSelection();t?e.setPosition(this.#ol,this.#ll):e.setPosition(this.#ul,this.#pl)}select(){super.select();this.#bl&&this.parent?.drawLayer.updateProperties(this.#bl,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#bl){this.parent?.drawLayer.updateProperties(this.#bl,{rootClass:{selected:!1}});this.#fl||this.#_l(!1)}}get _mustFixPosition(){return!this.#fl}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#T,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#bl,{rootClass:{hidden:!t}})}}#Sl(){return this.#fl?this.rotation:0}#Ml(){if(this.#fl)return null;const[t,e]=this.pageDimensions,[i,n]=this.pageTranslation,s=this.#hl,a=new Float32Array(8*s.length);let r=0;for(const{x:o,y:l,width:h,height:c}of s){const s=o*t+i,d=(1-l)*e+n;a[r]=a[r+4]=s;a[r+1]=a[r+3]=d;a[r+2]=a[r+6]=s+h*t;a[r+5]=a[r+7]=d-c*e;r+=8}return a}#Dl(t){return this.#ml.serialize(t,this.#Sl())}static startHighlighting(t,e,{target:i,x:n,y:s}){const{x:a,y:r,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#Pl(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:c});window.addEventListener("pointerup",pointerUpCallback,{signal:c});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:c});window.addEventListener("contextmenu",noContextMenu,{signal:c});i.addEventListener("pointermove",this.#Il.bind(this,t),{signal:c});this._freeHighlight=new FreeHighlightOutliner({x:n,y:s},[a,r,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#Il(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#Pl(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let n=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:s,id:a,color:r,opacity:o,popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:b.HIGHLIGHT,color:Array.from(r),opacity:o,quadPoints:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:a,color:r,borderStyle:{rawWidth:o},popupRef:l,richText:h,contentsObj:c,creationDate:d,modificationDate:u},parent:{page:{pageNumber:p}}}=t;n=t={annotationType:b.HIGHLIGHT,color:Array.from(r),thickness:o,inkLists:e,boxes:null,pageIndex:p-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:l,richText:h,comment:c?.str||null,creationDate:d,modificationDate:u}}const{color:s,quadPoints:a,inkLists:r,outlines:o,opacity:l}=t,h=await super.deserialize(t,e,i);h.color=Util.makeHexColor(...s);h.opacity=l||1;r&&(h.#Oo=t.thickness);h._initialData=n;t.comment&&h.setCommentData(t);const[c,d]=h.pageDimensions,[u,p]=h.pageTranslation;if(a){const t=h.#hl=[];for(let e=0;e<a.length;e+=8)t.push({x:(a[e]-u)/c,y:1-(a[e+1]-p)/d,width:(a[e+2]-a[e])/c,height:(a[e+1]-a[e+5])/d});h.#wl();h.#Al();h.rotate(h.rotation)}else if(r||o){h.#fl=!0;const t=(r||o.points)[0],i={x:t[0]-u,y:d-(t[1]-p)},n=new FreeHighlightOutliner(i,[0,0,c,d],1,h.#Oo/2,!0,.001);for(let e=0,s=t.length;e<s;e+=2){i.x=t[e]-u;i.y=d-(t[e+1]-p);n.add(i)}const{id:s,clipPathId:a}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:n.toSVGPath()}},!0,!0);h.#vl({highlightOutlines:n.getOutlines(),highlightId:s,clipPathId:a});h.#Al();h.rotate(h.parentRotation)}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);Object.assign(i,{color:e,opacity:this.opacity,thickness:this.#Oo,quadPoints:this.#Ml(),outlines:this.#Dl(i.rect)});this.addComment(i);if(this.annotationElementId&&!this.#Eo(i))return null;i.id=this.annotationElementId;return i}#Eo(t){const{color:e}=this._initialData;return this.hasEditedComment||t.color.some((t,i)=>t!==e[i])}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#Fl=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))e.startsWith("_")||this.updateProperty(e,i)}updateSVGProperty(t,e){this.#Fl[t]=e}toSVGProperties(){const t=this.#Fl;this.#Fl=Object.create(null);return{root:t}}reset(){this.#Fl=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#Bl=null;#Ll;_colorPicker=null;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#Ol=null;static#Rl=null;static#Nl=null;static _INNER_MARGIN=3;constructor(t){super(t);this.#Ll=t.mustBeCommitted||!1;this._addOutlines(t)}onUpdatedColor(){this._colorPicker?.update(this.color);super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(t){if(t.drawOutlines){this.#Ul(t);this.#Al()}}#Ul({drawOutlines:t,drawId:e,drawingOptions:i}){this.#Bl=t;this._drawingOptions||=i;this.annotationElementId||this._uiManager.a11yAlert(AnnotationEditor._l10nAlert[this.editorType]);if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Hl(t,this.parent);this.#zl(t.box)}#Hl(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[n,s]of Object.entries(e))i.has(n)?Object.assign(t[n],s):t[n]=s;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#Ol.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)t.push([i,e[n]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,n]of this.constructor.typesMap)t.push([i,e[n]]);return t}_updateProperty(t,e,i){const n=this._drawingOptions,s=n[e],setter=i=>{n.updateProperty(e,i);const s=this.#Bl.updateProperty(e,i);s&&this.#zl(s);this.parent?.drawLayer.updateProperties(this._drawId,n.toSVGProperties());t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,e){const i=this.constructor.typesMap.get(this.colorType),n=this.constructor.typesMap.get(this.opacityType),s=this._drawingOptions,a=s[i],r=s[n],setter=(t,e)=>{s.updateProperty(i,t);s.updateProperty(n,e);this.#Bl.updateProperty(i,t);this.#Bl.updateProperty(n,e);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties());this.onUpdatedColor();this.onUpdatedOpacity()};this.addCommands({cmd:setter.bind(this,t,e),undo:setter.bind(this,a,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:y.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Bl.getPathResizingSVGProperties(this.#Gl()),{bbox:this.#Wl()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Bl.getPathResizedSVGProperties(this.#Gl()),{bbox:this.#Wl()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Wl()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#Bl.getPathTranslatedSVGProperties(this.#Gl(),this.parentDimensions),{bbox:this.#Wl()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#Ll){this.#Ll=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#Tl();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Al();this.#zl(this.#Bl.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#Tl()}else if(t){this._uiManager.addShouldRescale(this);this.#Al(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#Tl(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#Al(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Hl(this.#Bl,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Vl([t,e,i,n]){const{parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[e,1-t,i*(a/s),n*(s/a)];case 180:return[1-t,1-e,i,n];case 270:return[1-e,t,i*(a/s),n*(s/a)];default:return[t,e,i,n]}}#Gl(){const{x:t,y:e,width:i,height:n,parentDimensions:[s,a],rotation:r}=this;switch(r){case 90:return[1-e,t,i*(s/a),n*(a/s)];case 180:return[1-t,1-e,i,n];case 270:return[e,1-t,i*(s/a),n*(a/s)];default:return[t,e,i,n]}}#zl(t){[this.x,this.y,this.width,this.height]=this.#Vl(t);if(this.div){this.fixAndSetPosition();this.setDims()}this._onResized()}#Wl(){const{x:t,y:e,width:i,height:n,rotation:s,parentRotation:a,parentDimensions:[r,o]}=this;switch((4*s+a)/90){case 1:return[1-e-n,t,n,i];case 2:return[1-t-i,1-e-n,i,n];case 3:return[e,1-t-i,n,i];case 4:return[t,e-i*(r/o),n*(o/r),i*(r/o)];case 5:return[1-e,t,i*(r/o),n*(o/r)];case 6:return[1-t-n*(o/r),1-e,n*(o/r),i*(r/o)];case 7:return[e-i*(r/o),1-t-n*(o/r),i*(r/o),n*(o/r)];case 8:return[t-i,e-n,i,n];case 9:return[1-e,t-i,n,i];case 10:return[1-t,1-e,i,n];case 11:return[e-n,1-t,n,i];case 12:return[t-n*(o/r),e,n*(o/r),i*(r/o)];case 13:return[1-e-i*(r/o),t-n*(o/r),i*(r/o),n*(o/r)];case 14:return[1-t,1-e-i*(r/o),n*(o/r),i*(r/o)];case 15:return[e,1-t,i*(r/o),n*(o/r)];default:return[t,e,i,n]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Wl()},this.#Bl.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#zl(this.#Bl.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}const i=super.render();i.classList.add("draw");const n=document.createElement("div");i.append(n);n.setAttribute("aria-hidden","true");n.className="internal";this.setDims();this._uiManager.addShouldRescale(this);this.disableEditing();this._isCopy&&this._moveAfterPaste(t,e);return i}static createDrawerInstance(t,e,i,n,s){unreachable("Not implemented")}static startDrawing(t,e,i,n){const{target:s,offsetX:a,offsetY:r,pointerId:o,pointerType:l}=n;if(CurrentPointers.isInitializedAndDifferentPointerType(l))return;const{viewport:{rotation:h}}=t,{width:c,height:d}=s.getBoundingClientRect(),u=DrawingEditor.#Rl=new AbortController,p=t.combinedSignal(u);CurrentPointers.setPointer(l,o);window.addEventListener("pointerup",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._endDraw(t)},{signal:p});window.addEventListener("pointercancel",t=>{CurrentPointers.isSamePointerIdOrRemove(t.pointerId)&&this._currentParent.endDrawingSession()},{signal:p});window.addEventListener("pointerdown",t=>{if(CurrentPointers.isSamePointerType(t.pointerType)){CurrentPointers.initializeAndAddPointerId(t.pointerId);if(DrawingEditor.#Ol.isCancellable()){DrawingEditor.#Ol.removeLastElement();DrawingEditor.#Ol.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}},{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});s.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});s.addEventListener("touchmove",t=>{CurrentPointers.isSameTimeStamp(t.timeStamp)&&stopEvent(t)},{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#Ol)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ol.startNew(a,r,c,d,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#Ol=this.createDrawerInstance(a,r,c,d,h);DrawingEditor.#Nl=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#Nl.toSVGProperties(),DrawingEditor.#Ol.defaultSVGProperties),!0,!1))}}static _drawMove(t){CurrentPointers.isSameTimeStamp(t.timeStamp);if(!DrawingEditor.#Ol)return;const{offsetX:e,offsetY:i,pointerId:n}=t;if(CurrentPointers.isSamePointerId(n))if(CurrentPointers.isUsingMultiplePointers())this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ol.add(e,i));CurrentPointers.setTimeStamp(t.timeStamp);stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#Ol=null;DrawingEditor.#Nl=null;CurrentPointers.clearTimeStamp()}if(DrawingEditor.#Rl){DrawingEditor.#Rl.abort();DrawingEditor.#Rl=null;CurrentPointers.clearPointerIds()}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t?.target===e.div&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#Ol.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#Ol,i=this._currentDrawId,n=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:y.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(y.DRAW_STEP);if(!DrawingEditor.#Ol.isEmpty()){const{pageDimensions:[i,n],scale:s}=e,a=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#Ol.getOutlines(i*s,n*s,s,this._INNER_MARGIN),drawingOptions:DrawingEditor.#Nl,mustBeCommitted:!t});this._cleanup(!0);return a}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,n,s,a){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:n,pageHeight:s,pageX:a,pageY:r}}=e.viewport,o=this.deserializeDraw(a,r,n,s,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#Ul({drawOutlines:o});l.#Al();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[n,s]=this.pageDimensions;return this.#Bl.serialize([e,i,n,s],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getPDFRect()});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Do=new Float64Array(6);#Kr;#jl;#ea;#Oo;#Ro;#$l="";#Kl=0;#rl=new InkDrawOutline;#Xl;#ql;constructor(t,e,i,n,s,a){this.#Xl=i;this.#ql=n;this.#ea=s;this.#Oo=a;[t,e]=this.#Yl(t,e);const r=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#Ro=[t,e];this.#jl=[{line:r,points:this.#Ro}];this.#Do.set(r,0)}updateProperty(t,e){"stroke-width"===t&&(this.#Oo=e)}#Yl(t,e){return Outline._normalizePoint(t,e,this.#Xl,this.#ql,this.#ea)}isEmpty(){return!this.#jl?.length}isCancellable(){return this.#Ro.length<=10}add(t,e){[t,e]=this.#Yl(t,e);const[i,n,s,a]=this.#Do.subarray(2,6),r=t-s,o=e-a;if(Math.hypot(this.#Xl*r,this.#ql*o)<=2)return null;this.#Ro.push(t,e);if(isNaN(i)){this.#Do.set([s,a,t,e],2);this.#Kr.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Do[0])&&this.#Kr.splice(6,6);this.#Do.set([i,n,s,a,t,e],0);this.#Kr.push(...Outline.createBezierPoints(i,n,s,a,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#Ro.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,n,s){this.#Xl=i;this.#ql=n;this.#ea=s;[t,e]=this.#Yl(t,e);const a=this.#Kr=[NaN,NaN,NaN,NaN,t,e];this.#Ro=[t,e];const r=this.#jl.at(-1);if(r){r.line=new Float32Array(r.line);r.points=new Float32Array(r.points)}this.#jl.push({line:a,points:this.#Ro});this.#Do.set(a,0);this.#Kl=0;this.toSVGPath();return null}getLastElement(){return this.#jl.at(-1)}setLastElement(t){if(!this.#jl)return this.#rl.setLastElement(t);this.#jl.push(t);this.#Kr=t.line;this.#Ro=t.points;this.#Kl=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#jl)return this.#rl.removeLastElement();this.#jl.pop();this.#$l="";for(let t=0,e=this.#jl.length;t<e;t++){const{line:e,points:i}=this.#jl[t];this.#Kr=e;this.#Ro=i;this.#Kl=0;this.toSVGPath()}return{path:{d:this.#$l}}}toSVGPath(){const t=Outline.svgRound(this.#Kr[4]),e=Outline.svgRound(this.#Kr[5]);if(2===this.#Ro.length){this.#$l=`${this.#$l} M ${t} ${e} Z`;return this.#$l}if(this.#Ro.length<=6){const i=this.#$l.lastIndexOf("M");this.#$l=`${this.#$l.slice(0,i)} M ${t} ${e}`;this.#Kl=6}if(4===this.#Ro.length){const t=Outline.svgRound(this.#Kr[10]),e=Outline.svgRound(this.#Kr[11]);this.#$l=`${this.#$l} L ${t} ${e}`;this.#Kl=12;return this.#$l}const i=[];if(0===this.#Kl){i.push(`M ${t} ${e}`);this.#Kl=6}for(let t=this.#Kl,e=this.#Kr.length;t<e;t+=6){const[e,n,s,a,r,o]=this.#Kr.slice(t,t+6).map(Outline.svgRound);i.push(`C${e} ${n} ${s} ${a} ${r} ${o}`)}this.#$l+=i.join(" ");this.#Kl=this.#Kr.length;return this.#$l}getOutlines(t,e,i,n){const s=this.#jl.at(-1);s.line=new Float32Array(s.line);s.points=new Float32Array(s.points);this.#rl.build(this.#jl,t,e,i,this.#ea,this.#Oo,n);this.#Do=null;this.#Kr=null;this.#jl=null;this.#$l=null;return this.#rl}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class InkDrawOutline extends Outline{#Xo;#Ql=0;#ko;#jl;#Xl;#ql;#Jl;#ea;#Oo;build(t,e,i,n,s,a,r){this.#Xl=e;this.#ql=i;this.#Jl=n;this.#ea=s;this.#Oo=a;this.#ko=r??0;this.#jl=t;this.#Zl()}get thickness(){return this.#Oo}setLastElement(t){this.#jl.push(t);return{path:{d:this.toSVGPath()}}}removeLastElement(){this.#jl.pop();return{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#jl){t.push(`M${Outline.svgRound(e[4])} ${Outline.svgRound(e[5])}`);if(6!==e.length)if(12===e.length&&isNaN(e[6]))t.push(`L${Outline.svgRound(e[10])} ${Outline.svgRound(e[11])}`);else for(let i=6,n=e.length;i<n;i+=6){const[n,s,a,r,o,l]=e.subarray(i,i+6).map(Outline.svgRound);t.push(`C${n} ${s} ${a} ${r} ${o} ${l}`)}else t.push("Z")}return t.join("")}serialize([t,e,i,n],s){const a=[],r=[],[o,l,h,c]=this.#th();let d,u,p,g,m,f,b,y,v;switch(this.#ea){case 0:v=Outline._rescale;d=t;u=e+n;p=i;g=-n;m=t+o*i;f=e+(1-l-c)*n;b=t+(o+h)*i;y=e+(1-l)*n;break;case 90:v=Outline._rescaleAndSwap;d=t;u=e;p=i;g=n;m=t+l*i;f=e+o*n;b=t+(l+c)*i;y=e+(o+h)*n;break;case 180:v=Outline._rescale;d=t+i;u=e;p=-i;g=n;m=t+(1-o-h)*i;f=e+l*n;b=t+(1-o)*i;y=e+(l+c)*n;break;case 270:v=Outline._rescaleAndSwap;d=t+i;u=e+n;p=-i;g=-n;m=t+(1-l-c)*i;f=e+(1-o-h)*n;b=t+(1-l)*i;y=e+(1-o)*n}for(const{line:t,points:e}of this.#jl){a.push(v(t,d,u,p,g,s?new Array(t.length):null));r.push(v(e,d,u,p,g,s?new Array(e.length):null))}return{lines:a,points:r,rect:[m,f,b,y]}}static deserialize(t,e,i,n,s,{paths:{lines:a,points:r},rotation:o,thickness:l}){const h=[];let c,d,u,p,g;switch(o){case 0:g=Outline._rescale;c=-t/i;d=e/n+1;u=1/i;p=-1/n;break;case 90:g=Outline._rescaleAndSwap;c=-e/n;d=-t/i;u=1/n;p=1/i;break;case 180:g=Outline._rescale;c=t/i+1;d=-e/n;u=-1/i;p=1/n;break;case 270:g=Outline._rescaleAndSwap;c=e/n+1;d=t/i+1;u=-1/n;p=-1/i}if(!a){a=[];for(const t of r){const e=t.length;if(2===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1]]));continue}if(4===e){a.push(new Float32Array([NaN,NaN,NaN,NaN,t[0],t[1],NaN,NaN,NaN,NaN,t[2],t[3]]));continue}const i=new Float32Array(3*(e-2));a.push(i);let[n,s,r,o]=t.subarray(0,4);i.set([NaN,NaN,NaN,NaN,n,s],0);for(let a=4;a<e;a+=2){const e=t[a],l=t[a+1];i.set(Outline.createBezierPoints(n,s,r,o,e,l),3*(a-2));[n,s,r,o]=[r,o,e,l]}}}for(let t=0,e=a.length;t<e;t++)h.push({line:g(a[t].map(t=>t??NaN),c,d,u,p),points:g(r[t].map(t=>t??NaN),c,d,u,p)});const m=new this.prototype.constructor;m.build(h,i,n,1,o,l,s);return m}#eh(t=this.#Oo){const e=this.#ko+t/2*this.#Jl;return this.#ea%180==0?[e/this.#Xl,e/this.#ql]:[e/this.#ql,e/this.#Xl]}#th(){const[t,e,i,n]=this.#Xo,[s,a]=this.#eh(0);return[t+s,e+a,i-2*s,n-2*a]}#Zl(){const t=this.#Xo=i.slice();for(const{line:e}of this.#jl){if(e.length<=12){for(let i=4,n=e.length;i<n;i+=6)Util.pointBoundingBox(e[i],e[i+1],t);continue}let i=e[4],n=e[5];for(let s=6,a=e.length;s<a;s+=6){const[a,r,o,l,h,c]=e.subarray(s,s+6);Util.bezierBoundingBox(i,n,a,r,o,l,h,c,t);i=h;n=c}}const[e,n]=this.#eh();t[0]=MathClamp(t[0]-e,0,1);t[1]=MathClamp(t[1]-n,0,1);t[2]=MathClamp(t[2]+e,0,1);t[3]=MathClamp(t[3]+n,0,1);t[2]-=t[0];t[3]-=t[1]}get box(){return this.#Xo}updateProperty(t,e){return"stroke-width"===t?this.#Cl(e):null}#Cl(t){const[e,i]=this.#eh();this.#Oo=t;const[n,s]=this.#eh(),[a,r]=[n-e,s-i],o=this.#Xo;o[0]-=a;o[1]-=r;o[2]+=2*a;o[3]+=2*r;return o}updateParentDimensions([t,e],i){const[n,s]=this.#eh();this.#Xl=t;this.#ql=e;this.#Jl=i;const[a,r]=this.#eh(),o=a-n,l=r-s,h=this.#Xo;h[0]-=o;h[1]-=l;h[2]+=2*o;h[3]+=2*l;return h}updateRotation(t){this.#Ql=t;return{path:{transform:this.rotationTransform}}}get viewBox(){return this.#Xo.map(Outline.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#Xo;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#Xo;let i=0,n=0,s=0,a=0,r=0,o=0;switch(this.#Ql){case 90:n=e/t;s=-t/e;r=t;break;case 180:i=-1;a=-1;r=t;o=e;break;case 270:n=-e/t;s=t/e;o=e;break;default:return""}return`matrix(${i} ${n} ${s} ${a} ${Outline.svgRound(r)} ${Outline.svgRound(o)})`}getPathResizingSVGProperties([t,e,i,n]){const[s,a]=this.#eh(),[r,o,l,h]=this.#Xo;if(Math.abs(l-s)<=Outline.PRECISION||Math.abs(h-a)<=Outline.PRECISION){const s=t+i/2-(r+l/2),a=e+n/2-(o+h/2);return{path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:`${this.rotationTransform} translate(${s} ${a})`}}}const c=(i-2*s)/(l-2*s),d=(n-2*a)/(h-2*a),u=l/i,p=h/n;return{path:{"transform-origin":`${Outline.svgRound(r)} ${Outline.svgRound(o)}`,transform:`${this.rotationTransform} scale(${u} ${p}) translate(${Outline.svgRound(s)} ${Outline.svgRound(a)}) scale(${c} ${d}) translate(${Outline.svgRound(-s)} ${Outline.svgRound(-a)})`}}}getPathResizedSVGProperties([t,e,i,n]){const[s,a]=this.#eh(),r=this.#Xo,[o,l,h,c]=r;r[0]=t;r[1]=e;r[2]=i;r[3]=n;if(Math.abs(h-s)<=Outline.PRECISION||Math.abs(c-a)<=Outline.PRECISION){const s=t+i/2-(o+h/2),a=e+n/2-(l+c/2);for(const{line:t,points:e}of this.#jl){Outline._translate(t,s,a,t);Outline._translate(e,s,a,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(i-2*s)/(h-2*s),u=(n-2*a)/(c-2*a),p=-d*(o+s)+t+s,g=-u*(l+a)+e+a;if(1!==d||1!==u||0!==p||0!==g)for(const{line:t,points:e}of this.#jl){Outline._rescale(t,p,g,d,u,t);Outline._rescale(e,p,g,d,u,e)}return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],i){const[n,s]=i,a=this.#Xo,r=t-a[0],o=e-a[1];if(this.#Xl===n&&this.#ql===s)for(const{line:t,points:e}of this.#jl){Outline._translate(t,r,o,t);Outline._translate(e,r,o,e)}else{const t=this.#Xl/n,e=this.#ql/s;this.#Xl=n;this.#ql=s;for(const{line:i,points:n}of this.#jl){Outline._rescale(i,r,o,t,e,i);Outline._rescale(n,r,o,t,e,n)}a[2]*=t;a[3]*=e}a[0]=t;a[1]=e;return{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t)} ${Outline.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#Xo;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Outline.svgRound(t[0])} ${Outline.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class InkDrawingOptions extends DrawingOptions{constructor(t){super();this._viewParameters=t;super.updateProperties({fill:"none",stroke:AnnotationEditor._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){if("stroke-width"===t){e??=this["stroke-width"];e*=this._viewParameters.realScale}super.updateSVGProperty(t,e)}clone(){const t=new InkDrawingOptions(this._viewParameters);t.updateAll(this);return t}}class InkEditor extends DrawingEditor{static _type="ink";static _editorType=b.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"});this._willKeepAspectRatio=!0;this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new InkDrawingOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!0}static get typesMap(){return shadow(this,"typesMap",new Map([[y.INK_THICKNESS,"stroke-width"],[y.INK_COLOR,"stroke"],[y.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,i,n,s){return new InkDrawOutliner(t,e,i,n,s,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,i,n,s,a){return InkDrawOutline.deserialize(t,e,i,n,s,a)}static async deserialize(t,e,i){let n=null;if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:s,id:a,color:r,opacity:o,borderStyle:{rawWidth:l},popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},parent:{page:{pageNumber:g}}}=t;n=t={annotationType:b.INK,color:Array.from(r),thickness:l,opacity:o,paths:{points:e},boxes:null,pageIndex:g-1,rect:i.slice(0),rotation:s,annotationElementId:a,id:a,deleted:!1,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const s=await super.deserialize(t,e,i);s._initialData=n;t.comment&&s.setCommentData(t);return s}get toolbarButtons(){this._colorPicker||=new BasicColorPicker(this);return[["colorPicker",this._colorPicker]]}get colorType(){return y.INK_COLOR}get colorAndOpacityType(){return y.INK_COLOR_AND_OPACITY}get opacityType(){return y.INK_OPACITY}updateParams(t,e){t!==y.INK_COLOR_AND_OPACITY?super.updateParams(t,e):this._updateColorAndOpacity(e.color,e.opacity)}static updateDefaultParams(t,e){if(t!==y.INK_COLOR_AND_OPACITY)super.updateDefaultParams(t,e);else{super.updateDefaultParams(y.INK_COLOR,e.color);super.updateDefaultParams(y.INK_OPACITY,e.opacity)}}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:i}=this;e.updateSVGProperty("stroke-width");i.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;if(t){super.onScaleChangingWhenDrawing();this._defaultDrawingOptions.updateSVGProperty("stroke-width");t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}createDrawingOptions({color:t,thickness:e,opacity:i}){this._drawingOptions=InkEditor.getDefaultDrawingOptions({stroke:Util.makeHexColor(...t),"stroke-width":e,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":s,"stroke-width":a}}=this,r=Object.assign(super.serialize(t),{color:AnnotationEditor._colorManager.convert(n),opacity:s,thickness:a,paths:{lines:e,points:i}});this.addComment(r);if(t){r.isCopy=!0;return r}if(this.annotationElementId&&!this.#Eo(r))return null;r.id=this.annotationElementId;return r}#Eo(t){const{color:e,thickness:i,opacity:n,pageIndex:s}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((t,i)=>t!==e[i])||t.thickness!==i||t.opacity!==n||t.pageIndex!==s}renderAnnotationElement(t){if(this.deleted){t.hide();return null}const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e,popup:this.comment});return null}}class ContourDrawOutline extends InkDrawOutline{toSVGPath(){let t=super.toSVGPath();t.endsWith("Z")||(t+="Z");return t}}class SignatureExtractor{static#ih={maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16};static#nh(t,e,i,n){n-=e;return 0===(i-=t)?n>0?0:4:1===i?n+6:2-n}static#sh=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#ah(t,e,i,n,s,a,r){const o=this.#nh(i,n,s,a);for(let s=0;s<8;s++){const a=(-s+o-r+16)%8;if(0!==t[(i+this.#sh[2*a])*e+(n+this.#sh[2*a+1])])return a}return-1}static#rh(t,e,i,n,s,a,r){const o=this.#nh(i,n,s,a);for(let s=0;s<8;s++){const a=(s+o+r+16)%8;if(0!==t[(i+this.#sh[2*a])*e+(n+this.#sh[2*a+1])])return a}return-1}static#oh(t,e,i,n){const s=t.length,a=new Int32Array(s);for(let e=0;e<s;e++)a[e]=t[e]<=n?1:0;for(let t=1;t<i-1;t++)a[t*e]=a[t*e+e-1]=0;for(let t=0;t<e;t++)a[t]=a[e*i-1-t]=0;let r,o=1;const l=[];for(let t=1;t<i-1;t++){r=1;for(let i=1;i<e-1;i++){const n=t*e+i,s=a[n];if(0===s)continue;let h=t,c=i;if(1===s&&0===a[n-1]){o+=1;c-=1}else{if(!(s>=1&&0===a[n+1])){1!==s&&(r=Math.abs(s));continue}o+=1;c+=1;s>1&&(r=s)}const d=[i,t],u=c===i+1,p={isHole:u,points:d,id:o,parent:0};l.push(p);let g;for(const t of l)if(t.id===r){g=t;break}g?g.isHole?p.parent=u?g.parent:r:p.parent=u?r:g.parent:p.parent=u?r:0;const m=this.#ah(a,e,t,i,h,c,0);if(-1===m){a[n]=-o;1!==a[n]&&(r=Math.abs(a[n]));continue}let f=this.#sh[2*m],b=this.#sh[2*m+1];const y=t+f,v=i+b;h=y;c=v;let A=t,w=i;for(;;){const s=this.#rh(a,e,A,w,h,c,1);f=this.#sh[2*s];b=this.#sh[2*s+1];const l=A+f,u=w+b;d.push(u,l);const p=A*e+w;0===a[p+1]?a[p]=-o:1===a[p]&&(a[p]=o);if(l===t&&u===i&&A===y&&w===v){1!==a[n]&&(r=Math.abs(a[n]));break}h=A;c=w;A=l;w=u}}}return l}static#lh(t,e,i,n){if(i-e<=4){for(let s=e;s<i-2;s+=2)n.push(t[s],t[s+1]);return}const s=t[e],a=t[e+1],r=t[i-4]-s,o=t[i-3]-a,l=Math.hypot(r,o),h=r/l,c=o/l,d=h*a-c*s,u=o/r,p=1/l,g=Math.atan(u),m=Math.cos(g),f=Math.sin(g),b=p*(Math.abs(m)+Math.abs(f)),y=p*(1-b+b**2),v=Math.max(Math.atan(Math.abs(f+m)*y),Math.atan(Math.abs(f-m)*y));let A=0,w=e;for(let n=e+2;n<i-2;n+=2){const e=Math.abs(d-h*t[n+1]+c*t[n]);if(e>A){w=n;A=e}}if(A>(l*v)**2){this.#lh(t,e,w+2,n);this.#lh(t,w,i,n)}else n.push(s,a)}static#hh(t){const e=[],i=t.length;this.#lh(t,0,i,e);e.push(t[i-2],t[i-1]);return e.length<=4?null:e}static#ch(t,e,i,n,s,a){const r=new Float32Array(a**2),o=-2*n**2,l=a>>1;for(let t=0;t<a;t++){const e=(t-l)**2;for(let i=0;i<a;i++)r[t*a+i]=Math.exp((e+(i-l)**2)/o)}const h=new Float32Array(256),c=-2*s**2;for(let t=0;t<256;t++)h[t]=Math.exp(t**2/c);const d=t.length,u=new Uint8Array(d),p=new Uint32Array(256);for(let n=0;n<i;n++)for(let s=0;s<e;s++){const o=n*e+s,c=t[o];let d=0,g=0;for(let o=0;o<a;o++){const u=n+o-l;if(!(u<0||u>=i))for(let i=0;i<a;i++){const n=s+i-l;if(n<0||n>=e)continue;const p=t[u*e+n],m=r[o*a+i]*h[Math.abs(p-c)];d+=p*m;g+=m}}p[u[o]=Math.round(d/g)]++}return[u,p]}static#dh(t){const e=new Uint32Array(256);for(const i of t)e[i]++;return e}static#uh(t){const e=t.length,i=new Uint8ClampedArray(e>>2);let n=-1/0,s=1/0;for(let e=0,a=i.length;e<a;e++){const a=i[e]=t[e<<2];n=Math.max(n,a);s=Math.min(s,a)}const a=255/(n-s);for(let t=0,e=i.length;t<e;t++)i[t]=(i[t]-s)*a;return i}static#ph(t){let e,i=-1/0,n=-1/0;const s=t.findIndex(t=>0!==t);let a=s,r=s;for(e=s;e<256;e++){const s=t[e];if(s>i){if(e-a>n){n=e-a;r=e-1}i=s;a=e}}for(e=r-1;e>=0&&!(t[e]>t[e+1]);e--);return e}static#gh(t){const e=t,{width:i,height:n}=t,{maxDim:s}=this.#ih;let a=i,r=n;if(i>s||n>s){let o=i,l=n,h=Math.log2(Math.max(i,n)/s);const c=Math.floor(h);h=h===c?c-1:c;for(let i=0;i<h;i++){a=Math.ceil(o/2);r=Math.ceil(l/2);const i=new OffscreenCanvas(a,r);i.getContext("2d").drawImage(t,0,0,o,l,0,0,a,r);o=a;l=r;t!==e&&t.close();t=i.transferToImageBitmap()}const d=Math.min(s/a,s/r);a=Math.round(a*d);r=Math.round(r*d)}const o=new OffscreenCanvas(a,r).getContext("2d",{willReadFrequently:!0});o.fillStyle="white";o.fillRect(0,0,a,r);o.filter="grayscale(1)";o.drawImage(t,0,0,t.width,t.height,0,0,a,r);const l=o.getImageData(0,0,a,r).data;return[this.#uh(l),a,r]}static extractContoursFromText(t,{fontFamily:e,fontStyle:i,fontWeight:n},s,a,r,o){let l=new OffscreenCanvas(1,1),h=l.getContext("2d",{alpha:!1});const c=h.font=`${i} ${n} 200px ${e}`,{actualBoundingBoxLeft:d,actualBoundingBoxRight:u,actualBoundingBoxAscent:p,actualBoundingBoxDescent:g,fontBoundingBoxAscent:m,fontBoundingBoxDescent:f,width:b}=h.measureText(t),y=1.5,v=Math.ceil(Math.max(Math.abs(d)+Math.abs(u)||0,b)*y),A=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||200,Math.abs(m)+Math.abs(f)||200)*y);l=new OffscreenCanvas(v,A);h=l.getContext("2d",{alpha:!0,willReadFrequently:!0});h.font=c;h.filter="grayscale(1)";h.fillStyle="white";h.fillRect(0,0,v,A);h.fillStyle="black";h.fillText(t,.5*v/2,1.5*A/2);const w=this.#uh(h.getImageData(0,0,v,A).data),x=this.#dh(w),C=this.#ph(x),E=this.#oh(w,v,A,C);return this.processDrawnLines({lines:{curves:E,width:v,height:A},pageWidth:s,pageHeight:a,rotation:r,innerMargin:o,mustSmooth:!0,areContours:!0})}static process(t,e,i,n,s){const[a,r,o]=this.#gh(t),[l,h]=this.#ch(a,r,o,Math.hypot(r,o)*this.#ih.sigmaSFactor,this.#ih.sigmaR,this.#ih.kernelSize),c=this.#ph(h),d=this.#oh(l,r,o,c);return this.processDrawnLines({lines:{curves:d,width:r,height:o},pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:s,mustSmooth:a,areContours:r}){n%180!=0&&([e,i]=[i,e]);const{curves:o,width:l,height:h}=t,c=t.thickness??0,d=[],u=Math.min(e/l,i/h),p=u/e,g=u/i,m=[];for(const{points:t}of o){const e=a?this.#hh(t):t;if(!e)continue;m.push(e);const i=e.length,n=new Float32Array(i),s=new Float32Array(3*(2===i?2:i-2));d.push({line:s,points:n});if(2===i){n[0]=e[0]*p;n[1]=e[1]*g;s.set([NaN,NaN,NaN,NaN,n[0],n[1]],0);continue}let[r,o,l,h]=e;r*=p;o*=g;l*=p;h*=g;n.set([r,o,l,h],0);s.set([NaN,NaN,NaN,NaN,r,o],0);for(let t=4;t<i;t+=2){const i=n[t]=e[t]*p,a=n[t+1]=e[t+1]*g;s.set(Outline.createBezierPoints(r,o,l,h,i,a),3*(t-2));[r,o,l,h]=[l,h,i,a]}}if(0===d.length)return null;const f=r?new ContourDrawOutline:new InkDrawOutline;f.build(d,e,i,1,n,r?0:c,s);return{outline:f,newCurves:m,areContours:r,thickness:c,width:l,height:h}}static async compressSignature({outlines:t,areContours:e,thickness:i,width:n,height:s}){let a,r=1/0,o=-1/0,l=0;for(const e of t){l+=e.length;for(let t=2,i=e.length;t<i;t++){const i=e[t]-e[t-2];r=Math.min(r,i);o=Math.max(o,i)}}a=r>=-128&&o<=127?Int8Array:r>=-32768&&o<=32767?Int16Array:Int32Array;const h=t.length,c=8+3*h,d=new Uint32Array(c);let u=0;d[u++]=c*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*a.BYTES_PER_ELEMENT;d[u++]=0;d[u++]=n;d[u++]=s;d[u++]=e?0:1;d[u++]=Math.max(0,Math.floor(i??0));d[u++]=h;d[u++]=a.BYTES_PER_ELEMENT;for(const e of t){d[u++]=e.length-2;d[u++]=e[0];d[u++]=e[1]}const p=new CompressionStream("deflate-raw"),g=p.writable.getWriter();await g.ready;g.write(d);const m=a.prototype.constructor;for(const e of t){const t=new m(e.length-2);for(let i=2,n=e.length;i<n;i++)t[i-2]=e[i]-e[i-2];g.write(t)}g.close();return(await new Response(p.readable).bytes()).toBase64()}static async decompressSignature(t){try{const e=Uint8Array.fromBase64(t),{readable:i,writable:n}=new DecompressionStream("deflate-raw"),s=n.getWriter();await s.ready;s.write(e).then(async()=>{await s.ready;await s.close()}).catch(()=>{});let a=null,r=0;for await(const t of i){a||=new Uint8Array(new Uint32Array(t.buffer,0,4)[0]);a.set(t,r);r+=t.length}const o=new Uint32Array(a.buffer,0,a.length>>2),l=o[1];if(0!==l)throw new Error(`Invalid version: ${l}`);const h=o[2],c=o[3],d=0===o[4],u=o[5],p=o[6],g=o[7],m=[],f=(8+3*p)*Uint32Array.BYTES_PER_ELEMENT;let b;switch(g){case Int8Array.BYTES_PER_ELEMENT:b=new Int8Array(a.buffer,f);break;case Int16Array.BYTES_PER_ELEMENT:b=new Int16Array(a.buffer,f);break;case Int32Array.BYTES_PER_ELEMENT:b=new Int32Array(a.buffer,f)}r=0;for(let t=0;t<p;t++){const e=o[3*t+8],i=new Float32Array(e+2);m.push(i);for(let e=0;e<2;e++)i[e]=o[3*t+8+e+1];for(let t=0;t<e;t++)i[t+2]=i[t]+b[r++]}return{areContours:d,thickness:u,outlines:m,width:h,height:c}}catch(t){warn(`decompressSignature: ${t}`);return null}}}class SignatureOptions extends DrawingOptions{constructor(){super();super.updateProperties({fill:AnnotationEditor._defaultLineColor,"stroke-width":0})}clone(){const t=new SignatureOptions;t.updateAll(this);return t}}class DrawnSignatureOptions extends InkDrawingOptions{constructor(t){super(t);super.updateProperties({stroke:AnnotationEditor._defaultLineColor,"stroke-width":1})}clone(){const t=new DrawnSignatureOptions(this._viewParameters);t.updateAll(this);return t}}class SignatureEditor extends DrawingEditor{#mh=!1;#fh=null;#bh=null;#yh=null;static _type="signature";static _editorType=b.SIGNATURE;static _defaultDrawingOptions=null;constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});this._willKeepAspectRatio=!0;this.#bh=t.signatureData||null;this.#fh=null;this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,e){AnnotationEditor.initialize(t,e);this._defaultDrawingOptions=new SignatureOptions;this._defaultDrawnSignatureOptions=new DrawnSignatureOptions(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();e.updateProperties(t);return e}static get supportMultipleDrawings(){return!1}static get typesMap(){return shadow(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#fh}}static computeTelemetryFinalData(t){const e=t.get("hasDescription");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){null!==this._drawId&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,e;const{_isCopy:i}=this;if(i){this._isCopy=!1;t=this.x;e=this.y}super.render();if(null===this._drawId)if(this.#bh){const{lines:t,mustSmooth:e,areContours:i,description:n,uuid:s,heightInPage:a}=this.#bh,{rawDims:{pageWidth:r,pageHeight:o},rotation:l}=this.parent.viewport,h=SignatureExtractor.processDrawnLines({lines:t,pageWidth:r,pageHeight:o,rotation:l,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:e,areContours:i});this.addSignature(h,a,n,s)}else{this.div.setAttribute("data-l10n-args",JSON.stringify({description:""}));this.div.hidden=!0;this._uiManager.getSignature(this)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#fh||""}));if(i){this._isCopy=!0;this._moveAfterPaste(t,e)}return this.div}setUuid(t){this.#yh=t;this.addEditToolbar()}getUuid(){return this.#yh}get description(){return this.#fh}set description(t){this.#fh=t;if(this.div){this.div.setAttribute("data-l10n-args",JSON.stringify({description:t}));super.addEditToolbar().then(e=>{e?.updateEditSignatureButton(t)})}}getSignaturePreview(){const{newCurves:t,areContours:e,thickness:i,width:n,height:s}=this.#bh,a=Math.max(n,s);return{areContours:e,outline:SignatureExtractor.processDrawnLines({lines:{curves:t.map(t=>({points:t})),thickness:i,width:n,height:s},pageWidth:a,pageHeight:a,rotation:0,innerMargin:0,mustSmooth:!1,areContours:e}).outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,e,i,n){const{x:s,y:a}=this,{outline:r}=this.#bh=t;this.#mh=r instanceof ContourDrawOutline;this.description=i;let o;if(this.#mh)o=SignatureEditor.getDefaultDrawingOptions();else{o=SignatureEditor._defaultDrawnSignatureOptions.clone();o.updateProperties({"stroke-width":r.thickness})}this._addOutlines({drawOutlines:r,drawingOptions:o});const[,l]=this.pageDimensions;let h=e/l;h=h>=1?.5:h;this.width*=h/this.height;if(this.width>=1){h*=.9/this.width;this.width=.9}this.height=h;this.setDims();this.x=s;this.y=a;this.center();this._onResized();this.onScaleChanging();this.rotate();this._uiManager.addToAnnotationStorage(this);this.setUuid(n);this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!n,hasDescription:!!i}});this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.process(t,e,i,n,SignatureEditor._INNER_MARGIN)}getFromText(t,e){const{rawDims:{pageWidth:i,pageHeight:n},rotation:s}=this.parent.viewport;return SignatureExtractor.extractContoursFromText(t,e,i,n,s,SignatureEditor._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:e,pageHeight:i},rotation:n}=this.parent.viewport;return SignatureExtractor.processDrawnLines({lines:t,pageWidth:e,pageHeight:i,rotation:n,innerMargin:SignatureEditor._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:e}){if(t)this._drawingOptions=SignatureEditor.getDefaultDrawingOptions();else{this._drawingOptions=SignatureEditor._defaultDrawnSignatureOptions.clone();this._drawingOptions.updateProperties({"stroke-width":e})}}serialize(t=!1){if(this.isEmpty())return null;const{lines:e,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":n}}=this,s=Object.assign(super.serialize(t),{isSignature:!0,areContours:this.#mh,color:[0,0,0],thickness:this.#mh?0:n});this.addComment(s);if(t){s.paths={lines:e,points:i};s.uuid=this.#yh;s.isCopy=!0}else s.lines=e;this.#fh&&(s.accessibilityData={type:"Figure",alt:this.#fh});return s}static deserializeDraw(t,e,i,n,s,a){return a.areContours?ContourDrawOutline.deserialize(t,e,i,n,s,a):InkDrawOutline.deserialize(t,e,i,n,s,a)}static async deserialize(t,e,i){const n=await super.deserialize(t,e,i);n.#mh=t.areContours;n.description=t.accessibilityData?.alt||"";n.#yh=t.uuid;return n}}class StampEditor extends AnnotationEditor{#vh=null;#Ah=null;#wh=null;#xh=null;#Ch=null;#Eh="";#Sh=null;#Th=!1;#kh=null;#_h=!1;#Mh=!1;static _type="stamp";static _editorType=b.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#xh=t.bitmapUrl;this.#Ch=t.bitmapFile;this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,e){AnnotationEditor.initialize(t,e)}static isHandlingMimeForPasting(t){return j.includes(t)}static paste(t,e){e.pasteEditor({mode:b.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Dh(t,e=!1){if(t){this.#vh=t.bitmap;if(!e){this.#Ah=t.id;this.#_h=t.isSvg}t.file&&(this.#Eh=t.file.name);this.#Ph()}else this.remove()}#Ih(){this.#wh=null;this._uiManager.enableWaiting(!1);if(this.#Sh)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#vh)this.addEditToolbar().then(()=>{this._editToolbar.hide();this._uiManager.editAltText(this,!0)});else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#vh){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:s,height:a}=t||this.copyCanvas(null,null,!0).imageData,r=await i.guess({name:"altText",request:{data:n,width:s,height:a,channels:n.length/(s*a)}});if(!r)throw new Error("No response from the AI service.");if(r.error)throw new Error("Error from the AI service.");if(r.cancel)return null;if(!r.output)throw new Error("No valid response from the AI service.");const o=r.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#Fh(){if(this.#Ah){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#Ah).then(t=>this.#Dh(t,!0)).finally(()=>this.#Ih());return}if(this.#xh){const t=this.#xh;this.#xh=null;this._uiManager.enableWaiting(!0);this.#wh=this._uiManager.imageManager.getFromUrl(t).then(t=>this.#Dh(t)).finally(()=>this.#Ih());return}if(this.#Ch){const t=this.#Ch;this.#Ch=null;this._uiManager.enableWaiting(!0);this.#wh=this._uiManager.imageManager.getFromFile(t).then(t=>this.#Dh(t)).finally(()=>this.#Ih());return}const t=document.createElement("input");t.type="file";t.accept=j.join(",");const e=this._uiManager._signal;this.#wh=new Promise(i=>{t.addEventListener("change",async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Dh(e)}else this.remove();i()},{signal:e});t.addEventListener("cancel",()=>{this.remove();i()},{signal:e})}).finally(()=>this.#Ih());t.click()}remove(){if(this.#Ah){this.#vh=null;this._uiManager.imageManager.deleteId(this.#Ah);this.#Sh?.remove();this.#Sh=null;if(this.#kh){clearTimeout(this.#kh);this.#kh=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#Ah&&null===this.#Sh&&this.#Fh();this.isAttachedToDOM||this.parent.add(this)}}else this.#Ah&&this.#Fh()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#wh||this.#vh||this.#xh||this.#Ch||this.#Ah||this.#Th)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this._isCopy){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.createAltText();this.#Th||(this.#vh?this.#Ph():this.#Fh());this._isCopy&&this._moveAfterPaste(t,e);this._uiManager.addShouldRescale(this);return this.div}setCanvas(t,e){const{id:i,bitmap:n}=this._uiManager.imageManager.getFromCanvas(t,e);e.remove();if(i&&this._uiManager.imageManager.isValidId(i)){this.#Ah=i;n&&(this.#vh=n);this.#Th=!1;this.#Ph()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#kh&&clearTimeout(this.#kh);this.#kh=setTimeout(()=>{this.#kh=null;this.#Bh()},200)}#Ph(){const{div:t}=this;let{width:e,height:i}=this.#vh;const[n,s]=this.pageDimensions,a=.75;if(this.width){e=this.width*n;i=this.height*s}else if(e>a*n||i>a*s){const t=Math.min(a*n/e,a*s/i);e*=t;i*=t}this._uiManager.enableWaiting(!1);const r=this.#Sh=document.createElement("canvas");r.setAttribute("role","img");this.addContainer(r);this.width=e/n;this.height=i/s;this.setDims();this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#Bh();if(!this.#Mh){this.parent.addUndoableEditor(this);this.#Mh=!0}this._reportTelemetry({action:"inserted_image"});this.#Eh&&this.div.setAttribute("aria-description",this.#Eh);this.annotationElementId||this._uiManager.a11yAlert(AnnotationEditor._l10nAlert.stamp)}copyCanvas(t,e,i=!1){t||(t=224);const{width:n,height:s}=this.#vh,a=new OutputScale;let r=this.#vh,o=n,l=s,h=null;if(e){if(n>e||s>e){const t=Math.min(e/n,e/s);o=Math.floor(n*t);l=Math.floor(s*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*a.sx),i=h.height=Math.ceil(l*a.sy);this.#_h||(r=this.#Lh(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(ColorScheme.isDarkMode){d="#8f8f9d";u="#42414d"}const p=15,g=p*a.sx,m=p*a.sy,f=new OffscreenCanvas(2*g,2*m),b=f.getContext("2d");b.fillStyle=d;b.fillRect(0,0,2*g,2*m);b.fillStyle=u;b.fillRect(0,0,g,m);b.fillRect(g,m,g,m);c.fillStyle=c.createPattern(f,"repeat");c.fillRect(0,0,t,i);c.drawImage(r,0,0,r.width,r.height,0,0,t,i)}let c=null;if(i){let e,i;if(a.symmetric&&r.width<t&&r.height<t){e=r.width;i=r.height}else{r=this.#vh;if(n>t||s>t){const a=Math.min(t/n,t/s);e=Math.floor(n*a);i=Math.floor(s*a);this.#_h||(r=this.#Lh(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(r,0,0,r.width,r.height,0,0,e,i);c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#Lh(t,e){const{width:i,height:n}=this.#vh;let s=i,a=n,r=this.#vh;for(;s>2*t||a>2*e;){const i=s,n=a;s>2*t&&(s=Math.ceil(s/2));a>2*e&&(a=Math.ceil(a/2));const o=new OffscreenCanvas(s,a);o.getContext("2d").drawImage(r,0,0,i,n,0,0,s,a);r=o.transferToImageBitmap()}return r}#Bh(){const[t,e]=this.parentDimensions,{width:i,height:n}=this,s=new OutputScale,a=Math.ceil(i*t*s.sx),r=Math.ceil(n*e*s.sy),o=this.#Sh;if(!o||o.width===a&&o.height===r)return;o.width=a;o.height=r;const l=this.#_h?this.#vh:this.#Lh(a,r),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,a,r)}#Oh(t){if(t){if(this.#_h){const t=this._uiManager.imageManager.getSvgUrl(this.#Ah);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#vh);t.getContext("2d").drawImage(this.#vh,0,0);return t.toDataURL()}if(this.#_h){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),n=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),s=new OffscreenCanvas(i,n);s.getContext("2d").drawImage(this.#vh,0,0,this.#vh.width,this.#vh.height,0,0,i,n);return s.transferToImageBitmap()}return structuredClone(this.#vh)}static async deserialize(t,e,i){let n=null,s=!1;if(t instanceof StampAnnotationElement){const{data:{rect:a,rotation:r,id:o,structParent:l,popupRef:h,richText:c,contentsObj:d,creationDate:u,modificationDate:p},container:g,parent:{page:{pageNumber:f}},canvas:y}=t;let v,A;if(y){delete t.canvas;({id:v,bitmap:A}=i.imageManager.getFromCanvas(g.id,y));y.remove()}else{s=!0;t._hasNoCanvas=!0}const w=(await e._structTree.getAriaAttributes(`${m}${o}`))?.get("aria-label")||"";n=t={annotationType:b.STAMP,bitmapId:v,bitmap:A,pageIndex:f-1,rect:a.slice(0),rotation:r,annotationElementId:o,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:w},isSvg:!1,structParent:l,popupRef:h,richText:c,comment:d?.str||null,creationDate:u,modificationDate:p}}const a=await super.deserialize(t,e,i),{rect:r,bitmap:o,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:d}=t;if(s){i.addMissingCanvas(t.id,a);a.#Th=!0}else if(h&&i.imageManager.isValidId(h)){a.#Ah=h;o&&(a.#vh=o)}else a.#xh=l;a.#_h=c;const[u,p]=a.pageDimensions;a.width=(r[2]-r[0])/u;a.height=(r[3]-r[1])/p;d&&(a.altTextData=d);a._initialData=n;t.comment&&a.setCommentData(t);a.#Mh=!!n;return a}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:this.#Ah,isSvg:this.#_h});this.addComment(i);if(t){i.bitmapUrl=this.#Oh(!0);i.accessibilityData=this.serializeAltText(!0);i.isCopy=!0;return i}const{decorative:n,altText:s}=this.serializeAltText(!1);!n&&s&&(i.accessibilityData={type:"Figure",alt:s});if(this.annotationElementId){const t=this.#Eo(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1;i.id=this.annotationElementId;delete i.bitmapId;return i}if(null===e)return i;e.stamps||=new Map;const a=this.#_h?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#Ah)){if(this.#_h){const t=e.stamps.get(this.#Ah);if(a>t.area){t.area=a;t.serialized.bitmap.close();t.serialized.bitmap=this.#Oh(!1)}}}else{e.stamps.set(this.#Ah,{area:a,serialized:i});i.bitmap=this.#Oh(!1)}return i}#Eo(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,n=t.pageIndex===e,s=(t.accessibilityData?.alt||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&n&&s,isSameAltText:s}}renderAnnotationElement(t){if(this.deleted){t.hide();return null}t.updateEdited({rect:this.getPDFRect(),popup:this.comment});return null}}class AnnotationEditorLayer{#ro;#Rh=!1;#Nh=null;#Uh=null;#Hh=null;#zh=new Map;#Gh=!1;#Wh=!1;#Vh=!1;#jh=null;#$h=null;#Kh=null;#Xh=null;#qh=null;#Yh=-1;#y;static _initialized=!1;static#J=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor,SignatureEditor].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:n,accessibilityManager:s,annotationLayer:a,drawLayer:r,textLayer:o,viewport:l,l10n:h}){const c=[...AnnotationEditorLayer.#J.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c);this.#y=t;this.pageIndex=e;this.div=i;this.#ro=s;this.#Nh=a;this.viewport=l;this.#Kh=o;this.drawLayer=r;this._structTree=n;this.#y.addLayer(this)}get isEmpty(){return 0===this.#zh.size}get isInvisible(){return this.isEmpty&&this.#y.getMode()===b.NONE}updateToolbar(t){this.#y.updateToolbar(t)}updateMode(t=this.#y.getMode()){this.#Qh();switch(t){case b.NONE:this.div.classList.toggle("nonEditing",!0);this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case b.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case b.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;e.toggle("nonEditing",!1);if(t===b.POPUP)e.toggle("commentEditing",!0);else{e.toggle("commentEditing",!1);for(const i of AnnotationEditorLayer.#J.values())e.toggle(`${i._type}Editing`,t===i._editorType)}this.div.hidden=!1}hasTextLayer(t){return t===this.#Kh?.div}setEditingState(t){this.#y.setEditingState(t)}addCommands(t){this.#y.addCommands(t)}cleanUndoStack(t){this.#y.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#Nh?.togglePointerEvents(t)}get#Jh(){return 0!==this.#zh.size?this.#zh.values():this.#y.getEditors(this.pageIndex)}async enable(){this.#Vh=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);this.div.classList.toggle("nonEditing",!1);this.#qh?.abort();this.#qh=null;const t=new Set;for(const e of this.#Jh){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#y.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}const e=this.#Nh;if(e)for(const i of e.getEditableAnnotations()){i.hide();if(this.#y.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#Vh=!1;this.#y._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){this.#Wh=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);this.div.classList.toggle("nonEditing",!0);if(this.#Kh&&!this.#qh){this.#qh=new AbortController;const t=this.#y.combinedSignal(this.#qh);this.#Kh.div.addEventListener("pointerdown",t=>{const{clientX:e,clientY:i,timeStamp:n}=t;if(n-this.#Yh>500){this.#Yh=n;return}this.#Yh=-1;const{classList:s}=this.div;s.toggle("getElements",!0);const a=document.elementsFromPoint(e,i);s.toggle("getElements",!1);if(!this.div.contains(a[0]))return;let r;const o=new RegExp(`^${f}[0-9]+$`);for(const t of a)if(o.test(t.id)){r=t.id;break}if(!r)return;const l=this.#zh.get(r);if(null===l?.annotationElementId){stopEvent(t);l.dblclick(t)}},{signal:t,capture:!0})}const t=this.#Nh,e=[];if(t){const i=new Map,n=new Map;for(const t of this.#Jh){t.disableEditing();if(t.annotationElementId)if(null===t.serialize()){n.set(t.annotationElementId,t);this.getEditableAnnotation(t.annotationElementId)?.show();t.remove()}else i.set(t.annotationElementId,t);else e.push(t)}for(const e of t.getEditableAnnotations()){const{id:t}=e.data;if(this.#y.isDeletedAnnotationElement(t)){e.updateEdited({deleted:!0});continue}let s=n.get(t);if(s){s.resetAnnotationElement(e);s.show(!1);e.show()}else{s=i.get(t);if(s){this.#y.addChangedExistingAnnotation(s);s.renderAnnotationElement(e)&&s.show(!1)}e.show()}}}this.#Qh();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#J.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);t?.updateFakeAnnotations(e);this.#Wh=!1}getEditableAnnotation(t){return this.#Nh?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#y.getActive()!==t&&this.#y.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#Kh?.div&&!this.#Xh){this.#Xh=new AbortController;const t=this.#y.combinedSignal(this.#Xh);this.#Kh.div.addEventListener("pointerdown",this.#Zh.bind(this),{signal:t});this.#Kh.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#Kh?.div&&this.#Xh){this.#Xh.abort();this.#Xh=null;this.#Kh.div.classList.remove("highlighting")}}#Zh(t){this.#y.unselectAll();const{target:e}=t;if(e===this.#Kh.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent")||e.classList.contains("textLayerImages")||e.classList.contains("textLayerImagePlaceholder"))&&this.#Kh.div.contains(e)){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#y.showAllEditors("highlight",!0,!0);this.#Kh.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#y.direction,{target:this.#Kh.div,x:t.x,y:t.y});this.#Kh.div.addEventListener("pointerup",()=>{this.#Kh.div.classList.remove("free");this.toggleDrawing(!0)},{once:!0,signal:this.#y._signal});t.preventDefault()}}enableClick(){if(this.#Uh)return;this.#Uh=new AbortController;const t=this.#y.combinedSignal(this.#Uh);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#Uh?.abort();this.#Uh=null}attach(t){this.#zh.set(t.id,t);const{annotationElementId:e}=t;e&&this.#y.isDeletedAnnotationElement(e)&&this.#y.removeDeletedAnnotationElement(t)}detach(t){this.#zh.delete(t.id);this.#ro?.removePointerInTextLayer(t.contentDiv);!this.#Wh&&t.annotationElementId&&this.#y.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#y.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#y.addDeletedAnnotationElement(t);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#y.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#Vh);this.#y.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#Hh){t._focusEventsAllowed=!1;this.#Hh=setTimeout(()=>{this.#Hh=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#y._signal});e.focus()}},0)}t._structTreeParentId=this.#ro?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getEditorByUID(t){for(const e of this.#zh.values())if(e.uid===t)return e;return null}get#tc(){return AnnotationEditorLayer.#J.get(this.#y.getMode())}combinedSignal(t){return this.#y.combinedSignal(t)}#ec(t){const e=this.#tc;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#tc?.canCreateNewEmptyEditor()}async pasteEditor(t,e){this.updateToolbar(t);await this.#y.updateMode(t.mode);const{offsetX:i,offsetY:n}=this.#ic(),s=this.#y.getId(),a=this.#ec({parent:this,id:s,x:i,y:n,uiManager:this.#y,isCentered:!0,...e});a&&this.add(a)}async deserialize(t){return await(AnnotationEditorLayer.#J.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#y))||null}createAndAddNewEditor(t,e,i={}){const n=this.#y.getId(),s=this.#ec({parent:this,id:n,x:t.offsetX,y:t.offsetY,uiManager:this.#y,isCentered:e,...i});s&&this.add(s);return s}get boundingClientRect(){return this.div.getBoundingClientRect()}#ic(){const{x:t,y:e,width:i,height:n}=this.boundingClientRect,s=Math.max(0,t),a=Math.max(0,e),r=(s+Math.min(window.innerWidth,t+i))/2-t,o=(a+Math.min(window.innerHeight,e+n))/2-e,[l,h]=this.viewport.rotation%180==0?[r,o]:[o,r];return{offsetX:l,offsetY:h}}addNewEditor(t={}){this.createAndAddNewEditor(this.#ic(),!0,t)}setSelected(t){this.#y.setSelected(t)}toggleSelected(t){this.#y.toggleSelected(t)}unselect(t){this.#y.unselect(t)}pointerup(t){const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;if(!this.#Gh)return;this.#Gh=!1;if(this.#tc?.isDrawer&&this.#tc.supportMultipleDrawings)return;if(!this.#Rh){this.#Rh=!0;return}const i=this.#y.getMode();i!==b.STAMP&&i!==b.POPUP&&i!==b.SIGNATURE?this.createAndAddNewEditor(t,!1):this.#y.unselectAll()}pointerdown(t){this.#y.getMode()===b.HIGHLIGHT&&this.enableTextSelection();if(this.#Gh){this.#Gh=!1;return}const{isMac:e}=FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#Gh=!0;if(this.#tc?.isDrawer){this.startDrawingSession(t);return}const i=this.#y.getActive();this.#Rh=!i||i.isEmpty()}startDrawingSession(t){this.div.focus({preventScroll:!0});if(this.#jh){this.#tc.startDrawing(this,this.#y,!1,t);return}this.#y.setCurrentDrawingSession(this);this.#jh=new AbortController;const e=this.#y.combinedSignal(this.#jh);this.div.addEventListener("blur",({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#$h=null;this.commitOrRemove()}},{signal:e});this.#tc.startDrawing(this,this.#y,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#$h=t);return}this.#$h&&setTimeout(()=>{this.#$h?.focus();this.#$h=null},0)}endDrawingSession(t=!1){if(!this.#jh)return null;this.#y.setCurrentDrawingSession(null);this.#jh.abort();this.#jh=null;this.#$h=null;return this.#tc.endDrawing(t)}findNewParent(t,e,i){const n=this.#y.findParent(e,i);if(null===n||n===this)return!1;n.changeParent(t);return!0}commitOrRemove(){if(this.#jh){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#jh&&this.#tc.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#y.getActive()?.parent===this){this.#y.commitOrRemove();this.#y.setActiveEditor(null)}if(this.#Hh){clearTimeout(this.#Hh);this.#Hh=null}for(const t of this.#zh.values()){this.#ro?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#zh.clear();this.#y.removeLayer(this)}#Qh(){for(const t of this.#zh.values())t.isEmpty()&&t.remove()}async render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#y.getEditors(this.pageIndex)){this.add(t);t.rebuild()}await this.#y.findClonesForPage(this);this.div.hidden=this.isEmpty;this.updateMode()}update({viewport:t}){this.#y.commitOrRemove();this.#Qh();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#zh.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#y.viewParameters.realScale}}function compareTextLayers(t,e){return t===e?0:t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function getTextLayer(t){return t?t.nodeType===Node.ELEMENT_NODE?t.closest(".textLayer"):t.parentElement?.closest(".textLayer")||null:null}function isPointBefore(t,e,i,n){if(t===i)return e<=n;const s=t.compareDocumentPosition(i);return!!(s&Node.DOCUMENT_POSITION_FOLLOWING)||!(s&Node.DOCUMENT_POSITION_PRECEDING)&&null}function normalizeEdgeBoundary(t,e,i){if(t.nodeType!==Node.ELEMENT_NODE||!t.classList.contains("textLayer")||e!==t.childNodes.length)return{container:t,offset:e};let n=t.lastChild;n?.nodeType===Node.ELEMENT_NODE&&n.classList.contains("endOfContent")&&(n=n.previousSibling);return n&&i.contains(n)?n.nodeType===Node.TEXT_NODE?{container:n,offset:n.textContent.length}:{container:n,offset:n.childNodes.length}:null}class DrawLayer{#Tr=null;#nc=new Map;#Kh=null;#nt=null;#xt=null;#sc=null;#ac=new Map;static#T=0;static#rc=0;static#oc=null;static#lc=new Set;static#hc=!1;static#cc=new Set;static#dc=new WeakMap;constructor({filterFactory:t=null,pageColors:e=null,pageIndex:i,textLayer:n=null}){this.pageIndex=i;this.#nt=t;this.#xt=e;if(n){const t=DrawLayer.#dc.get(n);if(t?.selectionDiv){t.selectionDiv.remove();DrawLayer.#lc.delete(t.selectionDiv)}DrawLayer.#dc.set(n,{drawLayer:this});DrawLayer.#cc.add(n);this.#Kh=n;this.#sc=new MutationObserver(t=>{if(this.#Tr&&this.#Kh?.isConnected&&DrawLayer.#uc())for(const{addedNodes:e}of t)for(const t of e)if(t.nodeType===Node.ELEMENT_NODE&&t.classList.contains("endOfContent")){DrawLayer.#Ut();return}});this.#sc.observe(n,{childList:!0});if(null===DrawLayer.#oc){DrawLayer.#oc=new AbortController;const{signal:t}=DrawLayer.#oc;document.addEventListener("selectionchange",DrawLayer.#Ut.bind(DrawLayer),{signal:t});document.addEventListener("pointerdown",()=>{DrawLayer.#hc=!0},{signal:t});document.addEventListener("pointerup",()=>{DrawLayer.#hc=!1},{signal:t});window.addEventListener("blur",()=>{DrawLayer.#hc=!1},{signal:t})}}}setParent(t){if(this.#Tr){if(this.#Tr!==t){if(this.#nc.size>0)for(const e of this.#nc.values()){e.remove();t.append(e)}this.#Tr=t}}else{this.#Tr=t;this.#Kh?.isConnected&&DrawLayer.#uc()&&DrawLayer.#Ut()}}static#pc(t){const e=this.#dc.get(t);if(e?.selectionDiv){e.selectionDiv.remove();this.#lc.delete(e.selectionDiv);e.selectionDiv=null;e.path=null}}static#uc(){const t=document.getSelection();return!!t&&!t.isCollapsed}static#gc(){return[...this.#cc].filter(t=>t.isConnected).sort(compareTextLayers)}static#Ut(){const t=document.getSelection();if(!t||t.isCollapsed){for(const t of this.#lc)t.remove();this.#lc.clear();return}const e=new WeakMap,i=this.#gc(),n=[];for(let e=0,s=t.rangeCount;e<s;e++){const s=t.getRangeAt(e);if(s.collapsed)continue;let{startContainer:a,startOffset:r,endContainer:o,endOffset:l}=s,h=getTextLayer(a),c=getTextLayer(o);const d=null===h,u=null===c;if(this.#hc&&d!==u)return;if(1===t.rangeCount){const{anchorNode:e,anchorOffset:i,focusNode:n,focusOffset:s}=t,d=getTextLayer(e),u=getTextLayer(n),p=isPointBefore(e,i,n,s);if(d&&u&&null!==p)if(p){a=e;r=i;h=d;o=n;l=s;c=u}else{a=n;r=s;h=u;o=e;l=i;c=d}}const p=i.filter(t=>s.intersectsNode(t));if(0===p.length)continue;let g=!1;if(!h){h=p[0];a=h;r=0;g=!0}if(!c){c=p.at(-1);o=c;l=c.childNodes.length;g=!0}if(o.nodeType===Node.ELEMENT_NODE)if(o.classList.contains("endOfContent")){const t=o.previousSibling;if(!t)continue;o=t;l=t.nodeType===Node.TEXT_NODE?t.textContent.length:t.childNodes.length}else if(o.classList.contains("textLayer")&&o.childNodes.length===l){const t=normalizeEdgeBoundary(o,l,c);if(!t)continue;o=t.container;l=t.offset}if(a.nodeType===Node.ELEMENT_NODE){const t=normalizeEdgeBoundary(a,r,h);if(!t)continue;a=t.container;r=t.offset}if(h!==c||g||!p.includes(h))for(const t of p){const e=t.firstChild;if(!e)continue;const i=document.createRange();t===h?i.setStart(a,r):i.setStartBefore(e);if(t===c)i.setEnd(o,l);else{const e=t.lastChild;if(!e)continue;if(e.nodeType===Node.ELEMENT_NODE&&e.classList.contains("endOfContent")){const t=e.previousSibling;if(!t)continue;i.setEndAfter(t)}else i.setEndAfter(e)}i.collapsed||n.push([i,t])}else n.push([s,h])}const s=new Set(n.map(t=>t[1]));for(const t of this.#cc)s.has(t)||this.#pc(t);for(const[t,i]of n){const n=DrawLayer.#dc.get(i);if(!n)continue;let s=e.get(i);if(!s){const t=i.getBoundingClientRect();s=(e,i,n,s)=>({x:(e-t.x)/t.width,y:(i-t.y)/t.height,width:n/t.width,height:s/t.height});e.set(i,s)}const a=[];for(let{x:e,y:i,width:n,height:r}of t.getClientRects())if(0!==n&&0!==r){({x:e,y:i,width:n,height:r}=s(e,i,n,r));1===n&&1===r||a.push(`M${e} ${i} h${n} v${r} h-${n} Z`)}if(0===a.length)continue;const r=n.drawLayer;let o=n.selectionDiv,l=n.path;if(!o){const t="clip_selection_"+DrawLayer.#rc++;o=document.createElement("div");o.className="selection";o.style.clipPath=`url(#${t})`;const e=r.#nt?.createSelectionStyle(r.#xt);if(e)for(const[t,i]of Object.entries(e))o.style.setProperty(t,i);const i=DrawLayer._svgFactory.create(1,1,!0);i.setAttribute("aria-hidden","true");i.setAttribute("width","100%");i.setAttribute("height","100%");const s=DrawLayer._svgFactory.createElement("clipPath");s.setAttribute("id",t);s.setAttribute("clipPathUnits","objectBoundingBox");l=DrawLayer._svgFactory.createElement("path");s.append(l);i.append(s);o.append(i);n.path=l;n.selectionDiv=o}if(!o.parentNode&&r.#Tr){r.#Tr.append(o);this.#lc.add(o)}l.setAttribute("d",a.join(" "))}}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#mc(t,[e,i,n,s]){const{style:a}=t;a.top=100*i+"%";a.left=100*e+"%";a.width=100*n+"%";a.height=100*s+"%"}#fc(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#Tr.append(t);t.setAttribute("aria-hidden","true");return t}#bc(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const n=`clip_${e}`;i.setAttribute("id",n);i.setAttribute("clipPathUnits","objectBoundingBox");const s=DrawLayer._svgFactory.createElement("use");i.append(s);s.setAttribute("href",`#${e}`);s.classList.add("clip");return n}#yc(t,e){for(const[i,n]of Object.entries(e))null===n?t.removeAttribute(i):t.setAttribute(i,n)}draw(t,e=!1,i=!1){const n=DrawLayer.#T++,s=this.#fc(),a=DrawLayer._svgFactory.createElement("defs");s.append(a);const r=DrawLayer._svgFactory.createElement("path");a.append(r);const o=`path_${n}`;r.setAttribute("id",o);r.setAttribute("vector-effect","non-scaling-stroke");e&&this.#ac.set(n,r);const l=i?this.#bc(a,o):null,h=DrawLayer._svgFactory.createElement("use");s.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(s,t);this.#nc.set(n,s);return{id:n,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=DrawLayer.#T++,n=this.#fc(),s=DrawLayer._svgFactory.createElement("defs");n.append(s);const a=DrawLayer._svgFactory.createElement("path");s.append(a);const r=`path_${i}`;a.setAttribute("id",r);a.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");s.append(t);o=`mask_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const n=DrawLayer._svgFactory.createElement("use");t.append(n);n.setAttribute("href",`#${r}`);n.setAttribute("stroke","none");n.setAttribute("fill","black");n.setAttribute("fill-rule","nonzero");n.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");n.append(l);l.setAttribute("href",`#${r}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();n.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(n,t);this.#nc.set(i,n);return i}finalizeDraw(t,e){this.#ac.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:n,rootClass:s,path:a}=e,r="number"==typeof t?this.#nc.get(t):t;if(r){i&&this.#yc(r,i);n&&DrawLayer.#mc(r,n);if(s){const{classList:t}=r;for(const[e,i]of Object.entries(s))t.toggle(e,i)}if(a){const t=r.firstElementChild.firstElementChild;this.#yc(t,a)}}}updateParent(t,e){if(e===this)return;const i=this.#nc.get(t);if(i){e.#Tr.append(i);this.#nc.delete(t);e.#nc.set(t,i)}}remove(t){this.#ac.delete(t);if(null!==this.#Tr){this.#nc.get(t).remove();this.#nc.delete(t)}}destroy(){this.#Tr=null;for(const t of this.#nc.values())t.remove();this.#nc.clear();this.#ac.clear();this.#sc?.disconnect();this.#sc=null;if(this.#Kh){const t=DrawLayer.#dc.get(this.#Kh);if(t?.drawLayer===this){DrawLayer.#pc(this.#Kh);DrawLayer.#dc.delete(this.#Kh);DrawLayer.#cc.delete(this.#Kh);if(0===DrawLayer.#cc.size){DrawLayer.#oc?.abort();DrawLayer.#oc=null;DrawLayer.#hc=!1}}this.#Kh=null}}}function percentage(t){return`${(100*t).toFixed(2)}%`}class TextLayerImages{#vc=[];#Ac=new Map;#wc=null;#xc=0;#Js=0;#Qs=0;static#Cc=null;constructor(t,e,i,n){this.#xc=t;this.#vc=e;this.#Js=i.rawDims.pageWidth;this.#Qs=i.rawDims.pageHeight;this.#wc=n}render(){const t=document.createElement("div");t.className="textLayerImages";for(let e=0;e<this.#vc.length;e+=6){const i=this.#Ec(this.#vc.subarray(e,e+6));i&&t.append(i)}t.addEventListener("contextmenu",t=>{if(!(t.target instanceof HTMLCanvasElement))return;const e=t.target,i=this.#Ac.get(e);if(!i)return;const n=TextLayerImages.#Cc?.deref();if(n===e)return;if(n){n.width=0;n.height=0}TextLayerImages.#Cc=new WeakRef(e);const{inverseTransform:s,x1:a,y1:r,width:o,height:l}=i,h=this.#wc(),c=Math.ceil(a*h.width),d=Math.ceil(r*h.height),u=Math.floor((a+o/this.#Js)*h.width),p=Math.floor((r+l/this.#Qs)*h.height);e.width=u-c;e.height=p-d;const g=e.getContext("2d");g.setTransform(...s);g.translate(-c,-d);g.drawImage(h,0,0)});return t}#Ec([t,e,i,n,s,a]){const r=Math.hypot((s-t)*this.#Js,(a-e)*this.#Qs),o=Math.hypot((i-t)*this.#Js,(n-e)*this.#Qs);if(r<this.#xc||o<this.#xc)return null;const l=[(s-t)*this.#Js/r,(a-e)*this.#Qs/r,(i-t)*this.#Js/o,(n-e)*this.#Qs/o,0,0],h=Util.inverseTransform(l),c=document.createElement("canvas");c.className="textLayerImagePlaceholder";c.width=0;c.height=0;Object.assign(c.style,{opacity:0,position:"absolute",left:percentage(t),top:percentage(e),width:percentage(r/this.#Js),height:percentage(o/this.#Qs),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`});this.#Ac.set(c,{inverseTransform:h,width:r,height:o,x1:t,y1:e});return c}}globalThis._pdfjsTestingUtils={HighlightOutliner};globalThis.pdfjsLib={AbortException,AnnotationEditorLayer,AnnotationEditorParamsType:y,AnnotationEditorType:b,AnnotationEditorUIManager,AnnotationLayer,AnnotationMode:g,AnnotationType:k,applyOpacity,build:Ot,ColorPicker,createValidAbsoluteUrl,CSSConstants,DOMSVGFactory,DrawLayer,FeatureTest,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getRGBA,getUuid,GlobalWorkerOptions,ImageKind:T,InvalidPDFException,isDataScheme,isPdfFile,isValidExplicitDest:ht,makeArr,makeMap,makeObj,MathClamp,noContextMenu,normalizeUnicode,OPS:B,OutputScale,PasswordException,PasswordResponses:H,PDFDataRangeTransport,PDFDateString,PDFWorker,PermissionFlag:v,PixelsPerInch,RenderingCancelledException,renderRichText,ResponseException,setLayerDimensions,shadow,SignatureExtractor,stopEvent,SupportedImageMimeTypes:j,TextLayer,TextLayerImages,TouchManager,updateUrlHash,Util,VerbosityLevel:F,version:Lt,XfaLayer};export{AbortException,AnnotationEditorLayer,y as AnnotationEditorParamsType,b as AnnotationEditorType,AnnotationEditorUIManager,AnnotationLayer,g as AnnotationMode,k as AnnotationType,CSSConstants,ColorPicker,DOMSVGFactory,DrawLayer,FeatureTest,GlobalWorkerOptions,T as ImageKind,InvalidPDFException,MathClamp,B as OPS,OutputScale,PDFDataRangeTransport,PDFDateString,PDFWorker,PasswordException,H as PasswordResponses,v as PermissionFlag,PixelsPerInch,RenderingCancelledException,ResponseException,SignatureExtractor,j as SupportedImageMimeTypes,TextLayer,TextLayerImages,TouchManager,Util,F as VerbosityLevel,XfaLayer,applyOpacity,Ot as build,createValidAbsoluteUrl,fetchData,findContrastColor,getDocument,getFilenameFromUrl,getPdfFilenameFromUrl,getRGB,getRGBA,getUuid,isDataScheme,isPdfFile,ht as isValidExplicitDest,makeArr,makeMap,makeObj,noContextMenu,normalizeUnicode,renderRichText,setLayerDimensions,shadow,stopEvent,updateUrlHash,Lt as version};
|