@mavea/mavea 1.0.17 → 1.1.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/CHANGELOG.md +59 -3
- package/DISCLAIMER.md +4 -1
- package/PRIVACY.md +14 -8
- package/README.md +67 -24
- package/TERMS.md +11 -1
- package/THIRD-PARTY.txt +25248 -621
- package/bin/mavea.mjs +156 -147
- package/dist/.vite/manifest.json +2333 -1738
- package/dist/assets/AnnotationLayer-ClU-e6qL.css +1 -0
- package/dist/assets/AnnotationLayer-IiuYsoSa.js +0 -0
- package/dist/assets/AppCommandPalette-Dm3SedPO.js +1 -0
- package/dist/assets/AtlasView-B82UfrEX.js +1 -0
- package/dist/assets/BlockEmpty-B82uCse8.js +1 -0
- package/dist/assets/BriefingPlayer-C0D_2ILa.js +1 -0
- package/dist/assets/CanvasSkeleton-CcHXJqdq.js +2 -0
- package/dist/assets/CardEditor-DABIhGdQ.js +1 -0
- package/dist/assets/CheckLogRail-BOaXnqWK.css +1 -0
- package/dist/assets/CheckLogRail-BU_rmAFH.js +1 -0
- package/dist/assets/{CodeOutput-H8TQzjqL.js → CodeOutput-DF892aIR.js} +3 -3
- package/dist/assets/CommandPalette-E3reEqYR.js +1 -0
- package/dist/assets/ConversationVideoStudio-CIAMxElj.css +1 -0
- package/dist/assets/ConversationVideoStudio-DEZBpJUz.js +1 -0
- package/dist/assets/CourseLessonReader-Bpt-DkJo.js +2 -0
- package/dist/assets/CourseRail-C8MJG-zf.js +1 -0
- package/dist/assets/CoursesApp-DFVkhP2f.js +2 -0
- package/dist/assets/CrossExamPanel-CdIYUu-B.js +1 -0
- package/dist/assets/DashPresent-DwWDtjrU.js +1 -0
- package/dist/assets/DashboardDetail-D4wkiTux.js +2 -0
- package/dist/assets/DashboardLoopGate-B5UBPsvU.js +2 -0
- package/dist/assets/DashboardLoopRuntime-CAnZX234.js +1 -0
- package/dist/assets/DashboardOverview-C3hv9sm1.js +1 -0
- package/dist/assets/DashboardSettings-eMhHliVh.js +1 -0
- package/dist/assets/{DashboardsApp-Dx-EsaPW.css → DashboardsApp-B6yUtkKB.css} +1 -1
- package/dist/assets/DashboardsApp-BwFtTdWa.js +2 -0
- package/dist/assets/{DeepZoomApp-CQaTT2Uh.js → DeepZoomApp-CxdcUeFJ.js} +2 -2
- package/dist/assets/DelegatePanel-B0kIu8Et.js +33 -0
- package/dist/assets/DemoGallery-B__X0_H3.js +1 -0
- package/dist/assets/DropSelect-C3uYlej-.js +1 -0
- package/dist/assets/DropSelect-DilESAgA.css +1 -0
- package/dist/assets/ExportModal-CDGlhpdH.js +2 -0
- package/dist/assets/ExtractionPreview-CloJnrQi.js +18 -0
- package/dist/assets/{FallbackCard-B489rTd9.js → FallbackCard-ap_4wOfj.js} +1 -1
- package/dist/assets/FeatureUseNotice-CwHstxBh.js +1 -0
- package/dist/assets/FlagshipCTA-uoeGMQas.js +1 -0
- package/dist/assets/FlagshipCommandPalette-CHsD5BSH.js +1 -0
- package/dist/assets/FlagshipShowcase-D53Q_4m0.js +1 -0
- package/dist/assets/FlashcardsApp-CnLfEnDH.js +1 -0
- package/dist/assets/ForecastPanel-zPUh2ClQ.js +1 -0
- package/dist/assets/GalleryApp-2Ffc6CY6.js +1 -0
- package/dist/assets/{HonestByDesign-CCOt31nx.js → HonestByDesign-5jIu2ZC8.js} +1 -1
- package/dist/assets/{HowItWorks-auW5XXCZ.js → HowItWorks-BiJF84EM.js} +1 -1
- package/dist/assets/LegalApp-zC-rvTww.js +1 -0
- package/dist/assets/{LegalMarkdownDocument-DBjLz9Yf.js → LegalMarkdownDocument-CJ-gRHdX.js} +2 -2
- package/dist/assets/LegalPageShell-CmxGCdqJ.css +1 -0
- package/dist/assets/LegalPageShell-Dyd4Uh3r.js +1 -0
- package/dist/assets/LeverPanel-D1SNRGdm.js +1 -0
- package/dist/assets/Library-DmdzY2se.js +1 -0
- package/dist/assets/LibraryOverlay-_xpWdhLN.js +1 -0
- package/dist/assets/LiveApp-BNae3fDZ.css +1 -0
- package/dist/assets/LiveApp-DjcJQURO.js +78 -0
- package/dist/assets/LiveSettings-BceODlOb.js +6 -0
- package/dist/assets/MindMapViewerDrawer-BuDodC0s.js +1 -0
- package/dist/assets/MindShape-CBcCC7hP.js +1 -0
- package/dist/assets/MindShape-CaPeUo-a.css +1 -0
- package/dist/assets/{Orb-B0NEVfqL.js → Orb-D8lhTdmY.js} +1 -1
- package/dist/assets/PinToDashboard-DBIXvhlF.js +1 -0
- package/dist/assets/PlanReview-DUQ7OMvV.js +1 -0
- package/dist/assets/Presence-CKSoyuhE.js +1 -0
- package/dist/assets/PresentationDeck-C518t9pP.js +1 -0
- package/dist/assets/PrismApp-DRLl8841.js +2 -0
- package/dist/assets/PrismAskController-QRwxRP8D.js +37 -0
- package/dist/assets/PrismBriefingPlayer-Kyb8Vs_w.js +2 -0
- package/dist/assets/PrismOverlay-Bj7tCu5Q.js +105 -0
- package/dist/assets/PrismWorkbench-BCnhkp-S.js +1 -0
- package/dist/assets/{PrivacyApp-rhzy-5HG.js → PrivacyApp-DHSRr8wq.js} +16 -10
- package/dist/assets/Recap-T9DtFaEk.js +1 -0
- package/dist/assets/ReelJelly-D5e-jt-8.js +1 -0
- package/dist/assets/ReplayCard-CKo5reXy.js +2 -0
- package/dist/assets/ReplayCard-Cs6mzTRa.css +1 -0
- package/dist/assets/ReplayOverlay-DqAwLshS.js +1 -0
- package/dist/assets/ReplayOverlay-DzkcTnCA.css +1 -0
- package/dist/assets/RewindOverlay-CkJIETE0.js +1 -0
- package/dist/assets/RippleApp-C76VTaZK.js +2 -0
- package/dist/assets/RippleAskController-CdlMlRH8.js +34 -0
- package/dist/assets/RippleOverlay-Mvz3CXhD.js +6 -0
- package/dist/assets/SeeDontRead-BkySmnP3.js +1 -0
- package/dist/assets/ShareModal-Cl3ryjgK.js +2 -0
- package/dist/assets/{ShareModal-PobtP7AJ.css → ShareModal-D1QuQEko.css} +1 -1
- package/dist/assets/ShipCascade-Bf-qDWMb.js +1 -0
- package/dist/assets/ShipCourse-Cy5ldKLE.js +1 -0
- package/dist/assets/{ShipGate-BYYu9WVq.js → ShipGate-D4BP41-h.js} +1 -1
- package/dist/assets/ShipHotspots-lGioTtf1.js +1 -0
- package/dist/assets/{ShipIncident-Xod2gbjc.js → ShipIncident-DMLb14Lx.js} +1 -1
- package/dist/assets/ShipMigration-ZnzL-1rC.js +1 -0
- package/dist/assets/ShipOnboarding-DUxtx2Vr.js +1 -0
- package/dist/assets/ShipRead-CJJmY-wy.js +1 -0
- package/dist/assets/ShipRollout-Dt2TgI0L.js +1 -0
- package/dist/assets/ShipSuggestions-BrAXTjAR.js +1 -0
- package/dist/assets/ShipWorkspace-_MtKAiKH.js +2 -0
- package/dist/assets/SignatureLoop-Cdkifjb8.js +1 -0
- package/dist/assets/SrsReview-B1B2VekR.css +1 -0
- package/dist/assets/SrsReview-DhWNYYv7.js +1 -0
- package/dist/assets/SynthesisApp-C5udWwng.js +2 -0
- package/dist/assets/SynthesisOverlay-1o-CJsyX.js +66 -0
- package/dist/assets/{TermsApp-Dk2jpxq-.js → TermsApp-DIAESAZs.js} +13 -3
- package/dist/assets/TopbarMenu-DQXxqSWY.js +1 -0
- package/dist/assets/TopicCanvas-DkzJORfl.js +2 -0
- package/dist/assets/TourPrism-Bxp--s0i.js +1 -0
- package/dist/assets/TrackerTile-CyPD0A6b.js +2 -0
- package/dist/assets/TwoSurfaces-C_0XBpwA.js +1 -0
- package/dist/assets/UnderstoodPanel-DmJph4el.js +1 -0
- package/dist/assets/WhyMachineOverlay-QDSZx5Y7.js +1 -0
- package/dist/assets/WorldOverlay-DRdBQMnb.css +1 -0
- package/dist/assets/WorldOverlay-DorHCLzw.js +1 -0
- package/dist/assets/WowFeatures-DNEeO2pr.js +1 -0
- package/dist/assets/ZoomDeck-qdlPe_yl.js +1 -0
- package/dist/assets/__vite-browser-external-gfE6fZcA.js +1 -0
- package/dist/assets/alternateFinishes-Cgks49KV.js +494 -0
- package/dist/assets/annotationAuto-BmKrZ3hU.js +1 -0
- package/dist/assets/annotationReel-K2FYv-3B.js +1 -0
- package/dist/assets/annotations-CftUUB13.js +1 -0
- package/dist/assets/attachments-BW-vki-E.js +1 -0
- package/dist/assets/backup-PaRBwjJy.js +1 -0
- package/dist/assets/blockLabel-FogyzEQY.js +1 -0
- package/dist/assets/blockTypes-DUDdP3pB.js +1 -0
- package/dist/assets/buildShip-BgFg98tH.js +1 -0
- package/dist/assets/cache-CvbSI-pr.js +1 -0
- package/dist/assets/canvas-BlkTFnVo.js +1 -0
- package/dist/assets/capture-CL9ENM-c.js +2 -0
- package/dist/assets/catalog-Db9GWM6N.js +1 -0
- package/dist/assets/{cfo.generated-Bjl5OGay.js → cfo.generated-j5CXp1Zz.js} +1 -1
- package/dist/assets/chapters-Dqm4iLDa.js +1 -0
- package/dist/assets/charts2-CaKGzkgJ.js +1 -0
- package/dist/assets/checkLogModel-BMtruriG.js +1 -0
- package/dist/assets/{citation-BcvmjKS8.js → citation-BsSvaaer.js} +1 -1
- package/dist/assets/{codeContext-0UMRSGRr.js → codeContext-goNoLAIr.js} +1 -1
- package/dist/assets/compiler-runtime-qQQXpJgv.js +1 -0
- package/dist/assets/{compose-BJ9EfcQS.js → compose-D-OsDiU9.js} +1 -1
- package/dist/assets/confirmAdd-CZPBG1xe.js +1 -0
- package/dist/assets/{contentVault-DzTYWcbD.js → contentVault-xfUwSJ3i.js} +1 -1
- package/dist/assets/coreIcons-BzqW7Qiz.js +1 -0
- package/dist/assets/cpp-CJIxL8VH.js +1 -0
- package/dist/assets/cpp-Cts1PyIS.js +1 -0
- package/dist/assets/csv-DAqzYXUs.js +5 -0
- package/dist/assets/dash-composer-DeNWVwpU.css +1 -0
- package/dist/assets/dashboardEvents-D-wLCp1A.js +2 -0
- package/dist/assets/dashboards-CdzGklae.css +1 -0
- package/dist/assets/dataPending-lZUzUEo6.js +1 -0
- package/dist/assets/{diagrams-CaSfjT4I.js → diagrams-1DJMD4j-.js} +1 -1
- package/dist/assets/display-BrieMea1.js +1 -0
- package/dist/assets/dist-DRo0JOkC.js +14 -0
- package/dist/assets/{dist-DIKAXwpM.js → dist-kNHRtoqd.js} +21 -21
- package/dist/assets/emphasize-BqCIst-B.js +1 -0
- package/dist/assets/empty-BO1NC9qY.js +1 -0
- package/dist/assets/engine-2U7mvPIl.js +1 -0
- package/dist/assets/engine-BF8FqSbi.css +1 -0
- package/dist/assets/explode-qQ7Fzt6V.js +15 -0
- package/dist/assets/facts-BUGuVUIc.js +1 -0
- package/dist/assets/fit-CMu7prjb.js +1 -0
- package/dist/assets/fitText-DQ2omSN0.js +1 -0
- package/dist/assets/format-q0LwBjID.js +1 -0
- package/dist/assets/{format-hc2QOoIu.js → format-rPI6ZwwH.js} +1 -1
- package/dist/assets/friendlyAsk-BBdRZIar.js +1 -0
- package/dist/assets/{generate-8odaTyr4.js → generate-C9vOL1C2.js} +3 -3
- package/dist/assets/generateBeats-DpDpBcgV.js +1 -0
- package/dist/assets/{generateCourse-Cj_-vDWu.js → generateCourse-DU281tDE.js} +1 -1
- package/dist/assets/generateLive-_x2tWkBH.js +51 -0
- package/dist/assets/githubBrowser-BDiuD9dz.js +1 -0
- package/dist/assets/githubToken-Bwa7V9YT.js +1 -0
- package/dist/assets/history-D2EH2X6D.js +1 -0
- package/dist/assets/homeTarget-CsO8nY7z.js +1 -0
- package/dist/assets/http-Lar_UMKb.js +2 -0
- package/dist/assets/{icons-CHVz6kv_.js → icons-gLFQTv74.js} +1 -1
- package/dist/assets/incident-D3bmMmES.js +10 -0
- package/dist/assets/index-CfcUMOBf.js +22 -0
- package/dist/assets/index-D4FIsool.css +1 -0
- package/dist/assets/index.es-yrxxdux0.js +5 -0
- package/dist/assets/jspdf.es.min-Bbaa2Qun.js +79 -0
- package/dist/assets/jsx-runtime-DeHZSEgm.js +1 -0
- package/dist/assets/katex-CiJ_n4H9.js +257 -0
- package/dist/assets/keyVault-Aw5Y2PjT.js +1 -0
- package/dist/assets/kokoro-CdL8Kl48.js +1 -0
- package/dist/assets/layout-CEoNLr-w.js +1 -0
- package/dist/assets/{layout-CkO0Psde.js → layout-CHn3XWJd.js} +1 -1
- package/dist/assets/learn-CXstDWJf.js +1 -0
- package/dist/assets/ledger-Cv0LBflx.js +1 -0
- package/dist/assets/lib-B7OE1ZQQ.js +1 -0
- package/dist/assets/liveSchema-B4bQtO88.js +100 -0
- package/dist/assets/maplibre-gl-CrDadnl3.js +801 -0
- package/dist/assets/maplibre-gl-worker-DZ7nj4vd.js +11 -0
- package/dist/assets/{mastery-D7xYf5D7.js → mastery-CUfDeuqO.js} +2 -2
- package/dist/assets/{media-CsrUl279.js → media-BvwzACIX.js} +1 -1
- package/dist/assets/{model-BE0UHu1w.js → model-DxwoIVpo.js} +1 -1
- package/dist/assets/motion-BY_Egaxm.js +1 -0
- package/dist/assets/motion-DxHSlPN6.js +1 -0
- package/dist/assets/{neighborhoods-DFqKm9Xi.js → neighborhoods-D7QjURnE.js} +1 -1
- package/dist/assets/nextFrame-12y0UrAd.js +1 -0
- package/dist/assets/notes-CUeZ1cYu.js +1 -0
- package/dist/assets/{number-DXgzss0v.js → number-Bmf7DqLj.js} +1 -1
- package/dist/assets/officeDoc-GU6Cssjf.js +3 -0
- package/dist/assets/openWorld-BHTJM39n.js +1 -0
- package/dist/assets/openchemlib-Cz_MN0FG.js +23 -0
- package/dist/assets/{owners-FXDGInVq.js → owners-HRBX7JN_.js} +1 -1
- package/dist/assets/parseDiff-D8uBQ9mQ.js +2 -0
- package/dist/assets/pdf-CUAVYiYW.js +54 -0
- package/dist/assets/pdf.worker.min-CHFwMXne.mjs +29 -0
- package/dist/assets/pen-BAEq0JnM.js +24 -0
- package/dist/assets/{perfProbe-Xs39DqMh.js → perfProbe-3Ip5n0yx.js} +1 -1
- package/dist/assets/{php-CYrBA5iX.js → php-CQT4wx5i.js} +1 -1
- package/dist/assets/pin-BwWjjqmt.js +1 -0
- package/dist/assets/pin-D-4Zjiik.css +1 -0
- package/dist/assets/planTracker-BI9z_0gW.js +1 -0
- package/dist/assets/portal-BJzn-Tgn.js +1 -0
- package/dist/assets/{pptxgen.es-CveAizg8.js → pptxgen.es-zw8PIOkD.js} +11 -11
- package/dist/assets/predictions-CkVKHq-5.js +1 -0
- package/dist/assets/preload-helper-CiWYd9n-.js +1 -0
- package/dist/assets/preloadableLazy-MIX1ApBW.js +1 -0
- package/dist/assets/{prewarm-K5WcvrNh.js → prewarm-CheeUP2L.js} +1 -1
- package/dist/assets/prism.generated-BQkO5r6r.js +41 -0
- package/dist/assets/{prismExtract.worker-Cws9K1NG.js → prismExtract.worker-OxGWMXXN.js} +1 -1
- package/dist/assets/prismGround.worker-C9hyveb3.js +1 -0
- package/dist/assets/prismLayout.worker-CJa4orCT.js +1 -0
- package/dist/assets/providers-B2OCzEo1.js +1 -0
- package/dist/assets/purify.es-JEAr64Sr.js +3 -0
- package/dist/assets/{queue-J4h7E3uc.js → queue-Adae4IzW.js} +1 -1
- package/dist/assets/quietHours-DCMczU9R.js +1 -0
- package/dist/assets/quizResult-DB8yeqDr.js +1 -0
- package/dist/assets/react-BZJXY1be.js +1 -0
- package/dist/assets/ready-Ba6nk9O1.js +1 -0
- package/dist/assets/ready-DZY1bETr.js +1 -0
- package/dist/assets/receipts-ClyzFFGD.js +1 -0
- package/dist/assets/{reference-sJzyMiL4.js → reference-BjexflMu.js} +1 -1
- package/dist/assets/registry-4mMEt1Xy.css +1 -0
- package/dist/assets/registry-7poQfBaM.js +4 -0
- package/dist/assets/registry-9QjeHgKs.js +1 -0
- package/dist/assets/registry-B0GIHERt.js +1 -0
- package/dist/assets/{registry-DpaaVbmL.css → registry-B1KQ1VPZ.css} +1 -1
- package/dist/assets/registry-B5S3brjM.css +1 -0
- package/dist/assets/registry-BFbfXK-W.js +1 -0
- package/dist/assets/registry-BM9FDQxO.js +1 -0
- package/dist/assets/registry-BRbEINOV.js +1 -0
- package/dist/assets/registry-BSX3aFUw.js +1 -0
- package/dist/assets/registry-BZuT2Epw.css +1 -0
- package/dist/assets/registry-Bv1f5UU4.js +2 -0
- package/dist/assets/registry-C28gYnVq.js +1 -0
- package/dist/assets/registry-CPImC7mO.js +1 -0
- package/dist/assets/registry-CPiwQhAm.js +1 -0
- package/dist/assets/registry-CcOO8UZr.js +1 -0
- package/dist/assets/registry-ChQGee7C.js +1 -0
- package/dist/assets/registry-Ci65uThi.js +1 -0
- package/dist/assets/{registry-upbw6pyj.css → registry-CuVk7MAI.css} +1 -1
- package/dist/assets/registry-CvylL2BN.css +1 -0
- package/dist/assets/registry-D4Xdd7dO.js +1 -0
- package/dist/assets/registry-D8O0apUT.js +2 -0
- package/dist/assets/registry-DLyrLfe-.js +1 -0
- package/dist/assets/registry-DO4hGO5e.js +1 -0
- package/dist/assets/{registry-Xzq_Rpmm.css → registry-DScSjt8p.css} +1 -1
- package/dist/assets/registry-D_4_HlMg.js +1 -0
- package/dist/assets/registry-Daypk4uR.js +1 -0
- package/dist/assets/registry-Dd1lcXrO.js +2 -0
- package/dist/assets/{registry-DWcNVyI2.css → registry-DpMI23iE.css} +1 -1
- package/dist/assets/registry-DuP_q42N.js +1 -0
- package/dist/assets/registry-Vp8VuMV0.js +9 -0
- package/dist/assets/registry-WHd1PwU3.js +1 -0
- package/dist/assets/registry-Xl8mAnKq.js +1 -0
- package/dist/assets/registry-tkd3UhWn.css +1 -0
- package/dist/assets/{registry-ei6fIgBT.css → registry-twSIyxJQ.css} +1 -1
- package/dist/assets/registry-types-D3q_LrlV.js +1 -0
- package/dist/assets/registry-w4R6c89s.js +48 -0
- package/dist/assets/{relate-CEND9Qlk.js → relate-BXcg3Ioz.js} +1 -1
- package/dist/assets/replay-rSsGKjEc.js +1 -0
- package/dist/assets/rolldown-runtime-DkW27tQK.js +1 -0
- package/dist/assets/route-D4kd-D3B.js +1 -0
- package/dist/assets/{ruby-BhrksQMt.js → ruby-D_UtGFHI.js} +1 -1
- package/dist/assets/run-CkaYNX89.js +23 -0
- package/dist/assets/run-aj7robML.js +21 -0
- package/dist/assets/run-ndUTOxjM.js +21 -0
- package/dist/assets/safeImageUrl-BINWXOTz.js +1 -0
- package/dist/assets/screen-DFWKge3-.js +1 -0
- package/dist/assets/search-ZN7v_P5B.js +1 -0
- package/dist/assets/seed-DN4mRJp-.js +1 -0
- package/dist/assets/shapes-C5fjibEc.js +42 -0
- package/dist/assets/shard005-Dp5TM33O.js +1 -0
- package/dist/assets/shard006-DpJfkjmW.js +1 -0
- package/dist/assets/shard007-CIQN8OfZ.js +1 -0
- package/dist/assets/shard008-BFiyL7r6.js +1 -0
- package/dist/assets/shard009-0s30Tkk9.js +1 -0
- package/dist/assets/shard010-DPhgF5ck.js +1 -0
- package/dist/assets/shard011-C2jVsC25.js +1 -0
- package/dist/assets/shard012-DYtN5yzJ.js +1 -0
- package/dist/assets/shard013-1D6_Qy9C.js +1 -0
- package/dist/assets/shard014-D8s7GHnm.js +1 -0
- package/dist/assets/shard015-16W6KgnL.js +1 -0
- package/dist/assets/shard016-B4PpWmro.js +1 -0
- package/dist/assets/shard017-BO1sA5b3.js +1 -0
- package/dist/assets/shard018-D4gn8z25.js +1 -0
- package/dist/assets/shard019-vSbfaqRA.js +1 -0
- package/dist/assets/shard020-DwbHP8bp.js +1 -0
- package/dist/assets/{shard021-2FE-tze4.js → shard021-BhEyVVAL.js} +1 -1
- package/dist/assets/shard022-BdT7zFy3.js +1 -0
- package/dist/assets/shard023-Dga_NQcm.js +1 -0
- package/dist/assets/shard024-CXHofcxc.js +1 -0
- package/dist/assets/shard025-a4CQKYw1.js +1 -0
- package/dist/assets/shard026-0rhLKfDL.js +1 -0
- package/dist/assets/shard027-C9GMfOtn.js +1 -0
- package/dist/assets/shard028-D9__rPnw.js +1 -0
- package/dist/assets/shard029-BSdYKGgG.js +1 -0
- package/dist/assets/shard030-DceOU7pS.js +1 -0
- package/dist/assets/shard031-C6_p076r.js +1 -0
- package/dist/assets/shard032-Cah16sJi.js +1 -0
- package/dist/assets/shard033-D-iobGzc.js +1 -0
- package/dist/assets/shard034-DIyfCKl8.js +1 -0
- package/dist/assets/shard035-BHWs8v0a.js +1 -0
- package/dist/assets/shard036-AhOPHqzq.js +1 -0
- package/dist/assets/shard037-CuAGDOOu.js +1 -0
- package/dist/assets/shard038-CYdtnPjK.js +1 -0
- package/dist/assets/shard039-DgvXKOyi.js +1 -0
- package/dist/assets/shard040-DO012waT.js +1 -0
- package/dist/assets/shard041-BeUicA1R.js +1 -0
- package/dist/assets/shard042-D2zbq14A.js +1 -0
- package/dist/assets/shard043-BKoTEB-H.js +1 -0
- package/dist/assets/shard044-bmYKfH3A.js +1 -0
- package/dist/assets/shard045-i_R1olD9.js +1 -0
- package/dist/assets/shard046-CFk2L0GQ.js +1 -0
- package/dist/assets/shard047-pjHCnVaT.js +1 -0
- package/dist/assets/shard048-Cc7tGz6R.js +1 -0
- package/dist/assets/shard049-C9eoD-6Z.js +1 -0
- package/dist/assets/shard050-V3c_ZDrB.js +1 -0
- package/dist/assets/shard051-D1ISwZzf.js +1 -0
- package/dist/assets/shard052-Dy09xx3S.js +1 -0
- package/dist/assets/shard053-Bi4Z4cwW.js +1 -0
- package/dist/assets/shard054-BoC-LNYu.js +1 -0
- package/dist/assets/shard055-D2NJeMN1.js +1 -0
- package/dist/assets/shard056-sSFMbxXN.js +1 -0
- package/dist/assets/shard057-DhNK5nyZ.js +1 -0
- package/dist/assets/shard058-Du4SjxeD.js +1 -0
- package/dist/assets/shard059-fGiLnJzG.js +1 -0
- package/dist/assets/shard060-l84MDY2t.js +1 -0
- package/dist/assets/shard061-B3aIa7Aa.js +1 -0
- package/dist/assets/{shard061-C9A8iNiq.js → shard062-BJ8OX6CJ.js} +1 -1
- package/dist/assets/shard063-CMo-7Qit.js +1 -0
- package/dist/assets/shard064-B0EEOnfG.js +1 -0
- package/dist/assets/shard065-D-StlUHp.js +1 -0
- package/dist/assets/share-kW3pZ027.js +1 -0
- package/dist/assets/shikiHighlight-BwX78OP8.js +153 -0
- package/dist/assets/speed-K5_Ebj-8.js +1 -0
- package/dist/assets/spokenText-C88IQJ0M.js +1 -0
- package/dist/assets/spreadLabels-CQ8hufvK.js +1 -0
- package/dist/assets/src-DG1n-LFe.js +1 -0
- package/dist/assets/store-B39HvB_l.js +1 -0
- package/dist/assets/store-BWLbFXiY.js +1 -0
- package/dist/assets/{store-BMRQiV1z.js → store-BfHRbVKz.js} +1 -1
- package/dist/assets/store-D-f8ZuaK.js +1 -0
- package/dist/assets/store-D2IJF4SA.js +0 -0
- package/dist/assets/store-DpObYU1u.js +1 -0
- package/dist/assets/store-gohr8YVT.js +1 -0
- package/dist/assets/{streamParse-DRgMHWye.js → streamParse-B-Gjwa9T.js} +1 -1
- package/dist/assets/svgLabel-BQMDdcT2.js +1 -0
- package/dist/assets/swift-CyEgAFGc.js +1 -0
- package/dist/assets/theme-7IrMJ70_.js +1 -0
- package/dist/assets/threads-Cu2t3070.js +1 -0
- package/dist/assets/tiles-CBiVVjtT.css +1 -0
- package/dist/assets/tiles-pdNi6MGe.js +1 -0
- package/dist/assets/types-C42I77wh.js +1 -0
- package/dist/assets/types-CaO6xOn5.js +1 -0
- package/dist/assets/useDashboardLoop-B_YA5jLs.js +5 -0
- package/dist/assets/useDashboards-GafZIADI.js +1 -0
- package/dist/assets/{useFocusTrap-DbfG6zbM.js → useFocusTrap-DBtkeyRy.js} +1 -1
- package/dist/assets/useInView-CXTOAEV3.js +1 -0
- package/dist/assets/useLedger-1WVXef68.js +1 -0
- package/dist/assets/useLiveConfig-DWz7BRdk.js +1 -0
- package/dist/assets/useSpatialCanvas-CfmZOXXP.js +1 -0
- package/dist/assets/useSpotlightWalk-DxlxBezO.js +1 -0
- package/dist/assets/useSrsCards-C27o39fF.js +1 -0
- package/dist/assets/useStudy-CFIuakaM.js +1 -0
- package/dist/assets/{useTimeout-BRYvu2jQ.js → useTimeout-Cm4yzted.js} +1 -1
- package/dist/assets/{useValidatedImage-D2fhA198.js → useValidatedImage-BQi2c66o.js} +1 -1
- package/dist/assets/useZoomGesture-CN0p0lHL.js +1 -0
- package/dist/assets/validate-CnG23_8J.js +1 -0
- package/dist/assets/verbatim-DBTj9sPD.js +1 -0
- package/dist/assets/walkSync-AAocUygp.js +1 -0
- package/dist/assets/worker-D7eK-Ya8.js +2 -0
- package/dist/demo-assets/CREDITS.md +75 -24
- package/dist/demo-assets/pdf/cfd-primer.pdf +0 -0
- package/dist/demo-assets/video/azores-film.webm +0 -0
- package/dist/fonts/LICENSE.txt +32 -28
- package/dist/fonts/OFL-1.1.txt +81 -0
- package/dist/fonts/PROVENANCE.md +38 -0
- package/dist/index.html +24 -17
- package/dist/legal/DISCLAIMER.md +4 -1
- package/dist/legal/PRIVACY.md +14 -8
- package/dist/legal/TERMS.md +11 -1
- package/dist/legal/THIRD-PARTY.txt +25248 -621
- package/dist/pdfjs/LICENSE_JBIG2 +196 -0
- package/dist/pdfjs/LICENSE_OPENJPEG +39 -0
- package/dist/pdfjs/LICENSE_PDFJS_JBIG2 +13 -0
- package/dist/pdfjs/LICENSE_PDFJS_OPENJPEG +22 -0
- package/dist/pdfjs/LICENSE_PDFJS_QCMS +22 -0
- package/dist/pdfjs/LICENSE_QCMS +21 -0
- package/dist/pdfjs/jbig2.wasm +0 -0
- package/dist/pdfjs/openjpeg.wasm +0 -0
- package/dist/pdfjs/qcms_bg.wasm +0 -0
- package/docker-compose.yml +40 -7
- package/docs/media/answer-ink.jpg +0 -0
- package/docs/media/canvas-view.jpg +0 -0
- package/docs/media/deck-export.jpg +0 -0
- package/docs/media/deep-zoom.jpg +0 -0
- package/docs/media/doc-export.jpg +0 -0
- package/docs/media/doc-prism.jpg +0 -0
- package/docs/media/repo-course.jpg +0 -0
- package/docs/media/think-map.jpg +0 -0
- package/docs/media/trip-plan.jpg +0 -0
- package/docs/media/voice-scrub.jpg +0 -0
- package/package.json +72 -60
- package/voice/start-whisper.sh +28 -0
- package/voice/whisper.Dockerfile +44 -0
- package/dist/assets/AppCommandPalette-B3E1gTd4.js +0 -1
- package/dist/assets/AtlasView-B8b67dk0.js +0 -1
- package/dist/assets/BlockEmpty-DQkdduUE.js +0 -1
- package/dist/assets/BriefingPlayer-CRKTlKa3.js +0 -1
- package/dist/assets/CanvasSkeleton-cQ6KF-6z.js +0 -2
- package/dist/assets/CardEditor-DzJXb0G7.js +0 -1
- package/dist/assets/CheckLogRail-C6nouD1Y.js +0 -1
- package/dist/assets/CheckLogRail-F4AlgAcc.css +0 -1
- package/dist/assets/CommandPalette-CSvgbXxg.js +0 -1
- package/dist/assets/CourseLessonReader-1KDKwxIj.js +0 -2
- package/dist/assets/CourseRail-BijCpApU.js +0 -1
- package/dist/assets/CoursesApp-BWkdYL07.js +0 -2
- package/dist/assets/CrossExamPanel-Cn7b5y7B.js +0 -1
- package/dist/assets/DashPresent-B025i7iJ.js +0 -1
- package/dist/assets/DashboardDetail-CZLnxgp0.js +0 -2
- package/dist/assets/DashboardLoopRuntime-7MpMUcMg.js +0 -1
- package/dist/assets/DashboardOverview-COyleu7v.js +0 -1
- package/dist/assets/DashboardSettings-DUfUqbsp.js +0 -1
- package/dist/assets/DashboardsApp-6xMz2qCP.js +0 -2
- package/dist/assets/DelegatePanel-D4OrMa2D.js +0 -33
- package/dist/assets/DemoGallery-Bt92vKqc.js +0 -1
- package/dist/assets/DropSelect-Q310fTbf.js +0 -1
- package/dist/assets/ExportModal-D0zXlC8w.js +0 -2
- package/dist/assets/ExtractionPreview-0SZYynDs.js +0 -18
- package/dist/assets/FeatureUseNotice-CoK5HkbR.js +0 -1
- package/dist/assets/FlagshipCTA-D845jkdt.js +0 -1
- package/dist/assets/FlagshipCommandPalette-DHMnyG7j.js +0 -1
- package/dist/assets/FlagshipShowcase-BuR3PZvU.js +0 -1
- package/dist/assets/FlashcardsApp-BzWb4cRP.js +0 -1
- package/dist/assets/ForecastPanel-lTnux0EB.js +0 -1
- package/dist/assets/GalleryApp-D0NGZ1_t.js +0 -1
- package/dist/assets/LegalApp-DXDomKFv.js +0 -1
- package/dist/assets/LegalPageShell-BG5UUk-9.js +0 -1
- package/dist/assets/LegalPageShell-C_HottbD.css +0 -1
- package/dist/assets/LeverPanel-CvYnTLjh.js +0 -1
- package/dist/assets/Library-Cl1gE9Qg.js +0 -1
- package/dist/assets/LibraryOverlay-CX4cJLqD.js +0 -1
- package/dist/assets/LiveApp-CDckMWYX.js +0 -61
- package/dist/assets/LiveApp-Dj_6EQuL.css +0 -1
- package/dist/assets/LiveSettings-DgfIXanM.js +0 -6
- package/dist/assets/MindMapViewerDrawer-ClU9wgSH.js +0 -1
- package/dist/assets/MindShape-DjHtMW_5.css +0 -1
- package/dist/assets/MindShape-yF19n9qq.js +0 -1
- package/dist/assets/PinToDashboard-CpIDAcIU.js +0 -1
- package/dist/assets/PlanReview-CPcqOxjp.js +0 -1
- package/dist/assets/Presence-CHGZ1JRp.js +0 -1
- package/dist/assets/PresentationDeck-CrtiWjiM.js +0 -1
- package/dist/assets/PrismApp-D7RbekoX.js +0 -2
- package/dist/assets/PrismAskController-D6_7Epdb.js +0 -37
- package/dist/assets/PrismBriefingPlayer-Dq5_KRU3.js +0 -2
- package/dist/assets/PrismOverlay-CduGpA8D.js +0 -131
- package/dist/assets/Quiz-CUwtekfu.js +0 -1
- package/dist/assets/Recap-BPg2xEPo.js +0 -1
- package/dist/assets/ReelJelly-LWeMsFpj.js +0 -1
- package/dist/assets/ReplayCard-C3dGQfxG.js +0 -2
- package/dist/assets/ReplayOverlay-C9W603B5.js +0 -1
- package/dist/assets/RewindOverlay-BIWmxQlx.js +0 -1
- package/dist/assets/RippleApp-C9-KFvkn.js +0 -2
- package/dist/assets/RippleAskController-DEKz-6Vn.js +0 -34
- package/dist/assets/RippleOverlay-CfXvnUHE.js +0 -6
- package/dist/assets/SeeDontRead-DrG1qBxJ.js +0 -1
- package/dist/assets/ShareModal-eJ6sdMpf.js +0 -32
- package/dist/assets/ShipCascade-BP8qL0yM.js +0 -1
- package/dist/assets/ShipCourse-BoqW58VU.js +0 -1
- package/dist/assets/ShipHotspots-_9XPhZg2.js +0 -1
- package/dist/assets/ShipMigration-BdkaiJ9D.js +0 -1
- package/dist/assets/ShipOnboarding-CblWatXR.js +0 -1
- package/dist/assets/ShipRead-BBn7xkOF.js +0 -1
- package/dist/assets/ShipRollout-i5BY3YnP.js +0 -1
- package/dist/assets/ShipSuggestions-liytLgC-.js +0 -1
- package/dist/assets/ShipWorkspace-C3VQwGn1.js +0 -2
- package/dist/assets/SignatureLoop-Ba7plTb5.js +0 -1
- package/dist/assets/SrsReview-BoaYb6XN.js +0 -1
- package/dist/assets/SrsReview-DmGdGxT0.css +0 -1
- package/dist/assets/SynthesisApp-Ch0tWRBS.js +0 -2
- package/dist/assets/SynthesisOverlay-DMZndCzV.js +0 -66
- package/dist/assets/TopicCanvas-DX0Z1ZHv.js +0 -2
- package/dist/assets/TourPrism-6fWPMU4Z.js +0 -1
- package/dist/assets/TrackerTile-BboQpBGy.js +0 -2
- package/dist/assets/TwoSurfaces-Cabk1rES.js +0 -1
- package/dist/assets/UnderstoodPanel-B6jfiKx1.js +0 -1
- package/dist/assets/WhyMachineOverlay-BRNibJSf.js +0 -1
- package/dist/assets/WowFeatures-C7f4qzIf.js +0 -1
- package/dist/assets/ZoomDeck-BtlVyhwv.js +0 -1
- package/dist/assets/__vite-browser-external-BufR4LQa.js +0 -1
- package/dist/assets/alternateFinishes-CVUX4x0C.js +0 -494
- package/dist/assets/annotationAuto-BjWqgseH.js +0 -1
- package/dist/assets/annotationReel-B5A2RZkx.js +0 -1
- package/dist/assets/annotations-D2K9A5GB.js +0 -1
- package/dist/assets/backup-d46KwktS.js +0 -1
- package/dist/assets/blockLabel-DAqaHKy3.js +0 -1
- package/dist/assets/cache-BumECILO.js +0 -1
- package/dist/assets/canvas-BuMP6u6i.js +0 -1
- package/dist/assets/catalog-Bv0dWU_C.js +0 -1
- package/dist/assets/chapters-Cbe53c3W.js +0 -1
- package/dist/assets/charts2-tyUiQPff.js +0 -1
- package/dist/assets/chunk-BVpWp9h4.js +0 -1
- package/dist/assets/confirmAdd-CWWtX1VN.js +0 -1
- package/dist/assets/cpp-BGdv8dzs.js +0 -1
- package/dist/assets/cpp-CNAAXZl-.js +0 -1
- package/dist/assets/dashboardEvents-Be4sftHN.js +0 -2
- package/dist/assets/dashboards-rcWxdoXI.css +0 -1
- package/dist/assets/dist-xRGLOZwv.js +0 -14
- package/dist/assets/explode-WBykfhqW.js +0 -13
- package/dist/assets/facts-BBTt3ImG.js +0 -1
- package/dist/assets/fit-CuHWhwsj.js +0 -1
- package/dist/assets/fitText-CDFmCQzl.js +0 -1
- package/dist/assets/format-DlZTyeMy.js +0 -1
- package/dist/assets/generateBeats-b64CL54v.js +0 -1
- package/dist/assets/generateLive-CMbGT3eM.js +0 -52
- package/dist/assets/githubBrowser-DywfDeYx.js +0 -1
- package/dist/assets/githubToken-DtcLYqwm.js +0 -11
- package/dist/assets/homeTarget-BcZYH3DY.js +0 -1
- package/dist/assets/http-CJCtjYpA.js +0 -2
- package/dist/assets/index-CepQEz75.css +0 -1
- package/dist/assets/index-Dbr1j8Fe.js +0 -22
- package/dist/assets/index.es-CRLiWwiA.js +0 -5
- package/dist/assets/jspdf.es.min-ydC1TxUW.js +0 -79
- package/dist/assets/jsx-runtime-DaSxXjOY.js +0 -1
- package/dist/assets/katex-BMCG0xok.js +0 -257
- package/dist/assets/keyVault-DEsNh9FR.js +0 -1
- package/dist/assets/kokoro-DsmNzulR.js +0 -1
- package/dist/assets/layout-BFQOzXtG.js +0 -1
- package/dist/assets/leaflet-src-C_xhOQY7.js +0 -1
- package/dist/assets/learn-DVfqN-nf.js +0 -1
- package/dist/assets/lib-B6qSkBPa.js +0 -1
- package/dist/assets/liveSchema-B1MGdSkK.js +0 -99
- package/dist/assets/motion-luJxBPnj.js +0 -1
- package/dist/assets/notes-3WQ6b0Mi.js +0 -1
- package/dist/assets/officeDoc-B6nEhNp4.js +0 -3
- package/dist/assets/openchemlib-nMLMmg26.js +0 -23
- package/dist/assets/pdf-RyoPCIGN.js +0 -11
- package/dist/assets/pdf.worker.min-yatZIOMy.mjs +0 -21
- package/dist/assets/pin-Bya3BL_a.css +0 -1
- package/dist/assets/pin-Cj-LMfpK.js +0 -1
- package/dist/assets/planTracker-7AMCQPNx.js +0 -1
- package/dist/assets/portal-zyqZwnb1.js +0 -1
- package/dist/assets/predictions-CYS7Vo39.js +0 -1
- package/dist/assets/prism.generated-BhbHDHR6.js +0 -41
- package/dist/assets/prismGround.worker-CIvKqxm2.js +0 -1
- package/dist/assets/prismLayout.worker-CZO2CY7B.js +0 -1
- package/dist/assets/providers-wzm7E8Pa.js +0 -1
- package/dist/assets/purify.es-adlwq8Pz.js +0 -3
- package/dist/assets/quietHours-BklvMqsV.js +0 -1
- package/dist/assets/react-BQSORdFI.js +0 -1
- package/dist/assets/registry-1h9idbfk.js +0 -2
- package/dist/assets/registry-2zthbrHC.js +0 -1
- package/dist/assets/registry-4O5l9cd5.js +0 -1
- package/dist/assets/registry-5a-E7vEN.css +0 -1
- package/dist/assets/registry-BRB85vr4.js +0 -2
- package/dist/assets/registry-BVHiKEwE.css +0 -1
- package/dist/assets/registry-BcZXBr3y.css +0 -1
- package/dist/assets/registry-BdMZ_4cm.js +0 -2
- package/dist/assets/registry-Bnp_yh8G.js +0 -4
- package/dist/assets/registry-C1IrZBk8.js +0 -1
- package/dist/assets/registry-C5DK98Hl.js +0 -1
- package/dist/assets/registry-CK0-re_Q.js +0 -49
- package/dist/assets/registry-COrl_Heq.js +0 -1
- package/dist/assets/registry-CQUQlrSx.js +0 -1
- package/dist/assets/registry-CXa3qXl3.js +0 -1
- package/dist/assets/registry-C_baBbqq.js +0 -5
- package/dist/assets/registry-CjY5POtx.js +0 -1
- package/dist/assets/registry-CoBAqOlY.js +0 -1
- package/dist/assets/registry-D5oMqeSa.js +0 -1
- package/dist/assets/registry-DJj-o3MQ.js +0 -1
- package/dist/assets/registry-DVzLacl_.css +0 -1
- package/dist/assets/registry-DfCCnIfu.js +0 -1
- package/dist/assets/registry-DfgFkD3J.js +0 -1
- package/dist/assets/registry-Dhlx1mF4.js +0 -1
- package/dist/assets/registry-Dkc7hN5T.js +0 -1
- package/dist/assets/registry-DmQlNN3y.js +0 -1
- package/dist/assets/registry-DnEh7nbX.js +0 -1
- package/dist/assets/registry-VD94nLXO.js +0 -1
- package/dist/assets/registry-aIH-Im5Y.css +0 -1
- package/dist/assets/registry-mFD4P5dI.js +0 -1
- package/dist/assets/registry-sDzDmht4.js +0 -1
- package/dist/assets/registry-types-DMuK0vJ6.js +0 -1
- package/dist/assets/run-BYP2YlZT.js +0 -23
- package/dist/assets/run-DSVvshaB.js +0 -21
- package/dist/assets/run-Dc2ZJz6n.js +0 -21
- package/dist/assets/safeImageUrl-CUkucDUu.js +0 -1
- package/dist/assets/screen-DLR7p_yP.js +0 -1
- package/dist/assets/search-Be63DJkp.js +0 -1
- package/dist/assets/shapes-Cw7tCHIp.js +0 -1
- package/dist/assets/shard005-DLVkh9IH.js +0 -1
- package/dist/assets/shard006-B6efKHov.js +0 -1
- package/dist/assets/shard007-AFdZLe38.js +0 -1
- package/dist/assets/shard008-LbSBzwRx.js +0 -1
- package/dist/assets/shard009-D_6-SUDb.js +0 -1
- package/dist/assets/shard010-DbOj-uZW.js +0 -1
- package/dist/assets/shard011-BYSz7EEW.js +0 -1
- package/dist/assets/shard012-B5Ypj7OV.js +0 -1
- package/dist/assets/shard013-BtsliNIe.js +0 -1
- package/dist/assets/shard014-15sjmk68.js +0 -1
- package/dist/assets/shard015-nnXrqru_.js +0 -1
- package/dist/assets/shard016-BayXFE13.js +0 -1
- package/dist/assets/shard017-Cy4cGexs.js +0 -1
- package/dist/assets/shard018-aO-BYJ8H.js +0 -1
- package/dist/assets/shard019-gxaTeA3I.js +0 -1
- package/dist/assets/shard020-BibJdMI0.js +0 -1
- package/dist/assets/shard022-IXiyG-JK.js +0 -1
- package/dist/assets/shard023-314F6NJS.js +0 -1
- package/dist/assets/shard024-cN5rpQ_X.js +0 -1
- package/dist/assets/shard025-KKTaXOGE.js +0 -1
- package/dist/assets/shard026-C2Dkd1t6.js +0 -1
- package/dist/assets/shard027-Xy-8x9As.js +0 -1
- package/dist/assets/shard028-Bul-klUj.js +0 -1
- package/dist/assets/shard029-BbRSUcUZ.js +0 -1
- package/dist/assets/shard030-GYllsFVC.js +0 -1
- package/dist/assets/shard031-DMigeiyn.js +0 -1
- package/dist/assets/shard032-CcvmzK0l.js +0 -1
- package/dist/assets/shard033-11AU702M.js +0 -1
- package/dist/assets/shard034-Bx3urxjM.js +0 -1
- package/dist/assets/shard035-DBdEeyCt.js +0 -1
- package/dist/assets/shard036-vYgoRBqS.js +0 -1
- package/dist/assets/shard037-DP4MMw91.js +0 -1
- package/dist/assets/shard038-ffxsv7d6.js +0 -1
- package/dist/assets/shard039-C1JHHNp9.js +0 -1
- package/dist/assets/shard040-JbVvCSO_.js +0 -1
- package/dist/assets/shard041-5L_eFwGx.js +0 -1
- package/dist/assets/shard042-C9nsGL79.js +0 -1
- package/dist/assets/shard043-Dx_9HSKI.js +0 -1
- package/dist/assets/shard044-B3QQNC4A.js +0 -1
- package/dist/assets/shard045-B7z0WHO6.js +0 -1
- package/dist/assets/shard046-D1yDablJ.js +0 -1
- package/dist/assets/shard047-DJi3AgeT.js +0 -1
- package/dist/assets/shard048-D_2ipfUr.js +0 -1
- package/dist/assets/shard049-1aGgWZdd.js +0 -1
- package/dist/assets/shard050-Bjwa0Og4.js +0 -1
- package/dist/assets/shard051-Cx_GAk3v.js +0 -1
- package/dist/assets/shard052-LaeOD3V5.js +0 -1
- package/dist/assets/shard053-D-da7Foj.js +0 -1
- package/dist/assets/shard054-CM8eSRQk.js +0 -1
- package/dist/assets/shard055-QRpDl4Vs.js +0 -1
- package/dist/assets/shard056-DkY7CQm3.js +0 -1
- package/dist/assets/shard057-BVCgf7o0.js +0 -1
- package/dist/assets/shard058-93aGtdrX.js +0 -1
- package/dist/assets/shard059-rJE9X1_I.js +0 -1
- package/dist/assets/shard060-Lu_hfl1r.js +0 -1
- package/dist/assets/shard062-BBIpEYZO.js +0 -1
- package/dist/assets/shard063-C_uen3Ub.js +0 -1
- package/dist/assets/shard064-DAHUsHST.js +0 -1
- package/dist/assets/share-QHGHNDhQ.js +0 -1
- package/dist/assets/shikiHighlight-SCFIB43b.js +0 -153
- package/dist/assets/speed-DwPw9KSv.js +0 -1
- package/dist/assets/spokenText-D4zPX9JY.js +0 -1
- package/dist/assets/src-B-t8Mww-.js +0 -2
- package/dist/assets/store-DXmC_fP2.js +0 -0
- package/dist/assets/store-Dn23_Ymr.js +0 -1
- package/dist/assets/store-DoJn3lBF.js +0 -1
- package/dist/assets/store-DrBDvqXF.js +0 -1
- package/dist/assets/swift-DonLKvLd.js +0 -1
- package/dist/assets/threads-CkMgrSDP.js +0 -1
- package/dist/assets/useDashboardLoop-C8Mcbcto.js +0 -5
- package/dist/assets/useLiveConfig-BW1WkpTc.js +0 -1
- package/dist/assets/useSpatialCanvas-C5TNlpeK.js +0 -1
- package/dist/assets/useSpotlightWalk-dA3IdI-1.js +0 -1
- package/dist/assets/useSrsCards-C7Xni9C0.js +0 -1
- package/dist/assets/useStudy-DHRIx8p-.js +0 -1
- package/dist/assets/useZoomGesture-BsPXvLw2.js +0 -1
- package/dist/assets/verbatim-CBMzUDlf.js +0 -1
- package/dist/assets/worker-BbLKfGzm.js +0 -2
- package/dist/demo-assets/video/azores-film.mp4 +0 -0
- /package/dist/assets/{shard065-C2edvdvh.js → shard066-C2edvdvh.js} +0 -0
- /package/dist/assets/{shard066-DFcuVhZm.js → shard067-DFcuVhZm.js} +0 -0
- /package/dist/assets/{shard067-BN8DM8JZ.js → shard068-BN8DM8JZ.js} +0 -0
- /package/dist/assets/{shard068-i464K77p.js → shard069-i464K77p.js} +0 -0
- /package/dist/assets/{shard069-Dm9m2a5U.js → shard070-Dm9m2a5U.js} +0 -0
- /package/dist/assets/{shard070-BPVvR8GH.js → shard071-BPVvR8GH.js} +0 -0
- /package/dist/assets/{shard071-Bal_0d9L.js → shard072-Bal_0d9L.js} +0 -0
- /package/dist/assets/{shard072-CBQu62kt.js → shard073-CBQu62kt.js} +0 -0
- /package/dist/assets/{shard073-D5BRae0w.js → shard074-D5BRae0w.js} +0 -0
- /package/dist/assets/{shard074-DtFvcBnZ.js → shard075-DtFvcBnZ.js} +0 -0
- /package/dist/assets/{queue-DHeyJ32F.css → templates-DHeyJ32F.css} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{i as e,t}from"./chunk-BVpWp9h4.js";import{J as n,q as r}from"./index-Dbr1j8Fe.js";var i=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.baseAssetPath=void 0;var t=typeof window<`u`&&window.document!==void 0?window.document.currentScript:null,n=`/`;t&&(n=t.src.replace(/#.*$/,``).replace(/\?.*$/,``).replace(/\/[^/]+$/,`/`)),e.baseAssetPath=n})),a=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultModelFetcher=void 0,e.defaultModelFetcher=e=>fetch(e).then(e=>e.arrayBuffer())})),o=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.log=void 0;var t=e=>t=>{console.log(`VAD | ${e} >`,t)};e.log={error:t(`error`),debug:t(`debug`),warn:t(`warn`)}})),s=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=void 0;var t;(function(e){e.AudioFrame=`AUDIO_FRAME`,e.SpeechStart=`SPEECH_START`,e.VADMisfire=`VAD_MISFIRE`,e.SpeechEnd=`SPEECH_END`,e.SpeechStop=`SPEECH_STOP`,e.SpeechRealStart=`SPEECH_REAL_START`,e.FrameProcessed=`FRAME_PROCESSED`})(t||(e.Message=t={}))})),c=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FrameProcessor=e.validateOptions=e.defaultFrameProcessorOptions=void 0;var t=o(),n=s();e.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(e){(e.positiveSpeechThreshold<0||e.positiveSpeechThreshold>1)&&t.log.error(`positiveSpeechThreshold should be a number between 0 and 1`),(e.negativeSpeechThreshold<0||e.negativeSpeechThreshold>e.positiveSpeechThreshold)&&t.log.error(`negativeSpeechThreshold should be between 0 and positiveSpeechThreshold`),e.preSpeechPadMs<0&&t.log.error(`preSpeechPadMs should be positive`),e.redemptionMs<0&&t.log.error(`redemptionMs should be positive`),e.minSpeechMs<0&&t.log.error(`minSpeechMs should be positive`)}e.validateOptions=r;var i=e=>{let t=e.reduce((e,t)=>(e.push(e.at(-1)+t.length),e),[0]),n=new Float32Array(t.at(-1));return e.forEach((e,r)=>{let i=t[r];n.set(e,i)}),n};function a(e,t){return{redemptionFrames:Math.floor(e.redemptionMs/t),preSpeechPadFrames:Math.floor(e.preSpeechPadMs/t),minSpeechFrames:Math.floor(e.minSpeechMs/t)}}e.FrameProcessor=class{constructor(e,t,r,o){this.modelProcessFunc=e,this.modelResetFunc=t,this.options=r,this.msPerFrame=o,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=e=>{this.options={...this.options,...e};let{redemptionFrames:t,preSpeechPadFrames:n,minSpeechFrames:r}=a(this.options,this.msPerFrame);this.redemptionFrames=t,this.preSpeechPadFrames=n,this.minSpeechFrames=r},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{let t=this.audioBuffer;this.audioBuffer=[];let r=this.speaking;if(this.reset(),r)if(t.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){let r=i(t.map(e=>e.frame));e({msg:n.Message.SpeechEnd,audio:r})}else e({msg:n.Message.VADMisfire});return{}},this.process=async(e,t)=>{if(!this.active)return;let r=await this.modelProcessFunc(e),a=r.isSpeech>=this.options.positiveSpeechThreshold;if(t({probs:r,msg:n.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:a}),a&&(this.speechFrameCount++,this.redemptionCounter=0),a&&!this.speaking&&(this.speaking=!0,t({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,t({msg:n.Message.SpeechRealStart})),r.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;let e=this.audioBuffer;if(this.audioBuffer=[],e.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){let r=i(e.map(e=>e.frame));t({msg:n.Message.SpeechEnd,audio:r})}else t({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];let{redemptionFrames:s,preSpeechPadFrames:c,minSpeechFrames:l}=a(this.options,this.msPerFrame);this.redemptionFrames=s,this.preSpeechPadFrames=c,this.minSpeechFrames=l,this.reset()}}})),l=t(((t,i)=>{n();var a=(()=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),s=(e,t)=>()=>(e&&(t=e(e=0)),t),c=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},l=(e,r,o,s)=>{if(r&&typeof r==`object`||typeof r==`function`)for(let c of i(r))!a.call(e,c)&&c!==o&&t(e,c,{get:()=>r[c],enumerable:!(s=n(r,c))||s.enumerable});return e},u=e=>l(t({},`__esModule`,{value:!0}),e),d,f,p,m,h,g=s(()=>{d=new Map,f=[],p=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}return}throw TypeError(`not a valid backend`)},m=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},h=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=new Set;for(let e of r){let t=await m(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),_=s(()=>{g()}),v,y=s(()=>{v=`1.26.0`}),b,x,S=s(()=>{y(),b=`warning`,x={wasm:{},webgl:{},webgpu:{},versions:{common:v},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);b=e}},get logLevel(){return b}},Object.defineProperty(x,"logLevel",{enumerable:!0})}),C,w=s(()=>{S(),C=x}),T,E,ee=s(()=>{T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},E=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),D,O,te,ne,re,ie,ae=s(()=>{me(),D=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new k(`float32`,u,[1,4,n,r]):new k(`float32`,u,[1,3,n,r])},O=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,D(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(D(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return D(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new k({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},re=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ie=(e,t,n)=>new k({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),oe,se,ce,le,ue=s(()=>{oe=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),se=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ce=!1,le=()=>{if(!ce){ce=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(oe.set(`int64`,BigInt64Array),se.set(BigInt64Array,`int64`)),t&&(oe.set(`uint64`,BigUint64Array),se.set(BigUint64Array,`uint64`)),r?(oe.set(`float16`,n),se.set(n,`float16`)):oe.set(`float16`,Uint16Array)}}}),de,fe,pe=s(()=>{me(),de=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},fe=(e,t)=>{switch(e.location){case`cpu`:return new k(e.type,e.data,t);case`cpu-pinned`:return new k({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new k({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new k({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new k({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),k,me=s(()=>{ee(),ae(),ue(),pe(),k=class{constructor(e,t,n){le();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=oe.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=oe.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=se.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=de(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return O(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return re(e,t)}static fromPinnedBuffer(e,t,n){return ie(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return E(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return fe(this,e)}}}),A,he=s(()=>{me(),A=k}),ge,_e,j,M,ve,ye,be=s(()=>{S(),ge=(e,t)=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeStamp(`${e}::ORT::${t}`)},_e=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ge(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},j=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`BEGIN`,e)},M=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`END`,e)},ve=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.time(`ORT::${e}`)},ye=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeEnd(`ORT::${e}`)}}),xe,Se=s(()=>{g(),he(),be(),xe=class e{constructor(e){this.handler=e}async run(e,t,n){j(),ve(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof A||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof A)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof A)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof A?s[e]=t:s[e]=new A(t.type,t.data,t.dims)}return ye(`InferenceSession.run`),M(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){j(),ve(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await h(o),l=await s.createInferenceSessionHandler(a,c);return ye(`InferenceSession.create`),M(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ce,we=s(()=>{Se(),Ce=xe}),Te=s(()=>{}),Ee=s(()=>{}),De=s(()=>{}),Oe=s(()=>{}),ke={};c(ke,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,env:()=>C,registerBackend:()=>p});var N=s(()=>{_(),w(),we(),he(),Te(),Ee(),be(),De(),Oe()}),Ae=s(()=>{}),je={};c(je,{default:()=>Pe});var Me,Ne,Pe,Fe=s(()=>{zu(),rt(),Je(),Me=`ort-wasm-proxy-worker`,Ne=globalThis.self?.name===Me,Ne&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:nt(n.wasm).then(()=>{Du(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Ou(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Mu(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;Nu(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Pu(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Iu(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Ru([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Lu(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),Pe=Ne?null:e=>new Worker(e??P,{type:`classic`,name:Me})}),Ie,Le,P,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je=s(()=>{Ae(),Ie=typeof location>`u`?void 0:location.origin,Le=()=>typeof document<`u`?document.currentScript?.src:typeof self<`u`?self.location?.href:void 0,P=Le(),Re=()=>{if(P&&!P.startsWith(`blob:`))return P.substring(0,P.lastIndexOf(`/`)+1)},ze=(e,t)=>{try{let n=t??P;return(n?new URL(e,n):new URL(e)).origin===Ie}catch{return!1}},Be=(e,t)=>{let n=t??P;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Ve=(e,t)=>`${t??`./`}${e}`,He=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Ue=async e=>(await r(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,We=(Fe(),u(je)).default,Ge=async()=>{if(!P)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(ze(P))return[void 0,We()];let e=await He(P);return[e,We(e)]},Ke=void 0,qe=async(e,t,n,r)=>{let i=Ke&&!(e||t);if(i)if(P)i=ze(P)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,Ke];{let r=`ort-wasm-simd-threaded.jsep.mjs`,i=e??Be(r,t),a=n&&i&&!ze(i,t),o=a?await He(i):i??Ve(r,t);return[a?o:void 0,await Ue(o)]}}}),Ye,Xe,Ze,Qe,$e,et,tt,nt,F,rt=s(()=>{Je(),Xe=!1,Ze=!1,Qe=!1,$e=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},et=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nt=async e=>{if(Xe)return Promise.resolve();if(Ze)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Qe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Ze=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!tt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!et())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=$e();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await qe(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Re();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Ze=!1,Xe=!0,Ye=t,e(),d&&URL.revokeObjectURL(d)},e=>{Ze=!1,Qe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Xe&&Ye)return Ye;throw Error(`WebAssembly is not initialized yet.`)}}),I,it,L,at=s(()=>{rt(),I=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},it=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)it(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},L=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),ot,st=s(()=>{rt(),at(),ot=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=I(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&L(`Can't create run options.`),e?.extra!==void 0&&it(e.extra,``,new WeakSet,(e,i)=>{let a=I(e,r),o=I(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&L(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ct,lt,ut,dt,ft,pt,mt=s(()=>{rt(),at(),ct=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},lt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ut=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},dt=(e,t,n,r)=>{let i=I(t,r),a=I(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&L(`Can't set a session config entry: ${t} - ${n}.`)},ft=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,dt(e,`session.disable_quant_qdq`,`1`,n),dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof t!=`string`){let r=t?.deviceType;r&&dt(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);dt(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=I(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&L(`Can't append execution provider: ${r}.`)}},pt=async e=>{let t=F(),n=0,r=[],i=e||{};ut(i);try{let e=ct(i.graphOptimizationLevel??`all`),a=lt(i.executionMode??`sequential`),o=typeof i.logId==`string`?I(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?I(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&L(`Can't create session options.`),i.executionProviders&&await ft(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=I(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&L(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&it(i.extra,``,new WeakSet,(e,t)=>{dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&L(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ht,gt,_t,vt,yt,bt,xt,St,R=s(()=>{ht=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},_t=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},vt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},yt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,xt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,St=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ct,wt=s(()=>{Ae(),Ct=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Tt,Et,Dt,Ot,kt,At,z,jt=s(()=>{R(),Tt=[`V`,`I`,`W`,`E`,`F`],Et=(e,t)=>{console.log(`[${Tt[e]},${new Date().toISOString()}]${t}`)},kt=(e,t)=>{Dt=e,Ot=t},At=(e,t)=>{let n=yt(e);n>=yt(Dt)&&Et(n,typeof t==`function`?t():t)},z=(...e)=>{Ot&&At(...e)}}),Mt,Nt,B,Pt,Ft,It,Lt,V=s(()=>{Mt=class{static calcMatMulShape(e,t){return e[1]===t[0]?[e[0],t[1]]:void 0}},Nt=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(r===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=Array(a);if(n){if(r<2||i<2)return;let n=Mt.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(n===void 0)return;[o[a-2],o[a-1]]=n}for(let s=n?3:1;s<=a;s++){let n=r-s<0?1:e[r-s],c=i-s<0?1:t[i-s];if(n!==c&&n>1&&c>1)return;let l=Math.max(n,c);if(n&&c)o[a-s]=Math.max(n,c);else{if(l>1)return;o[a-s]=0}}return o}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(e[n-i]!==1&&e[n-i]!==t[r-i])return!1;return!0}},B=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(n===0)return[];let r=Array(n),i=n-1;for(;i>=0;){if(e[i]%t===0){r[i]=e[i]/t;break}if(t%e[i]!==0)throw Error(`cannot convert shape`);r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<0)throw Error(`cannot get valid size from specified dimension range. Most likely the range contains negative values in them.`);r*=Number(e[i])}return r}static computeStrides(e){let t=e.length;if(t===0)return[];if(t===1)return[1];let n=Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw Error(`unsupported axis for this operation.`);return e<0?e+t:e}static normalizeAxes(e,t){return e.map(n=>this.normalizeAxis(n,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(t=>e[t]):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map((e,r)=>e+t[r]+t[r+n])}static areEqual(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}},Pt=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw Error(`length of specified kernel shapes should be 2 less than length of input dimensions`);if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw Error(`strides should be greater than or equal to 1`)}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw Error(`dilations should be greater than or equal to 1`)}else i.push(1);for(let e=0;e<n.length*2;e++)if(e<a.length){if(a[e]<0)throw Error(`pad should be greater than or equal to 1`)}else a.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw Error(`kernel shapes need to be greater than 0`);if(a[e]>=n[e]||a[e+n.length]>=n[e])throw Error(`pads should be smaller than kernel`)}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,o,s){if(s){if(a.length!==2*(t.length-2))throw Error(`length of pads should be twice the length of data dimensions`);if(n.length!==t.length-2)throw Error(`length of strides should be the length of data dimensions`);if(i.length!==t.length-2)throw Error(`length of kernel shapes should be the length of data dimensions`);for(let c=0;c<t.length-2;c++)e.adjustPadAndReturnShape(t[c+(o?1:2)],n[c],r[c],i[c],a,c,c+t.length-2,s)}}static computePoolOutputShape(t,n,r,i,a,o,s){if(n.length<=0)throw Error(`input shape must be of size greater than 0`);let c=[n[0],n[1]];return e.computeShapeHelper(t,n,c,r,i,a,o,s),c}static computeConvOutputShape(t,n,r,i,a,o,s){if(t.length<=0||n.length<=0)throw Error(`invalid input tensor dims or invalid filter tensor dims`);let c=[t[0],n[0]];return e.computeShapeHelper(!1,t,c,r,i,a,o,s),c}static computeShapeHelper(t,n,r,i,a,o,s,c){if(t)for(let e=0;e<n.length-2;e++)r.push(1);else for(let t=0;t<n.length-2;t++)r.push(e.adjustPadAndReturnShape(n[t+2],i[t],a[t],o[t],s,t,t+n.length-2,c))}static adjustPadAndReturnShape(e,t,n,r,i,a,o,s){let c=n*(r-1)+1;if(s&&s!==`NOTSET`)switch(s){case`VALID`:return i[a]=0,i[o]=0,Math.floor((e-c)/t+1);case`SAME_LOWER`:case`SAME_UPPER`:if(n!==1)throw Error(`Dilation not supported for SAME_UPPER or SAME_LOWER`);{let n=((e+t-1)/t-1)*t+r-e;return i[a]=Math.floor(s===`SAME_LOWER`?(n+1)/2:n/2),i[o]=n-i[a],Math.floor((e+n-r)/t+1)}default:throw Error(`Unsupported AutoPad type`)}else return Math.floor((e+i[a]+i[o]-c)/t+1)}},Ft=class{static getShapeOfGemmResult(e,t,n,r,i){if(e.length!==2||n.length!==2)throw Error(`shape need to be of size 2`);let a,o,s;t?(a=e[1],o=e[0]):(a=e[0],o=e[1]);let c=-1;if(r?(s=n[0],c=1):(s=n[1],c=0),n[c]!==o)throw Error(`dimension mismatch`);if(a<=0||s<=0||o<=0)throw Error(`invalid shape specified`);if(i&&!Nt.isValidBroadcast(i,[a,s]))throw Error(`gemm: invalid bias shape for broadcast`);return[a,s,o]}},It=-34028234663852886e22,Lt=34028234663852886e22}),Rt,zt=s(()=>{R(),Rt=(e,t)=>new(vt(t))(e)}),Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt=s(()=>{R(),jt(),Bt=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Vt=(e,t)=>{if(t===`int32`)return e;let n=Bt.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(vt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Ht=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Ut=1,Wt=()=>Ut++,Gt=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),Kt=(e,t)=>{let n=Bt.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},qt=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Kt(this.dataType,this.tensorShape)}destroy(){z(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Ht(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Jt=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Gt.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);z(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Kt(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType===`int32`)t=Vt(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else z(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Ht(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},Yt=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Wt();return this.tensorTrackersById.set(e,new Jt(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){z(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){z(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=Wt(),o=new qt({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Jt(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){z(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}z(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new qt({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Xt=(...e)=>new Yt(...e)}),Qt,$t,en,tn=s(()=>{R(),rt(),zt(),Zt(),jt(),Qt=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),$t=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},en=class{constructor(e){this.tensorManager=Xt(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,kt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){z(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){z(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)z(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}else if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>$t(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){z(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Qt.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){z(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Qt.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!F().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);z(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Rt(n,t)}}registerMLTensor(e,t,n,r){let i=Qt.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return z(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=Vt(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return z(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Qt.get(ht(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),nn=s(()=>{}),rn,an,on,sn,cn,ln,un,dn,fn,pn=s(()=>{jt(),nn(),rn=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),an=[],on=e=>Math.ceil(Number(e)/16)*16,sn=e=>{for(let t=0;t<an.length;t++){let n=an[t];if(e<=n)return n}return Math.ceil(e/16)*16},cn=1,ln=()=>cn++,un=async(e,t,n,r)=>{let i=on(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let s=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(s,0,n)),e}else return new Uint8Array(s.slice(0,n))}finally{a.destroy()}},dn=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of rn)an.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=on(i),o=this.storageCache.get(e);if(!o)throw Error(`gpu data for uploading does not exist`);if(Number(o.originalSize)!==i)throw Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let s=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=s.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,r,i)),s.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(s,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([l.finish()]),s.destroy(),z(`verbose`,()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw Error(`source gpu data for memcpy does not exist`);let r=this.storageCache.get(t);if(!r)throw Error(`destination gpu data for memcpy does not exist`);if(n.originalSize!==r.originalSize)throw Error(`inconsistent source and destination gpu data size`);let i=on(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return z(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
2
|
-
Please use the previous external buffer!`)}else r=ln();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),z(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`),r}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),z(`verbose`,()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=sn(e),r,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(n);r=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:n,usage:t})}else r=this.backend.device.createBuffer({size:n,usage:t});let o={id:ln(),type:0,buffer:r};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),z(`verbose`,()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e==`bigint`?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw Error(`releasing data does not exist`)}return z(`verbose`,()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw Error(`data does not exist`);await un(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=rn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(e=>{e.destroy()}),this.capturedPendingBuffers.delete(e)),--this.sessionCount,this.sessionCount===0&&(z(`warning`,()=>`[WebGPU] Clearing webgpu buffer cache`),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map)}},fn=(...e)=>new dn(...e)}),mn,H,U=s(()=>{mn=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(`;`),this.key}},H=e=>new mn(e)}),hn,gn,W,G,K,q,_n,vn,yn,J,bn,Y,X,xn,Sn,Cn,wn,Z=s(()=>{R(),V(),hn=64,gn=(e,t)=>{if(t===3)throw Error(`vec3 has same alignment as vec4, use vec4 instead`);switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:`f16`;case 1:return t>1?`vec${t}<f32>`:`f32`;case 6:return t>1?`vec${t}<i32>`:`i32`;case 12:return t>1?`vec${t}<u32>`:`u32`;case 7:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`i32`];case 13:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`u32`];case 9:if(t!==4)throw Error(`bool must be vec4`);return[`u32`,`vec4<bool>`];case 22:return`i32`;case 21:return`u32`;default:throw Error(`Unknown data type: ${e}`)}},W=(e,t=1)=>{let n=gn(e,t);return typeof n==`string`?n:n[0]},G=(e,t=1)=>{let n=gn(e,t);return typeof n==`string`?n:n[1]},K=(...e)=>{let t=[];return e.forEach(e=>{e.length!==0&&t.push({type:12,data:e},{type:12,data:B.computeStrides(e)})}),t},q=e=>e%4==0?4:e%2==0?2:1,_n=(e=`f32`,t,n=`0`)=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,vn=(e,t,n)=>e===`f32`?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,yn=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,J=(e,t,n,r)=>e.startsWith(`uniforms.`)&&n>4?typeof t==`string`?r===`f16`?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:r===`f16`?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,bn=(e,t,n,r,i)=>{let a=typeof n==`number`,o=a?n:n.length,s=[...Array(o).keys()],c=o<2?`u32`:o<=4?`vec${o}<u32>`:`array<u32, ${o}>`,l=gn(t,i),u=typeof l==`string`?l:l[1],d={indices:c,value:u,storage:typeof l==`string`?l:l[0],tensor:t},f=e=>typeof e==`string`?e:`${e}u`,p={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=a?`uniforms.`:``,h=`${m}${e}_shape`,g=`${m}${e}_strides`,_=``;for(let e=0;e<o-1;e++)_+=`
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime-DkW27tQK.js";import{n,t as r}from"./preload-helper-CiWYd9n-.js";var i=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.baseAssetPath=void 0;var t=typeof window<`u`&&window.document!==void 0?window.document.currentScript:null,n=`/`;t&&(n=t.src.replace(/#.*$/,``).replace(/\?.*$/,``).replace(/\/[^/]+$/,`/`)),e.baseAssetPath=n})),a=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultModelFetcher=void 0,e.defaultModelFetcher=e=>fetch(e).then(e=>e.arrayBuffer())})),o=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.log=void 0;var t=e=>t=>{console.log(`VAD | ${e} >`,t)};e.log={error:t(`error`),debug:t(`debug`),warn:t(`warn`)}})),s=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=void 0;var t;(function(e){e.AudioFrame=`AUDIO_FRAME`,e.SpeechStart=`SPEECH_START`,e.VADMisfire=`VAD_MISFIRE`,e.SpeechEnd=`SPEECH_END`,e.SpeechStop=`SPEECH_STOP`,e.SpeechRealStart=`SPEECH_REAL_START`,e.FrameProcessed=`FRAME_PROCESSED`})(t||(e.Message=t={}))})),c=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FrameProcessor=e.validateOptions=e.defaultFrameProcessorOptions=void 0;var t=o(),n=s();e.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(e){(e.positiveSpeechThreshold<0||e.positiveSpeechThreshold>1)&&t.log.error(`positiveSpeechThreshold should be a number between 0 and 1`),(e.negativeSpeechThreshold<0||e.negativeSpeechThreshold>e.positiveSpeechThreshold)&&t.log.error(`negativeSpeechThreshold should be between 0 and positiveSpeechThreshold`),e.preSpeechPadMs<0&&t.log.error(`preSpeechPadMs should be positive`),e.redemptionMs<0&&t.log.error(`redemptionMs should be positive`),e.minSpeechMs<0&&t.log.error(`minSpeechMs should be positive`)}e.validateOptions=r;var i=e=>{let t=e.reduce((e,t)=>(e.push(e.at(-1)+t.length),e),[0]),n=new Float32Array(t.at(-1));return e.forEach((e,r)=>{let i=t[r];n.set(e,i)}),n};function a(e,t){return{redemptionFrames:Math.floor(e.redemptionMs/t),preSpeechPadFrames:Math.floor(e.preSpeechPadMs/t),minSpeechFrames:Math.floor(e.minSpeechMs/t)}}e.FrameProcessor=class{constructor(e,t,r,o){this.modelProcessFunc=e,this.modelResetFunc=t,this.options=r,this.msPerFrame=o,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=e=>{this.options={...this.options,...e};let{redemptionFrames:t,preSpeechPadFrames:n,minSpeechFrames:r}=a(this.options,this.msPerFrame);this.redemptionFrames=t,this.preSpeechPadFrames=n,this.minSpeechFrames=r},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{let t=this.audioBuffer;this.audioBuffer=[];let r=this.speaking;if(this.reset(),r){if(t.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){let r=i(t.map(e=>e.frame));e({msg:n.Message.SpeechEnd,audio:r})}else e({msg:n.Message.VADMisfire})}return{}},this.process=async(e,t)=>{if(!this.active)return;let r=await this.modelProcessFunc(e),a=r.isSpeech>=this.options.positiveSpeechThreshold;if(t({probs:r,msg:n.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:a}),a&&(this.speechFrameCount++,this.redemptionCounter=0),a&&!this.speaking&&(this.speaking=!0,t({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,t({msg:n.Message.SpeechRealStart})),r.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;let e=this.audioBuffer;if(this.audioBuffer=[],e.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){let r=i(e.map(e=>e.frame));t({msg:n.Message.SpeechEnd,audio:r})}else t({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];let{redemptionFrames:s,preSpeechPadFrames:c,minSpeechFrames:l}=a(this.options,this.msPerFrame);this.redemptionFrames=s,this.preSpeechPadFrames=c,this.minSpeechFrames=l,this.reset()}}})),l=t(((t,i)=>{n();var a=(()=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),s=(e,t)=>()=>(e&&(t=e(e=0)),t),c=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},l=(e,r,o,s)=>{if(r&&typeof r==`object`||typeof r==`function`)for(let c of i(r))!a.call(e,c)&&c!==o&&t(e,c,{get:()=>r[c],enumerable:!(s=n(r,c))||s.enumerable});return e},u=e=>l(t({},`__esModule`,{value:!0}),e),d,f,p,m,h,g=s(()=>{d=new Map,f=[],p=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}return}throw TypeError(`not a valid backend`)},m=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},h=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=new Set;for(let e of r){let t=await m(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),_=s(()=>{g()}),v,y=s(()=>{v=`1.26.0`}),b,x,S=s(()=>{y(),b=`warning`,x={wasm:{},webgl:{},webgpu:{},versions:{common:v},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);b=e}},get logLevel(){return b}},Object.defineProperty(x,"logLevel",{enumerable:!0})}),C,w=s(()=>{S(),C=x}),T,E,ee=s(()=>{T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},E=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),D,O,te,ne,re,ie,ae=s(()=>{me(),D=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new k(`float32`,u,[1,4,n,r]):new k(`float32`,u,[1,3,n,r])},O=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,D(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(D(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return D(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new k({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},re=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ie=(e,t,n)=>new k({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),oe,se,ce,le,ue=s(()=>{oe=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),se=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ce=!1,le=()=>{if(!ce){ce=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(oe.set(`int64`,BigInt64Array),se.set(BigInt64Array,`int64`)),t&&(oe.set(`uint64`,BigUint64Array),se.set(BigUint64Array,`uint64`)),r?(oe.set(`float16`,n),se.set(n,`float16`)):oe.set(`float16`,Uint16Array)}}}),de,fe,pe=s(()=>{me(),de=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},fe=(e,t)=>{switch(e.location){case`cpu`:return new k(e.type,e.data,t);case`cpu-pinned`:return new k({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new k({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new k({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new k({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),k,me=s(()=>{ee(),ae(),ue(),pe(),k=class{constructor(e,t,n){le();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=oe.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=oe.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=se.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=de(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return O(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return re(e,t)}static fromPinnedBuffer(e,t,n){return ie(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return E(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return fe(this,e)}}}),A,he=s(()=>{me(),A=k}),ge,_e,j,M,ve,ye,be=s(()=>{S(),ge=(e,t)=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeStamp(`${e}::ORT::${t}`)},_e=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ge(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},j=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`BEGIN`,e)},M=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`END`,e)},ve=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.time(`ORT::${e}`)},ye=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeEnd(`ORT::${e}`)}}),xe,Se=s(()=>{g(),he(),be(),xe=class e{constructor(e){this.handler=e}async run(e,t,n){j(),ve(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof A||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof A)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof A)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof A?t:new A(t.type,t.data,t.dims)}return ye(`InferenceSession.run`),M(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){j(),ve(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await h(o),l=await s.createInferenceSessionHandler(a,c);return ye(`InferenceSession.create`),M(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ce,we=s(()=>{Se(),Ce=xe}),Te=s(()=>{}),Ee=s(()=>{}),De=s(()=>{}),Oe=s(()=>{}),ke={};c(ke,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,env:()=>C,registerBackend:()=>p});var N=s(()=>{_(),w(),we(),he(),Te(),Ee(),be(),De(),Oe()}),Ae=s(()=>{}),je={};c(je,{default:()=>Pe});var Me,Ne,Pe,Fe=s(()=>{zu(),rt(),Je(),Me=`ort-wasm-proxy-worker`,Ne=globalThis.self?.name===Me,Ne&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:nt(n.wasm).then(()=>{Du(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Ou(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Mu(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;Nu(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Pu(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Iu(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Ru([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Lu(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),Pe=Ne?null:e=>new Worker(e??P,{type:`classic`,name:Me})}),Ie,Le,P,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je=s(()=>{Ae(),Ie=typeof location>`u`?void 0:location.origin,Le=()=>typeof document<`u`?document.currentScript?.src:typeof self<`u`?self.location?.href:void 0,P=Le(),Re=()=>{if(P&&!P.startsWith(`blob:`))return P.substring(0,P.lastIndexOf(`/`)+1)},ze=(e,t)=>{try{let n=t??P;return(n?new URL(e,n):new URL(e)).origin===Ie}catch{return!1}},Be=(e,t)=>{let n=t??P;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Ve=(e,t)=>`${t??`./`}${e}`,He=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Ue=async e=>(await r(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,We=(Fe(),u(je)).default,Ge=async()=>{if(!P)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(ze(P))return[void 0,We()];let e=await He(P);return[e,We(e)]},Ke=void 0,qe=async(e,t,n,r)=>{let i=Ke&&!(e||t);if(i){if(P)i=ze(P)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,Ke];{let r=`ort-wasm-simd-threaded.jsep.mjs`,i=e??Be(r,t),a=n&&i&&!ze(i,t),o=a?await He(i):i??Ve(r,t);return[a?o:void 0,await Ue(o)]}}}),Ye,Xe,Ze,Qe,$e,et,tt,nt,F,rt=s(()=>{Je(),Xe=!1,Ze=!1,Qe=!1,$e=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},et=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nt=async e=>{if(Xe)return Promise.resolve();if(Ze)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Qe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Ze=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!tt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!et())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=$e();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await qe(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Re();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Ze=!1,Xe=!0,Ye=t,e(),d&&URL.revokeObjectURL(d)},e=>{Ze=!1,Qe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Xe&&Ye)return Ye;throw Error(`WebAssembly is not initialized yet.`)}}),I,it,L,at=s(()=>{rt(),I=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},it=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)it(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},L=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),ot,st=s(()=>{rt(),at(),ot=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=I(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&L(`Can't create run options.`),e?.extra!==void 0&&it(e.extra,``,new WeakSet,(e,i)=>{let a=I(e,r),o=I(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&L(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ct,lt,ut,dt,ft,pt,mt=s(()=>{rt(),at(),ct=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},lt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ut=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},dt=(e,t,n,r)=>{let i=I(t,r),a=I(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&L(`Can't set a session config entry: ${t} - ${n}.`)},ft=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,dt(e,`session.disable_quant_qdq`,`1`,n),dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof t!=`string`){let r=t?.deviceType;r&&dt(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);dt(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=I(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&L(`Can't append execution provider: ${r}.`)}},pt=async e=>{let t=F(),n=0,r=[],i=e||{};ut(i);try{let e=ct(i.graphOptimizationLevel??`all`),a=lt(i.executionMode??`sequential`),o=typeof i.logId==`string`?I(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?I(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&L(`Can't create session options.`),i.executionProviders&&await ft(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=I(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&L(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&it(i.extra,``,new WeakSet,(e,t)=>{dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&L(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ht,gt,_t,vt,yt,bt,xt,St,R=s(()=>{ht=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},_t=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},vt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},yt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,xt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,St=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ct,wt=s(()=>{Ae(),Ct=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Tt,Et,Dt,Ot,kt,At,z,jt=s(()=>{R(),Tt=[`V`,`I`,`W`,`E`,`F`],Et=(e,t)=>{console.log(`[${Tt[e]},${new Date().toISOString()}]${t}`)},kt=(e,t)=>{Dt=e,Ot=t},At=(e,t)=>{let n=yt(e);n>=yt(Dt)&&Et(n,typeof t==`function`?t():t)},z=(...e)=>{Ot&&At(...e)}}),Mt,Nt,B,Pt,Ft,It,Lt,V=s(()=>{Mt=class{static calcMatMulShape(e,t){return e[1]===t[0]?[e[0],t[1]]:void 0}},Nt=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(r===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=Array(a);if(n){if(r<2||i<2)return;let n=Mt.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(n===void 0)return;[o[a-2],o[a-1]]=n}for(let s=n?3:1;s<=a;s++){let n=r-s<0?1:e[r-s],c=i-s<0?1:t[i-s];if(n!==c&&n>1&&c>1)return;let l=Math.max(n,c);if(n&&c)o[a-s]=Math.max(n,c);else{if(l>1)return;o[a-s]=0}}return o}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(e[n-i]!==1&&e[n-i]!==t[r-i])return!1;return!0}},B=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(n===0)return[];let r=Array(n),i=n-1;for(;i>=0;){if(e[i]%t===0){r[i]=e[i]/t;break}if(t%e[i]!==0)throw Error(`cannot convert shape`);r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i<n;i++){if(e[i]<0)throw Error(`cannot get valid size from specified dimension range. Most likely the range contains negative values in them.`);r*=Number(e[i])}return r}static computeStrides(e){let t=e.length;if(t===0)return[];if(t===1)return[1];let n=Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw Error(`unsupported axis for this operation.`);return e<0?e+t:e}static normalizeAxes(e,t){return e.map(n=>this.normalizeAxis(n,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(t=>e[t]):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map((e,r)=>e+t[r]+t[r+n])}static areEqual(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}},Pt=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw Error(`length of specified kernel shapes should be 2 less than length of input dimensions`);if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw Error(`strides should be greater than or equal to 1`)}else r.push(1);for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw Error(`dilations should be greater than or equal to 1`)}else i.push(1);for(let e=0;e<n.length*2;e++)if(e<a.length){if(a[e]<0)throw Error(`pad should be greater than or equal to 1`)}else a.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw Error(`kernel shapes need to be greater than 0`);if(a[e]>=n[e]||a[e+n.length]>=n[e])throw Error(`pads should be smaller than kernel`)}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,o,s){if(s){if(a.length!==2*(t.length-2))throw Error(`length of pads should be twice the length of data dimensions`);if(n.length!==t.length-2)throw Error(`length of strides should be the length of data dimensions`);if(i.length!==t.length-2)throw Error(`length of kernel shapes should be the length of data dimensions`);for(let c=0;c<t.length-2;c++)e.adjustPadAndReturnShape(t[c+(o?1:2)],n[c],r[c],i[c],a,c,c+t.length-2,s)}}static computePoolOutputShape(t,n,r,i,a,o,s){if(n.length<=0)throw Error(`input shape must be of size greater than 0`);let c=[n[0],n[1]];return e.computeShapeHelper(t,n,c,r,i,a,o,s),c}static computeConvOutputShape(t,n,r,i,a,o,s){if(t.length<=0||n.length<=0)throw Error(`invalid input tensor dims or invalid filter tensor dims`);let c=[t[0],n[0]];return e.computeShapeHelper(!1,t,c,r,i,a,o,s),c}static computeShapeHelper(t,n,r,i,a,o,s,c){if(t)for(let e=0;e<n.length-2;e++)r.push(1);else for(let t=0;t<n.length-2;t++)r.push(e.adjustPadAndReturnShape(n[t+2],i[t],a[t],o[t],s,t,t+n.length-2,c))}static adjustPadAndReturnShape(e,t,n,r,i,a,o,s){let c=n*(r-1)+1;if(s&&s!==`NOTSET`)switch(s){case`VALID`:return i[a]=0,i[o]=0,Math.floor((e-c)/t+1);case`SAME_LOWER`:case`SAME_UPPER`:if(n!==1)throw Error(`Dilation not supported for SAME_UPPER or SAME_LOWER`);{let n=((e+t-1)/t-1)*t+r-e;return i[a]=Math.floor(s===`SAME_LOWER`?(n+1)/2:n/2),i[o]=n-i[a],Math.floor((e+n-r)/t+1)}default:throw Error(`Unsupported AutoPad type`)}else return Math.floor((e+i[a]+i[o]-c)/t+1)}},Ft=class{static getShapeOfGemmResult(e,t,n,r,i){if(e.length!==2||n.length!==2)throw Error(`shape need to be of size 2`);let a,o,s;t?(a=e[1],o=e[0]):(a=e[0],o=e[1]);let c=-1;if(r?(s=n[0],c=1):(s=n[1],c=0),n[c]!==o)throw Error(`dimension mismatch`);if(a<=0||s<=0||o<=0)throw Error(`invalid shape specified`);if(i&&!Nt.isValidBroadcast(i,[a,s]))throw Error(`gemm: invalid bias shape for broadcast`);return[a,s,o]}},It=-34028234663852886e22,Lt=34028234663852886e22}),Rt,zt=s(()=>{R(),Rt=(e,t)=>new(vt(t))(e)}),Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt=s(()=>{R(),jt(),Bt=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Vt=(e,t)=>{if(t===`int32`)return e;let n=Bt.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(vt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Ht=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Ut=1,Wt=()=>Ut++,Gt=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),Kt=(e,t)=>{let n=Bt.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},qt=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Kt(this.dataType,this.tensorShape)}destroy(){z(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Ht(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return n.buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Jt=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Gt.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);z(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Kt(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=Vt(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}z(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Ht(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},Yt=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Wt();return this.tensorTrackersById.set(e,new Jt(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){z(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){z(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=Wt(),o=new qt({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Jt(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){z(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}z(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new qt({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Xt=(...e)=>new Yt(...e)}),Qt,$t,en,tn=s(()=>{R(),rt(),zt(),Zt(),jt(),Qt=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),$t=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},en=class{constructor(e){this.tensorManager=Xt(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,kt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){z(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){z(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)z(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>$t(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){z(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Qt.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){z(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Qt.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!F().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);z(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Rt(n,t)}}registerMLTensor(e,t,n,r){let i=Qt.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return z(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=Vt(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return z(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Qt.get(ht(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),nn=s(()=>{}),rn,an,on,sn,cn,ln,un,dn,fn,pn=s(()=>{jt(),nn(),rn=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),an=[],on=e=>Math.ceil(Number(e)/16)*16,sn=e=>{for(let t=0;t<an.length;t++){let n=an[t];if(e<=n)return n}return Math.ceil(e/16)*16},cn=1,ln=()=>cn++,un=async(e,t,n,r)=>{let i=on(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let s=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(s,0,n)),e}return new Uint8Array(s.slice(0,n))}finally{a.destroy()}},dn=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of rn)an.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=on(i),o=this.storageCache.get(e);if(!o)throw Error(`gpu data for uploading does not exist`);if(Number(o.originalSize)!==i)throw Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let s=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=s.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,r,i)),s.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(s,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([l.finish()]),s.destroy(),z(`verbose`,()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw Error(`source gpu data for memcpy does not exist`);let r=this.storageCache.get(t);if(!r)throw Error(`destination gpu data for memcpy does not exist`);if(n.originalSize!==r.originalSize)throw Error(`inconsistent source and destination gpu data size`);let i=on(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return z(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
2
|
+
Please use the previous external buffer!`)}else r=ln();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),z(`verbose`,()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`),r}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),z(`verbose`,()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=sn(e),r,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(n);r=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:n,usage:t})}else r=this.backend.device.createBuffer({size:n,usage:t});let o={id:ln(),type:0,buffer:r};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),z(`verbose`,()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e==`bigint`?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw Error(`releasing data does not exist`)}return z(`verbose`,()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw Error(`data does not exist`);await un(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0){if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=rn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(e=>{e.destroy()}),this.capturedPendingBuffers.delete(e)),--this.sessionCount,this.sessionCount===0&&(z(`warning`,()=>`[WebGPU] Clearing webgpu buffer cache`),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map)}},fn=(...e)=>new dn(...e)}),mn,H,U=s(()=>{mn=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(`;`),this.key}},H=e=>new mn(e)}),hn,gn,W,G,K,q,_n,vn,yn,J,bn,Y,X,xn,Sn,Cn,wn,Z=s(()=>{R(),V(),hn=64,gn=(e,t)=>{if(t===3)throw Error(`vec3 has same alignment as vec4, use vec4 instead`);switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:`f16`;case 1:return t>1?`vec${t}<f32>`:`f32`;case 6:return t>1?`vec${t}<i32>`:`i32`;case 12:return t>1?`vec${t}<u32>`:`u32`;case 7:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`i32`];case 13:if(t>1)throw Error(`currently not supported vecX of uint64 yet`);return[`vec2<u32>`,`u32`];case 9:if(t!==4)throw Error(`bool must be vec4`);return[`u32`,`vec4<bool>`];case 22:return`i32`;case 21:return`u32`;default:throw Error(`Unknown data type: ${e}`)}},W=(e,t=1)=>{let n=gn(e,t);return typeof n==`string`?n:n[0]},G=(e,t=1)=>{let n=gn(e,t);return typeof n==`string`?n:n[1]},K=(...e)=>{let t=[];return e.forEach(e=>{e.length!==0&&t.push({type:12,data:e},{type:12,data:B.computeStrides(e)})}),t},q=e=>e%4==0?4:e%2==0?2:1,_n=(e=`f32`,t,n=`0`)=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,vn=(e,t,n)=>e===`f32`?n:t===1?`f32(${n})`:`vec${t}<f32>(${n})`,yn=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,J=(e,t,n,r)=>e.startsWith(`uniforms.`)&&n>4?typeof t==`string`?r===`f16`?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:r===`f16`?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,bn=(e,t,n,r,i)=>{let a=typeof n==`number`,o=a?n:n.length,s=[...Array(o).keys()],c=o<2?`u32`:o<=4?`vec${o}<u32>`:`array<u32, ${o}>`,l=gn(t,i),u=typeof l==`string`?l:l[1],d={indices:c,value:u,storage:typeof l==`string`?l:l[0],tensor:t},f=e=>typeof e==`string`?e:`${e}u`,p={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=a?`uniforms.`:``,h=`${m}${e}_shape`,g=`${m}${e}_strides`,_=``;for(let e=0;e<o-1;e++)_+=`
|
|
3
3
|
let dim${e} = current / ${J(g,e,o)};
|
|
4
4
|
let rest${e} = current % ${J(g,e,o)};
|
|
5
5
|
indices[${e}] = dim${e};
|
|
@@ -18,16 +18,16 @@ import{i as e,t}from"./chunk-BVpWp9h4.js";import{J as n,q as r}from"./index-Dbr1
|
|
|
18
18
|
}`,`${r}(${t})`},D=(t,n)=>(()=>{if(d.storage===d.value)return`${e}[${t}]=${n};`;if(d.storage===`vec2<u32>`&&d.value===`i32`)return`${e}[${t}]=vec2<u32>(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if(d.storage===`vec2<u32>`&&d.value===`u32`)return`${e}[${t}]=vec2<u32>(u32(${n}), 0u);`;if(d.storage===`u32`&&d.value===`vec4<bool>`)return`${e}[${t}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${n}));`;throw Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),O=t=>(()=>{if(d.storage===d.value)return`${e}[${t}]`;if(d.storage===`vec2<u32>`&&d.value===`i32`)return`i32(${e}[${t}].x)`;if(d.storage===`vec2<u32>`&&d.value===`u32`)return`u32(${e}[${t}].x)`;if(d.storage===`u32`&&d.value===`vec4<bool>`)return`vec4<bool>(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),te=o<2?``:`
|
|
19
19
|
fn get_${e}ByIndices(indices: ${d.indices}) -> ${u} {
|
|
20
20
|
return ${O(`i2o_${e}(indices)`)};
|
|
21
|
-
}`,ne=o<2
|
|
22
|
-
fn get_${e}(${
|
|
23
|
-
return get_${e}ByIndices(${C(
|
|
24
|
-
}
|
|
21
|
+
}`,ne=o<2?``:(()=>{let t=s.map(e=>`d${e}: u32`).join(`, `),n=s.map(e=>`d${e}`).join(`, `);return`
|
|
22
|
+
fn get_${e}(${t}) -> ${u} {
|
|
23
|
+
return get_${e}ByIndices(${C(n)});
|
|
24
|
+
}`})(),re=(...t)=>{if(t.length!==o)throw Error(`indices length must be ${o}`);let n=t.map(f).join(`,`);return o===0?O(`0u`):o===1?O(n[0]):(p.get=!0,p.getByIndices=!0,p.indicesToOffset=!0,`get_${e}(${n})`)},ie=t=>o<2?O(t):(p.getByIndices=!0,p.indicesToOffset=!0,`get_${e}ByIndices(${t})`),ae=o<2?``:`
|
|
25
25
|
fn set_${e}ByIndices(indices: ${d.indices}, value: ${u}) {
|
|
26
26
|
${D(`i2o_${e}(indices)`,`value`)}
|
|
27
|
-
}`,oe=o<2
|
|
28
|
-
fn set_${e}(${
|
|
29
|
-
set_${e}ByIndices(${C(
|
|
30
|
-
}
|
|
27
|
+
}`,oe=o<2?``:(()=>{let t=s.map(e=>`d${e}: u32`).join(`, `),n=s.map(e=>`d${e}`).join(`, `);return`
|
|
28
|
+
fn set_${e}(${t}, value: ${u}) {
|
|
29
|
+
set_${e}ByIndices(${C(n)}, value);
|
|
30
|
+
}`})();return{impl:()=>{let e=[],t=!1;return p.offsetToIndices&&(e.push(v),t=!0),p.indicesToOffset&&(e.push(x),t=!0),p.broadcastedIndicesToOffset&&(Object.values(E).forEach(t=>e.push(t)),t=!0),p.set&&(e.push(oe),t=!0),p.setByIndices&&(e.push(ae),t=!0),p.get&&(e.push(ne),t=!0),p.getByIndices&&(e.push(te),t=!0),!a&&t&&e.unshift(`const ${h} = ${d.indices}(${n.join(`,`)});`,`const ${g} = ${d.indices}(${B.computeStrides(n).join(`,`)});`),e.join(`
|
|
31
31
|
`)},type:d,offsetToIndices:y,indicesToOffset:S,broadcastedIndicesToOffset:ee,indices:C,indicesGet:w,indicesSet:T,set:(...t)=>{if(t.length!==o+1)throw Error(`indices length must be ${o}`);let n=t[o];if(typeof n!=`string`)throw Error(`value must be string`);let r=t.slice(0,o).map(f).join(`,`);return o===0?D(`0u`,n):o===1?D(r[0],n):(p.set=!0,p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:D,setByIndices:(t,n)=>o<2?D(t,n):(p.setByIndices=!0,p.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:re,getByOffset:O,getByIndices:ie,usage:r,name:e,strides:g,shape:h,rank:o}},Y=(e,t,n,r=1)=>bn(e,t,n,`input`,r),X=(e,t,n,r=1)=>bn(e,t,n,`output`,r),xn=(e,t,n)=>bn(e,t,n,`atomicOutput`,1),Sn=(e,t,n,r=1)=>bn(e,t,n,`internal`,r),Cn=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e==`number`?`${e}u`:e}) { return; }`}mainStart(e=hn){let t=typeof e==`number`?e:e[0],n=typeof e==`number`?1:e[1],r=typeof e==`number`?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1;return`@compute @workgroup_size(${t}, ${n}, ${r})
|
|
32
32
|
fn main(${i?`@builtin(global_invocation_id) global_id : vec3<u32>,
|
|
33
33
|
@builtin(workgroup_id) workgroup_id : vec3<u32>,
|
|
@@ -485,12 +485,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
485
485
|
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
|
|
486
486
|
|
|
487
487
|
${i.setByOffset(`global_idx`,`valueLeft * geluRight`)}
|
|
488
|
-
}`}},Ki=e=>{Wi(e.inputs),e.compute(Gi(e.inputs))}}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa=s(()=>{R(),V(),Z(),Ji=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f,p;typeof s==`string`?f=p=(e,t)=>`${s}((${e}),(${t}))`:typeof s==`function`?f=p=s:(f=s.scalar,p=s.vector);let m=X(`outputData`,u,r.length,4),h=Y(`aData`,c,t.length,4),g=Y(`bData`,l,n.length,4),_;if(i)if(a){let e=B.size(t)===1,r=B.size(n)===1,i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;_=e||r?m.setByOffset(`global_idx`,p(e?`${h.type.value}(${h.getByOffset(`0`)}.x)`:h.getByOffset(`global_idx`),r?`${g.type.value}(${g.getByOffset(`0`)}.x)`:g.getByOffset(`global_idx`))):`
|
|
488
|
+
}`}},Ki=e=>{Wi(e.inputs),e.compute(Gi(e.inputs))}}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa=s(()=>{R(),V(),Z(),Ji=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f,p;typeof s==`string`?f=p=(e,t)=>`${s}((${e}),(${t}))`:typeof s==`function`?f=p=s:(f=s.scalar,p=s.vector);let m=X(`outputData`,u,r.length,4),h=Y(`aData`,c,t.length,4),g=Y(`bData`,l,n.length,4),_;if(i){if(a){let e=B.size(t)===1,r=B.size(n)===1,i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;_=e||r?m.setByOffset(`global_idx`,p(e?`${h.type.value}(${h.getByOffset(`0`)}.x)`:h.getByOffset(`global_idx`),r?`${g.type.value}(${g.getByOffset(`0`)}.x)`:g.getByOffset(`global_idx`))):`
|
|
489
489
|
let outputIndices = ${m.offsetToIndices(`global_idx * 4u`)};
|
|
490
490
|
let offsetA = ${h.broadcastedIndicesToOffset(`outputIndices`,m)};
|
|
491
491
|
let offsetB = ${g.broadcastedIndicesToOffset(`outputIndices`,m)};
|
|
492
492
|
${m.setByOffset(`global_idx`,p(o||i?h.getByOffset(`offsetA / 4u`):`${h.type.value}(${h.getByOffset(`offsetA / 4u`)}[offsetA % 4u])`,o||a?g.getByOffset(`offsetB / 4u`):`${g.type.value}(${g.getByOffset(`offsetB / 4u`)}[offsetB % 4u])`))}
|
|
493
|
-
`}else _=m.setByOffset(`global_idx`,p(h.getByOffset(`global_idx`),g.getByOffset(`global_idx`)))
|
|
493
|
+
`}else _=m.setByOffset(`global_idx`,p(h.getByOffset(`global_idx`),g.getByOffset(`global_idx`)))}else{if(!a)throw Error(`no necessary to use scalar implementation for element-wise binary op implementation.`);let e=(e,t,n=``)=>{let r=`aData[indexA${t}][componentA${t}]`,i=`bData[indexB${t}][componentB${t}]`;return`
|
|
494
494
|
let outputIndices${t} = ${m.offsetToIndices(`global_idx * 4u + ${t}u`)};
|
|
495
495
|
let offsetA${t} = ${h.broadcastedIndicesToOffset(`outputIndices${t}`,m)};
|
|
496
496
|
let offsetB${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,m)};
|
|
@@ -561,7 +561,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
|
|
|
561
561
|
${ua(o,d)}
|
|
562
562
|
}`}},fa=(e,t)=>{let n=e.inputs,r=n[0].dims,i=B.normalizeAxis(t.axis,r.length);ca(n,i);let a=r.slice();a[i]=n.reduce((e,t)=>e+(t.dims.length>i?t.dims[i]:0),0);let o=n.filter(e=>B.size(e.dims)>0);e.compute(da(o,i,a,n[0].dataType),{inputs:o})},pa=e=>H({axis:e.axis})}),ha,ga,_a,va,ya=s(()=>{R(),V(),ha=(e,t,n=`f32`)=>{switch(e.activation){case`Relu`:return`value = max(value, ${t}(0.0));`;case`Sigmoid`:return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case`Clip`:return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case`HardSigmoid`:return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case`LeakyRelu`:return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case`Tanh`:return`let e2x = exp(-2.0 * abs(value));
|
|
563
563
|
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
564
|
-
`;case``:return``;default:throw Error(`Unsupported activation ${e.activation}`)}},ga=(e,t)=>{e.activation===`Clip`?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===`HardSigmoid`?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===`LeakyRelu`&&t.push({type:1,data:e.alpha})},_a=(e,t)=>{e.activation===`Clip`?t.push({name:`clip_max`,type:`f32`},{name:`clip_min`,type:`f32`}):e.activation===`HardSigmoid`?t.push({name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}):e.activation===`LeakyRelu`&&t.push({name:`alpha`,type:`f32`})},va=e=>{let t=e?.activation||``;if(t===`HardSigmoid`){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}
|
|
564
|
+
`;case``:return``;default:throw Error(`Unsupported activation ${e.activation}`)}},ga=(e,t)=>{e.activation===`Clip`?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===`HardSigmoid`?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===`LeakyRelu`&&t.push({type:1,data:e.alpha})},_a=(e,t)=>{e.activation===`Clip`?t.push({name:`clip_max`,type:`f32`},{name:`clip_min`,type:`f32`}):e.activation===`HardSigmoid`?t.push({name:`alpha`,type:`f32`},{name:`beta`,type:`f32`}):e.activation===`LeakyRelu`&&t.push({name:`alpha`,type:`f32`})},va=e=>{let t=e?.activation||``;if(t===`HardSigmoid`){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}if(t===`Clip`){let[n,r]=e?.activation_params||[It,Lt];return{activation:t,clipMax:r,clipMin:n}}if(t===`LeakyRelu`){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),$,ba,xa=s(()=>{$=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw Error(`${e}-component is not supported.`)}},ba=e=>`
|
|
565
565
|
${e?`value = value + getBiasByOutputCoords(coords);`:``}
|
|
566
566
|
`}),Sa,Ca=s(()=>{Sa=e=>`
|
|
567
567
|
fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
|
|
@@ -716,7 +716,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
716
716
|
mm_Asub[inputRow][inputCol] = mm_readA(batch,
|
|
717
717
|
globalRowStart + inputRow,
|
|
718
718
|
kStart + inputCol${t?`, batchIndices`:``});
|
|
719
|
-
`,ja=e=>e?`let ACached = mm_Asub[k][tileRow + innerRow];`:`let ACached = mm_Asub[tileRow + innerRow][k];`,Ma=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32,c=!1)=>{let l=e[1]*t[1],u=e[0]*t[0],d=i?l:a,f=i?a:l;if(
|
|
719
|
+
`,ja=e=>e?`let ACached = mm_Asub[k][tileRow + innerRow];`:`let ACached = mm_Asub[tileRow + innerRow][k];`,Ma=(e,t,n=`f32`,r,i=!1,a=32,o=!1,s=32,c=!1)=>{let l=e[1]*t[1],u=e[0]*t[0],d=i?l:a,f=i?a:l;if(f%t[1]!==0||d%t[0]!==0||a%t[1]!==0)throw Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let p=f/t[1],m=d/t[0],h=a/t[1],g=c?`
|
|
720
720
|
let localRow = i32(localId.y);
|
|
721
721
|
let localCol = i32(localId.x);
|
|
722
722
|
let globalRowStart = i32(workgroupId.y) * ${l};
|
|
@@ -1722,7 +1722,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1722
1722
|
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1723
1723
|
|
|
1724
1724
|
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1725
|
-
}`}},{inputs:[t,n],outputs:[-1]})[0]},Vs=(e,t,n,r,i,a,o,s)=>{let c=a;if(o&&B.size(o.dims)>0){if(r===1)throw Error(`AddBiasReshape is not implemented. Please export your model with packed QKV or KV`);return c=Bs(e,a,o,t,r,n*i,s),c=c.reshape([t,r,n,i]),n===1||r===1?c:e.compute(jn(c,zs.perm),{inputs:[c],outputs:[-1]})[0]}
|
|
1725
|
+
}`}},{inputs:[t,n],outputs:[-1]})[0]},Vs=(e,t,n,r,i,a,o,s)=>{let c=a;if(o&&B.size(o.dims)>0){if(r===1)throw Error(`AddBiasReshape is not implemented. Please export your model with packed QKV or KV`);return c=Bs(e,a,o,t,r,n*i,s),c=c.reshape([t,r,n,i]),n===1||r===1?c:e.compute(jn(c,zs.perm),{inputs:[c],outputs:[-1]})[0]}return a.dims.length===3&&(c=a.reshape([t,r,n,i])),n===1||r===1?c:e.compute(jn(c,zs.perm),{inputs:[c],outputs:[-1]})[0]},Hs=(e,t)=>{let n=Ls(e.inputs,t),r=e.inputs[0],i=Is(e.inputs,1),a=Is(e.inputs,2),o=Is(e.inputs,3),s=Is(e.inputs,4),c=Is(e.inputs,5),l=Is(e.inputs,6),u=Is(e.inputs,7);if(r.dims.length===5)throw Error(`Packed QKV is not implemented`);if(i?.dims.length===5)throw Error(`Packed KV is not implemented`);let d=i&&a&&i.dims.length===4&&a.dims.length===4,f=Vs(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,o,0);if(d)return Br(e,f,i,a,s,void 0,l,u,c,n);if(!i||!a)throw Error(`key and value must be provided`);let p=Vs(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,i,o,n.hiddenSize),m=Vs(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,o,2*n.hiddenSize);Br(e,f,p,m,s,void 0,l,u,c,n)}}),Ws,Gs,Ks,qs,Js,Ys,Xs,Zs=s(()=>{R(),V(),U(),Z(),Ws=e=>{if(!e||e.length<1)throw Error(`too few inputs`)},Gs=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),r=n.length),H({numOutputs:r,axis:t.axis,splitSizes:n})},Ks=e=>`
|
|
1726
1726
|
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1727
1727
|
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
|
|
1728
1728
|
if (index < ${J(`uniforms.size_in_split_axis`,`i`,e)}) {
|
|
@@ -2135,7 +2135,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2135
2135
|
var value = ${c}(0);
|
|
2136
2136
|
${l}
|
|
2137
2137
|
output[global_idx] = value;
|
|
2138
|
-
}`}}},Nc=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)a[Number(t[e])]=Number(n[e]),a[Number(t[e])+i]=Number(n[e+t.length])}else n.forEach((e,t)=>a[Number(t)]=Number(e));let o=[];return a.forEach(e=>o.push(e)),{mode:t.mode,value:r,pads:o}}
|
|
2138
|
+
}`}}},Nc=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)a[Number(t[e])]=Number(n[e]),a[Number(t[e])+i]=Number(n[e+t.length])}else n.forEach((e,t)=>a[Number(t)]=Number(e));let o=[];return a.forEach(e=>o.push(e)),{mode:t.mode,value:r,pads:o}}return t},Pc=(e,t)=>{Ec(e.inputs);let n=Nc(e.inputs,t);e.compute(Mc(e.inputs,n),{inputs:[0]})}}),Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl=s(()=>{N(),R(),V(),Z(),Ic=e=>{if(C.webgpu.validateInputContent&&(!e||e.length!==1))throw Error(`Pool ops requires 1 input.`)},Lc=(e,t,n)=>{let r=t.format===`NHWC`,i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,`dilations`),o=t.kernelShape.slice(),s=t.strides.slice(),c=a?t.dilations.slice():[],l=t.pads.slice();Pt.adjustPoolAttributes(n,i,o,s,c,l);let u=Pt.computePoolOutputShape(n,i,s,c,o,l,t.autoPad),d=Object.assign({},t);a?Object.assign(d,{kernelShape:o,strides:s,pads:l,dilations:c,cacheKey:t.cacheKey}):Object.assign(d,{kernelShape:o,strides:s,pads:l,cacheKey:t.cacheKey});let f=u.slice();return f.push(f.splice(1,1)[0]),[d,r?f:u]},Rc=(e,t)=>{let n=t.format===`NHWC`,r=B.size(e),i=B.size(t.kernelShape),a=[{type:12,data:r},{type:12,data:i}],o=[{name:`outputSize`,type:`u32`},{name:`kernelSize`,type:`u32`}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],r=t.pads[t.pads.length/2-1],i=t.pads[t.pads.length-1],s=!!(r+i);a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kw`,type:`u32`},{name:`sw`,type:`u32`},{name:`pwStart`,type:`u32`},{name:`pwEnd`,type:`u32`});let c=!1;if(t.kernelShape.length===2){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],r=t.pads[t.pads.length/2-2],i=t.pads[t.pads.length-2];c=!!(r+i),a.push({type:12,data:e},{type:12,data:n},{type:12,data:r},{type:12,data:i}),o.push({name:`kh`,type:`u32`},{name:`sh`,type:`u32`},{name:`phStart`,type:`u32`},{name:`phEnd`,type:`u32`})}return[a,o,!0,s,c]}{if(n)throw Error(`Pooling with kernelShape.length > 2 is not supported for NHWC format.`);let e=B.computeStrides(t.kernelShape);return a.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:`kernelStrides`,type:`u32`,length:e.length},{name:`pads`,type:`u32`,length:t.pads.length},{name:`strides`,type:`u32`,length:t.strides.length}),[a,o,!!t.pads.reduce((e,t)=>e+t),!1,!1]}},zc=(e,t,n,r,i,a,o,s,c,l,u,d)=>{let f=i.format===`NHWC`,p=t.type.value,m=X(`output`,t.type.tensor,r);if(i.kernelShape.length<=2){let r=``,l=``,h=``,g=n-(f?2:1);if(r=u?`
|
|
2139
2139
|
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2140
2140
|
xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;
|
|
2141
2141
|
if (xIndices[${g}] < 0 || xIndices[${g}]
|
|
@@ -2179,7 +2179,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2179
2179
|
${o}
|
|
2180
2180
|
|
|
2181
2181
|
output[global_idx] = value;
|
|
2182
|
-
}`}
|
|
2182
|
+
}`}{if(f)throw Error(`Pooling with kernelShape.length > 2 is not supported for NHWC format.`);let r=i.kernelShape.length,u=i.pads.length,d=``;return d=l?`
|
|
2183
2183
|
if (xIndices[j] >= uniforms.x_shape[j]) {
|
|
2184
2184
|
pad++;
|
|
2185
2185
|
isPad = true;
|
|
@@ -2349,7 +2349,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2349
2349
|
const adjustment = ${t}(lengthResized) / outputWidth;
|
|
2350
2350
|
const center = ${t}(lengthOriginal) / 2;
|
|
2351
2351
|
const offset = center * (1 - adjustment);
|
|
2352
|
-
return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case`half_pixel`:return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw Error(`Coordinate transform mode ${e} is not supported`)}})()+`}`,xl=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case`round_prefer_ceil`:return`if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }`;case`floor`:return`return floor(xOriginal);`;case`ceil`:return`return ceil(xOriginal);`;case`round_prefer_floor`:return`if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }`;default:if(t<11)return`if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }`;throw Error(`Nearest mode ${e} is not supported`)}})()+`}`,Sl=(e,t,n)=>{let r=Array(n).fill(0).concat(Array(n).fill(1)),i=e.length===0?r:e.slice();return t.length>0?(t.forEach((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]}),r):i},Cl=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach(e=>i.push(e)),Math.max(...r)>e.length)throw Error(`axes is out of bound`);r.forEach((e,t)=>i[e]=n[t])}else n.forEach(e=>i.push(e))
|
|
2352
|
+
return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case`half_pixel`:return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw Error(`Coordinate transform mode ${e} is not supported`)}})()+`}`,xl=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case`round_prefer_ceil`:return`if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }`;case`floor`:return`return floor(xOriginal);`;case`ceil`:return`return ceil(xOriginal);`;case`round_prefer_floor`:return`if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }`;default:if(t<11)return`if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }`;throw Error(`Nearest mode ${e} is not supported`)}})()+`}`,Sl=(e,t,n)=>{let r=Array(n).fill(0).concat(Array(n).fill(1)),i=e.length===0?r:e.slice();return t.length>0?(t.forEach((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]}),r):i},Cl=(e,t,n,r)=>{let i=[];if(n.length>0){if(r.length>0){if(e.forEach(e=>i.push(e)),Math.max(...r)>e.length)throw Error(`axes is out of bound`);r.forEach((e,t)=>i[e]=n[t])}else n.forEach(e=>i.push(e))}else{if(t.length===0)throw Error(`Resize requires either scales or sizes.`);i=e.map((e,n)=>Math.round(e*t[n]))}return i},wl=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case`not_larger`:return n.axes.length>0?Math.min(...n.axes.map(e=>t[e]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case`not_smaller`:return n.axes.length>0?Math.max(...n.axes.map(e=>t[e]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach(e=>t[e]=r),n.axes.forEach(n=>i[n]=Math.round(e[n]*t[n]))):(t.fill(r,0,t.length),i.forEach((e,n)=>i[n]=Math.round(e*t[n]))),i},Tl=(e,t,n,r,i)=>`
|
|
2353
2353
|
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {
|
|
2354
2354
|
var original_indices: array<${e.type.value}, ${n.length}>;
|
|
2355
2355
|
for (var i:u32 = 0; i < ${n.length}; i++) {
|
|
@@ -2637,7 +2637,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2637
2637
|
${a}(inv_std_dev) * gamma[offset1d + i]
|
|
2638
2638
|
${d?`+ beta[offset1d + i]`:``};
|
|
2639
2639
|
}
|
|
2640
|
-
}`},y=[{dims:s,dataType:e[0].dataType}];return n>1&&y.push({dims:u,dataType:1}),n>2&&y.push({dims:u,dataType:1}),n>3&&y.push({dims:a,dataType:e[0].dataType}),{name:`SkipLayerNormalization`,shaderCache:{hint:`${g};${p};${m};${h}`,inputDependencies:e.map((e,t)=>`type`)},getShaderSource:v,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(c/l)},programUniforms:_})}},zl=(e,t)=>{Ll(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Rl(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl=s(()=>{R(),V(),U(),Z(),Vl=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw Error(`axes, starts and ends must have the same length`)}else if(t.starts.length!==t.ends.length)throw Error(`starts and ends must have the same length`);e.slice(1).forEach((t,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw Error(`Input ${n} must be an array of int32 or int64`)})},Hl=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(e=>n.push(Number(e)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(e=>n.push(Number(e)));else throw Error(`Input ${t} must be an array of int32 or int64`)
|
|
2640
|
+
}`},y=[{dims:s,dataType:e[0].dataType}];return n>1&&y.push({dims:u,dataType:1}),n>2&&y.push({dims:u,dataType:1}),n>3&&y.push({dims:a,dataType:e[0].dataType}),{name:`SkipLayerNormalization`,shaderCache:{hint:`${g};${p};${m};${h}`,inputDependencies:e.map((e,t)=>`type`)},getShaderSource:v,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(c/l)},programUniforms:_})}},zl=(e,t)=>{Ll(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Rl(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Vl,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl=s(()=>{R(),V(),U(),Z(),Vl=(e,t)=>{if(!e||e.length<1)throw Error(`too few inputs`);if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw Error(`axes, starts and ends must have the same length`)}else if(t.starts.length!==t.ends.length)throw Error(`starts and ends must have the same length`);e.slice(1).forEach((t,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw Error(`Input ${n} must be an array of int32 or int64`)})},Hl=(e,t)=>{let n=[];if(e.length>t){if(e[t].dataType===7)e[t].getBigInt64Array().forEach(e=>n.push(Number(e)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(e=>n.push(Number(e)));else throw Error(`Input ${t} must be an array of int32 or int64`)}return n},Ul=(e,t)=>{if(e.length>1){let t=Hl(e,1),n=Hl(e,2),r=Hl(e,3);return r.length===0&&(r=[...Array(e[0].dims.length).keys()]),H({starts:t,ends:n,axes:r})}return t},Wl=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},Gl=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {
|
|
2641
2641
|
var input_indices: ${e.type.indices};
|
|
2642
2642
|
var carry = 0u;
|
|
2643
2643
|
for (var i = ${n.length-1}; i >= 0; i--) {
|
|
@@ -2655,7 +2655,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2655
2655
|
${e.indicesSet(`input_indices`,`i`,`input_index`)};
|
|
2656
2656
|
}
|
|
2657
2657
|
return input_indices;
|
|
2658
|
-
}`,Kl=(e,t)=>{let n=e[0].dims,r=B.size(n),i=t.axes.length>0?B.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=Hl(e,4);a.forEach(e=>e!==0||(()=>{throw Error(`step cannot be 0`)})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((e,t)=>Wl(e,t,n,i,a)),s=t.ends.map((e,t)=>Wl(e,t,n,i,a));if(i.length!==o.length||i.length!==s.length)throw Error(`start, ends and axes should have the same number of elements`);if(i.length!==n.length)for(let e=0;e<n.length;++e)i.includes(e)||(o.splice(e,0,0),s.splice(e,0,n[e]),a.splice(e,0,1));let c=a.map(e=>Math.sign(e));a.forEach((e,t,n)=>{if(e<0){let r=(s[t]-o[t])/e,i=o[t]
|
|
2658
|
+
}`,Kl=(e,t)=>{let n=e[0].dims,r=B.size(n),i=t.axes.length>0?B.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=Hl(e,4);a.forEach(e=>e!==0||(()=>{throw Error(`step cannot be 0`)})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((e,t)=>Wl(e,t,n,i,a)),s=t.ends.map((e,t)=>Wl(e,t,n,i,a));if(i.length!==o.length||i.length!==s.length)throw Error(`start, ends and axes should have the same number of elements`);if(i.length!==n.length)for(let e=0;e<n.length;++e)i.includes(e)||(o.splice(e,0,0),s.splice(e,0,n[e]),a.splice(e,0,1));let c=a.map(e=>Math.sign(e));a.forEach((e,t,n)=>{if(e<0){let r=(s[t]-o[t])/e,i=o[t],c=i+r*a[t];o[t]=c,s[t]=i,n[t]=-e}});let l=n.slice(0);i.forEach((e,t)=>{l[e]=Math.ceil((s[e]-o[e])/a[e])});let u={dims:l,dataType:e[0].dataType},d=X(`output`,e[0].dataType,l.length),f=Y(`input`,e[0].dataType,e[0].dims.length),p=B.size(l),m=[{name:`outputSize`,type:`u32`},{name:`starts`,type:`u32`,length:o.length},{name:`signs`,type:`i32`,length:c.length},{name:`steps`,type:`u32`,length:a.length}],h=[{type:12,data:p},{type:12,data:o},{type:6,data:c},{type:12,data:a},...K(e[0].dims,l)];return{name:`Slice`,shaderCache:{hint:`${c.length}_${o.length}_${a.length}`,inputDependencies:[`rank`]},getShaderSource:e=>`
|
|
2659
2659
|
${e.registerUniforms(m).declareVariables(f,d)}
|
|
2660
2660
|
${Gl(f,d,n)}
|
|
2661
2661
|
${e.mainStart()}
|
|
@@ -2782,4 +2782,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2782
2782
|
}`},cu=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(B.areEqual(t,n)&&B.areEqual(n,r)),o=t,s=B.size(t);if(a){let e=Nt.calcShape(Nt.calcShape(t,n,!1),r,!1);if(!e)throw Error(`Can't perform where op on the given tensors`);o=e,s=B.size(o)}let c=Math.ceil(s/4);return{name:`Where`,shaderCache:{inputDependencies:[`rank`,`rank`,`rank`]},getShaderSource:t=>su(t,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(s/64/4)},programUniforms:[{type:12,data:c},...K(r,t,n,o)]})}},lu=e=>{e.compute(cu(e.inputs))}}),du,fu=s(()=>{Pr(),Ur(),Jr(),Qr(),qi(),sa(),ma(),oo(),yo(),Co(),ko(),Vo(),qo(),Xo(),ts(),as(),us(),hs(),bs(),Fs(),sc(),fc(),gc(),yc(),Tc(),Us(),Fc(),tl(),ol(),ul(),hl(),kr(),Il(),tc(),Bl(),Yl(),eu(),Zs(),ou(),Pn(),Ui(),uu(),du=new Map([[`Abs`,[ei]],[`Acos`,[ti]],[`Acosh`,[ni]],[`Add`,[Zi]],[`ArgMax`,[Mr,Nr]],[`ArgMin`,[jr,Nr]],[`Asin`,[ri]],[`Asinh`,[ii]],[`Atan`,[ai]],[`Atanh`,[oi]],[`Attention`,[Hr]],[`AveragePool`,[Kc,Gc]],[`BatchNormalization`,[qr]],[`BiasAdd`,[Zr]],[`BiasSplitGelu`,[Ki]],[`Cast`,[ci,si]],[`Ceil`,[di]],[`Clip`,[ui]],[`Concat`,[fa,pa]],[`Conv`,[ao,to]],[`ConvTranspose`,[vo,mo]],[`Cos`,[fi]],[`Cosh`,[pi]],[`CumSum`,[xo,So]],[`DepthToSpace`,[Do,Oo]],[`DequantizeLinear`,[il,al]],[`Div`,[Qi]],[`Einsum`,[zo,Bo]],[`Elu`,[hi,mi]],[`Equal`,[$i]],[`Erf`,[_i]],[`Exp`,[vi]],[`Expand`,[Ko]],[`FastGelu`,[Yo]],[`Floor`,[yi]],[`FusedConv`,[ao,to]],[`Gather`,[es,$o]],[`GatherElements`,[ms,ps]],[`GatherBlockQuantized`,[cs,ls]],[`GatherND`,[rs,is]],[`Gelu`,[bi]],[`Gemm`,[ys,vs]],[`GlobalAveragePool`,[Yc,Jc]],[`GlobalMaxPool`,[el,$c]],[`Greater`,[ra]],[`GreaterOrEqual`,[aa]],[`GridSample`,[Ns,Ps]],[`GroupQueryAttention`,[oc]],[`HardSigmoid`,[Oi,Di]],[`InstanceNormalization`,[dc]],[`LayerNormalization`,[hc]],[`LeakyRelu`,[xi,mi]],[`Less`,[ia]],[`LessOrEqual`,[oa]],[`Log`,[zi]],[`MatMul`,[vc]],[`MatMulNBits`,[Cc,wc]],[`MaxPool`,[Zc,Qc]],[`Mul`,[ea]],[`MultiHeadAttention`,[Hs,Rs]],[`Neg`,[Ci]],[`Not`,[Si]],[`Pad`,[Pc]],[`Pow`,[ta]],[`QuickGelu`,[Hi,mi]],[`Range`,[ll]],[`Reciprocal`,[wi]],[`ReduceMin`,[wr]],[`ReduceMean`,[yr]],[`ReduceMax`,[Cr]],[`ReduceSum`,[Er]],[`ReduceProd`,[Tr]],[`ReduceL1`,[br]],[`ReduceL2`,[xr]],[`ReduceLogSum`,[Or]],[`ReduceLogSumExp`,[Sr]],[`ReduceSumSquare`,[Dr]],[`Relu`,[Ti]],[`Resize`,[Pl,Fl]],[`RotaryEmbedding`,[ec]],[`ScatterND`,[ml,pl]],[`Sigmoid`,[Ei]],[`Sin`,[ki]],[`Sinh`,[Ai]],[`Slice`,[ql,Jl]],[`SkipLayerNormalization`,[zl]],[`Split`,[Ys,Xs]],[`Sqrt`,[ji]],[`Softmax`,[Ql,$l]],[`Sub`,[na]],[`Tan`,[Mi]],[`Tanh`,[Pi]],[`ThresholdedRelu`,[Ri,mi]],[`Tile`,[au]],[`Transpose`,[Mn,Nn]],[`Where`,[lu]]])}),pu,mu=s(()=>{N(),jt(),Z(),pu=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){j(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let s=[];for(let e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(let e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});i&&s.push({binding:s.length,resource:i});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s,label:e.programInfo.name});if(this.backend.sessionStatus===`capturing`){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}o.setPipeline(e.computePipeline),o.setBindGroup(0,c),o.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===`at-passes`)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),M(e.programInfo.name)}dispose(){}build(e,t){j(e.name);let n=this.backend.device,r=[];[{feature:`shader-f16`,extension:`f16`},{feature:`subgroups`,extension:`subgroups`}].forEach(e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)});let i=wn(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${r.join(`
|
|
2783
2783
|
`)}
|
|
2784
2784
|
${i.additionalImplementations}
|
|
2785
|
-
${a}`,s=n.createShaderModule({code:o,label:e.name});z(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return M(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}else return[o,o,1]}}}),hu={};c(hu,{WebGpuBackend:()=>yu});var gu,_u,vu,yu,bu=s(()=>{N(),R(),jt(),zt(),pn(),fu(),mu(),gu=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},_u=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${gu(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},vu=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},yu=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new vu(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fn(this),this.programManager=new pu(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,kt(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;j(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:gt(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:gt(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${gt(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${gt(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}ge(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),M()}run(e,t,n,r,i,a){j(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return M(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${gt(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=_u(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),z(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(z(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),M(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=du.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),z(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await un(this,e,t);return Rt(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){z(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){z(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){z(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),xu={};c(xu,{init:()=>wu});var Su,Cu,wu,Tu=s(()=>{R(),jt(),V(),tn(),Su=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(B.size(t)!==B.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},Cu=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new Su(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new Su(this.module,t,this.output(e,n),n),(e,t)=>{let n=_t(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new Su(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},wu=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(bu(),u(hu)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)z(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{z(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{z(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{z(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new Cu(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new en(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),Eu,Du,Ou,ku,Au,ju,Mu,Nu,Pu,Fu,Iu,Lu,Ru,zu=s(()=>{N(),st(),mt(),R(),rt(),at(),wt(),Eu=(e,t)=>{F()._OrtInit(e,t)!==0&&L(`Can't initialize onnxruntime.`)},Du=async e=>{Eu(e.wasm.numThreads,yt(e.logLevel))},Ou=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);{let r=(Tu(),u(xu)).init;t===`webgpu`&&await r(`webgpu`,F(),e,n),t===`webnn`&&await r(`webnn`,F(),e)}},ku=new Map,Au=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&L(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},ju=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&L(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Mu=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Nu=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Mu(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await pt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Ct(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&L(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Au(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=ju(a,t);e===0&&L(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:gt(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=ju(a,n+e);r===0&&L(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:gt(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&L(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>St(e))}),ku.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&L(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&L(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&L(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Pu=e=>{let t=F(),n=ku.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&L(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&L(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&L(`Can't release session.`),ku.delete(e)},Fu=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=_t(ht(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=_t(ht(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,ht(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,I(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ht(l);m=_t(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ht(l),p,m,g,u.length,St(f));e===0&&L(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Iu=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=ku.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),ee=o.stackAlloc(g*s);try{[_,v]=ot(a),ve(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await Fu(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await Fu(i[t],b,x,e,d[r[t]],h+r[t],p);ye(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(ee+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);ve(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&L(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&L(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&L(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}ye(`wasm bindInputsOutputs`),ku.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,ee,g,E,_),c!==0&&L(`failed to call OrtRun().`);let C=[],D=[];ve(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&L(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&L(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=gt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=_t(a,g);if(r===void 0||!bt(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(_t(a,g)===void 0||!xt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,D.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(vt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&L(`Can't clear bound outputs.`),ku.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(D))C[e][2]=t;return ye(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Lu=e=>{let t=F(),n=ku.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&L(`Can't get an profile file name.`),t._OrtFree(i)},Ru=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Bu,Vu,Hu,Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id=s(()=>{N(),zu(),rt(),Je(),Bu=()=>!!C.wasm.proxy&&typeof document<`u`,Hu=!1,Uu=!1,Wu=!1,qu=new Map,Ju=(e,t)=>{let n=qu.get(e);n?n.push(t):qu.set(e,[t])},Yu=()=>{if(Hu||!Uu||Wu||!Vu)throw Error(`worker not ready`)},Xu=e=>{switch(e.data.type){case`init-wasm`:Hu=!1,e.data.err?(Wu=!0,Ku[1](e.data.err)):(Uu=!0,Ku[0]()),Gu&&=(URL.revokeObjectURL(Gu),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=qu.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Zu=async()=>{if(!Uu){if(Hu)throw Error(`multiple calls to 'initWasm()' detected.`);if(Wu)throw Error(`previous call to 'initWasm()' failed.`);if(Hu=!0,Bu())return new Promise((e,t)=>{Vu?.terminate(),Ge().then(([n,r])=>{try{Vu=r,Vu.onerror=e=>t(e),Vu.onmessage=Xu,Ku=[e,t];let i={type:`init-wasm`,in:C};if(!i.in.wasm.wasmPaths&&n){let e=Re();e&&(i.in.wasm.wasmPaths=e)}Vu.postMessage(i),Gu=n}catch(e){t(e)}},t)});try{await nt(C.wasm),await Du(C),Uu=!0}catch(e){throw Wu=!0,e}finally{Hu=!1}}},Qu=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:C}};Vu.postMessage(r)});await Ou(C,e)},$u=async e=>Bu()?(Yu(),new Promise((t,n)=>{Ju(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Vu.postMessage(r,[e.buffer])})):Mu(e),ed=async(e,t)=>{if(Bu()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Yu(),new Promise((n,r)=>{Ju(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Vu.postMessage(i,a)})}else return Nu(e,t)},td=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`release`,[t,n]);let r={type:`release`,in:e};Vu.postMessage(r)});Pu(e)},nd=async(e,t,n,r,i,a)=>{if(Bu()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Yu(),new Promise((i,o)=>{Ju(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Vu.postMessage(c,Ru(s))})}else return Iu(e,t,n,r,i,a)},rd=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Vu.postMessage(r)});Lu(e)}}),ad,od,sd,cd=s(()=>{N(),id(),R(),Ae(),wt(),ad=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},od=e=>{switch(e[3]){case`cpu`:return new A(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!bt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return A.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!xt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return A.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},sd=class{async fetchModelAndCopyToWasmMemory(e){return $u(await Ct(e))}async loadModel(e,t){j();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ed(n,t),M()}async dispose(){return td(this.sessionId)}async run(e,t,n){j();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>ad(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?ad(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await nd(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??od(l[e]);return M(),u}startProfiling(){}endProfiling(){rd(this.sessionId)}}}),ld={};c(ld,{OnnxruntimeWebAssemblyBackend:()=>dd,initializeFlags:()=>ud,wasmBackend:()=>fd});var ud,dd,fd,pd=s(()=>{N(),id(),cd(),ud=()=>{(typeof C.wasm.initTimeout!=`number`||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!=`boolean`&&(C.wasm.proxy=!1),typeof C.wasm.trace!=`boolean`&&(C.wasm.trace=!1),typeof C.wasm.numThreads!=`number`||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},dd=class{async init(e){ud(),await Zu(),await Qu(e)}async createInferenceSessionHandler(e,t){let n=new sd;return await n.loadModel(e,t),n}},fd=new dd}),md={};c(md,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,default:()=>gd,env:()=>C,registerBackend:()=>p}),N(),N(),N();var hd=`1.26.0`,gd=ke;{let e=(pd(),u(ld)).wasmBackend;p(`webgpu`,e,5),p(`webnn`,e,5),p(`cpu`,e,10),p(`wasm`,e,10)}return Object.defineProperty(C.versions,"web",{value:hd,enumerable:!0}),u(md)})();typeof t==`object`&&typeof i==`object`&&(i.exports=a)})),u=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),d=t((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroLegacy=void 0;var n=o(),r=class{constructor(e,t,n,r,i){this.ortInstance=e,this._session=t,this._h=n,this._c=r,this._sr=i,this.reset_state=()=>{let e=Array(128).fill(0);this._h=new this.ortInstance.Tensor(`float32`,e,[2,1,64]),this._c=new this.ortInstance.Tensor(`float32`,e,[2,1,64])},this.process=async e=>{let t={input:new this.ortInstance.Tensor(`float32`,e,[1,e.length]),h:this._h,c:this._c,sr:this._sr},n=await this._session.run(t);this._h=n.hn,this._c=n.cn;let[r]=n.output?.data;return{notSpeech:1-r,isSpeech:r}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}};e.SileroLegacy=r,t=r,r.new=async(e,r)=>{n.log.debug(`initializing vad`);let i=await r(),a=await e.InferenceSession.create(i),o=new e.Tensor(`int64`,[16000n]),s=Array(128).fill(0),c=new e.Tensor(`float32`,s,[2,1,64]),l=new e.Tensor(`float32`,s,[2,1,64]);return n.log.debug(`vad is initialized`),new t(e,a,c,l,o)}})),f=t((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=void 0;var n=o();function r(e){let t=Array(256).fill(0);return new e.Tensor(`float32`,t,[2,1,128])}var i=class{constructor(e,t,n,i){this._session=e,this._state=t,this._sr=n,this.ortInstance=i,this.reset_state=()=>{this._state=r(this.ortInstance)},this.process=async e=>{let t={input:new this.ortInstance.Tensor(`float32`,e,[1,e.length]),state:this._state,sr:this._sr},n=await this._session.run(t);if(!n.stateN)throw Error(`No state from model`);if(this._state=n.stateN,!n.output?.data)throw Error(`No output from model`);let r=n.output.data[0];if(typeof r!=`number`)throw Error(`Weird output data`);return{notSpeech:1-r,isSpeech:r}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}};e.SileroV5=i,t=i,i.new=async(e,i)=>{n.log.debug(`Loading VAD...`);let a=await i(),o=await e.InferenceSession.create(a),s=new e.Tensor(`int64`,[16000n]),c=r(e);return n.log.debug(`...finished loading VAD`),new t(o,c,s,e)}})),p=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=e.SileroLegacy=void 0,n(u(),e);var r=d();Object.defineProperty(e,"SileroLegacy",{enumerable:!0,get:function(){return r.SileroLegacy}});var i=f();Object.defineProperty(e,"SileroV5",{enumerable:!0,get:function(){return i.SileroV5}})})),m=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Resampler=void 0;var t=o();e.Resampler=class{constructor(e){this.options=e,this.process=e=>{let t=[];for(let n of e)for(this.inputBuffer.push(n);this.hasEnoughDataForFrame();){let e=this.generateOutputFrame();t.push(e)}return t},e.nativeSampleRate<16e3&&t.log.error(`nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate`),this.inputBuffer=[]}async*stream(e){for(let t of e)for(this.inputBuffer.push(t);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){let e=new Float32Array(this.options.targetFrameSize),t=0,n=0;for(;t<this.options.targetFrameSize;){let r=0,i=0;for(;n<Math.min(this.inputBuffer.length,(t+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){let e=this.inputBuffer[n];e!==void 0&&(r+=e,i++),n++}e[t]=r/i,t++}return this.inputBuffer=this.inputBuffer.slice(n),e}}})),h=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.NonRealTimeVAD=e.defaultNonRealTimeVADOptions=void 0;var o=r(l()),u=i(),d=a(),f=c(),h=s(),g=p(),_=m();e.defaultNonRealTimeVADOptions={...f.defaultFrameProcessorOptions,modelURL:u.baseAssetPath+`silero_vad_legacy.onnx`,modelFetcher:d.defaultModelFetcher},e.NonRealTimeVAD=class{static async new(t={}){let n={...e.defaultNonRealTimeVADOptions,...t};(0,f.validateOptions)(n),n.ortConfig!==void 0&&n.ortConfig(o);let r=()=>n.modelFetcher(n.modelURL),i=await g.SileroLegacy.new(o,r),a=new f.FrameProcessor(i.process,i.reset_state,{positiveSpeechThreshold:n.positiveSpeechThreshold,negativeSpeechThreshold:n.negativeSpeechThreshold,redemptionMs:n.redemptionMs,preSpeechPadMs:n.preSpeechPadMs,minSpeechMs:n.minSpeechMs,submitUserSpeechOnPause:n.submitUserSpeechOnPause},1536/16);return a.resume(),new this(r,o,n,a)}constructor(e,t,n,r){this.modelFetcher=e,this.ort=t,this.options=n,this.frameProcessor=r,this.frameSamples=1536}async*run(e,t){let n={nativeSampleRate:t,targetSampleRate:16e3,targetFrameSize:this.frameSamples},r=new _.Resampler(n),i=0,a=0,o=0;for await(let t of r.stream(e)){let e=[];await this.frameProcessor.process(t,t=>{e.push(t)});for(let t of e)switch(t.msg){case h.Message.SpeechStart:i=o*this.frameSamples/16;break;case h.Message.SpeechEnd:a=(o+1)*this.frameSamples/16,yield{audio:t.audio,start:i,end:a};break;default:break}o++}let s=[];this.frameProcessor.endSegment(e=>{s.push(e)});for(let e of s)switch(e.msg){case h.Message.SpeechEnd:yield{audio:e.audio,start:i,end:o*this.frameSamples/16}}}}})),g=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.audioFileToArray=e.encodeWAV=e.arrayBufferToBase64=e.minFramesForTargetMS=void 0;function t(e,t,n=16e3){return Math.ceil(e*n/1e3/t)}e.minFramesForTargetMS=t;function n(e){let t=new Uint8Array(e),n=t.byteLength,r=Array(n);for(let e=0;e<n;e++){let n=t[e];if(n===void 0)break;r[e]=String.fromCharCode(n)}return btoa(r.join(``))}e.arrayBufferToBase64=n;function r(e,t=3,n=16e3,r=1,s=32){let c=s/8,l=r*c,u=new ArrayBuffer(44+e.length*c),d=new DataView(u);return o(d,0,`RIFF`),d.setUint32(4,36+e.length*c,!0),o(d,8,`WAVE`),o(d,12,`fmt `),d.setUint32(16,16,!0),d.setUint16(20,t,!0),d.setUint16(22,r,!0),d.setUint32(24,n,!0),d.setUint32(28,n*l,!0),d.setUint16(32,l,!0),d.setUint16(34,s,!0),o(d,36,`data`),d.setUint32(40,e.length*c,!0),t===1?a(d,44,e):i(d,44,e),u}e.encodeWAV=r;function i(e,t,n){for(let r=0;r<n.length;r++,t+=4)e.setFloat32(t,n[r],!0)}function a(e,t,n){for(let r=0;r<n.length;r++,t+=2){let i=Math.max(-1,Math.min(1,n[r]));e.setInt16(t,i<0?i*32768:i*32767,!0)}}function o(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}async function s(e){let t=new OfflineAudioContext(1,1,44100),n=new FileReader,r=null;if(await new Promise(i=>{n.addEventListener(`loadend`,()=>{let e=n.result;t.decodeAudioData(e,e=>{r=e,t.startRendering().then(()=>{console.log(`Rendering completed successfully`),i()}).catch(e=>{console.error(`Rendering failed: `,e)})},e=>{console.log(`Error with decoding audio data: `,e)})}),n.readAsArrayBuffer(e)}),r===null)throw Error(`some shit`);let i=r,a=new Float32Array(i.length);for(let e=0;e<i.length;e++)for(let t=0;t<i.numberOfChannels;t++){let n=i.getChannelData(t)[e],r=a[e];if(n===void 0||r===void 0)throw Error(`sample or out[i] is undefined`);a[e]=r+n}return{audio:a,sampleRate:i.sampleRate}}e.audioFileToArray=s})),_=t(((t,i)=>{n();var a=(()=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),s=(e,t)=>()=>(e&&(t=e(e=0)),t),c=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},l=(e,r,o,s)=>{if(r&&typeof r==`object`||typeof r==`function`)for(let c of i(r))!a.call(e,c)&&c!==o&&t(e,c,{get:()=>r[c],enumerable:!(s=n(r,c))||s.enumerable});return e},u=e=>l(t({},`__esModule`,{value:!0}),e),d,f,p,m,h,g=s(()=>{d=new Map,f=[],p=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}return}throw TypeError(`not a valid backend`)},m=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},h=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=new Set;for(let e of r){let t=await m(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),_=s(()=>{g()}),v,y=s(()=>{v=`1.26.0`}),b,x,S=s(()=>{y(),b=`warning`,x={wasm:{},webgl:{},webgpu:{},versions:{common:v},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);b=e}},get logLevel(){return b}},Object.defineProperty(x,"logLevel",{enumerable:!0})}),C,w=s(()=>{S(),C=x}),T,E,ee=s(()=>{T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},E=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),D,O,te,ne,re,ie,ae=s(()=>{me(),D=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new k(`float32`,u,[1,4,n,r]):new k(`float32`,u,[1,3,n,r])},O=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,D(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(D(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return D(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new k({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},re=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ie=(e,t,n)=>new k({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),oe,se,ce,le,ue=s(()=>{oe=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),se=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ce=!1,le=()=>{if(!ce){ce=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(oe.set(`int64`,BigInt64Array),se.set(BigInt64Array,`int64`)),t&&(oe.set(`uint64`,BigUint64Array),se.set(BigUint64Array,`uint64`)),r?(oe.set(`float16`,n),se.set(n,`float16`)):oe.set(`float16`,Uint16Array)}}}),de,fe,pe=s(()=>{me(),de=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},fe=(e,t)=>{switch(e.location){case`cpu`:return new k(e.type,e.data,t);case`cpu-pinned`:return new k({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new k({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new k({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new k({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),k,me=s(()=>{ee(),ae(),ue(),pe(),k=class{constructor(e,t,n){le();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=oe.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=oe.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=se.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=de(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return O(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return re(e,t)}static fromPinnedBuffer(e,t,n){return ie(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return E(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return fe(this,e)}}}),A,he=s(()=>{me(),A=k}),ge,_e,j,M,ve,ye,be=s(()=>{S(),ge=(e,t)=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeStamp(`${e}::ORT::${t}`)},_e=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ge(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},j=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`BEGIN`,e)},M=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`END`,e)},ve=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.time(`ORT::${e}`)},ye=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeEnd(`ORT::${e}`)}}),xe,Se=s(()=>{g(),he(),be(),xe=class e{constructor(e){this.handler=e}async run(e,t,n){j(),ve(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof A||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof A)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof A)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof A?s[e]=t:s[e]=new A(t.type,t.data,t.dims)}return ye(`InferenceSession.run`),M(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){j(),ve(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await h(o),l=await s.createInferenceSessionHandler(a,c);return ye(`InferenceSession.create`),M(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ce,we=s(()=>{Se(),Ce=xe}),Te=s(()=>{}),Ee=s(()=>{}),De=s(()=>{}),Oe=s(()=>{}),ke={};c(ke,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,env:()=>C,registerBackend:()=>p});var N=s(()=>{_(),w(),we(),he(),Te(),Ee(),be(),De(),Oe()}),Ae=s(()=>{}),je={};c(je,{default:()=>Pe});var Me,Ne,Pe,Fe=s(()=>{It(),rt(),Je(),Me=`ort-wasm-proxy-worker`,Ne=globalThis.self?.name===Me,Ne&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:nt(n.wasm).then(()=>{Et(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Dt(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=z(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;jt(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Mt(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;B(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Ft([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Pt(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),Pe=Ne?null:e=>new Worker(e??P,{type:`classic`,name:Me})}),Ie,Le,P,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je=s(()=>{Ae(),Ie=typeof location>`u`?void 0:location.origin,Le=()=>typeof document<`u`?document.currentScript?.src:typeof self<`u`?self.location?.href:void 0,P=Le(),Re=()=>{if(P&&!P.startsWith(`blob:`))return P.substring(0,P.lastIndexOf(`/`)+1)},ze=(e,t)=>{try{let n=t??P;return(n?new URL(e,n):new URL(e)).origin===Ie}catch{return!1}},Be=(e,t)=>{let n=t??P;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Ve=(e,t)=>`${t??`./`}${e}`,He=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Ue=async e=>(await r(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,We=(Fe(),u(je)).default,Ge=async()=>{if(!P)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(ze(P))return[void 0,We()];let e=await He(P);return[e,We(e)]},Ke=void 0,qe=async(e,t,n,r)=>{let i=Ke&&!(e||t);if(i)if(P)i=ze(P)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,Ke];{let r=`ort-wasm-simd-threaded.mjs`,i=e??Be(r,t),a=n&&i&&!ze(i,t),o=a?await He(i):i??Ve(r,t);return[a?o:void 0,await Ue(o)]}}}),Ye,Xe,Ze,Qe,$e,et,tt,nt,F,rt=s(()=>{Je(),Xe=!1,Ze=!1,Qe=!1,$e=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},et=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nt=async e=>{if(Xe)return Promise.resolve();if(Ze)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Qe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Ze=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!tt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!et())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=$e();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await qe(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Re();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Ze=!1,Xe=!0,Ye=t,e(),d&&URL.revokeObjectURL(d)},e=>{Ze=!1,Qe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Xe&&Ye)return Ye;throw Error(`WebAssembly is not initialized yet.`)}}),I,it,L,at=s(()=>{rt(),I=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},it=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)it(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},L=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),ot,st=s(()=>{rt(),at(),ot=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=I(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&L(`Can't create run options.`),e?.extra!==void 0&&it(e.extra,``,new WeakSet,(e,i)=>{let a=I(e,r),o=I(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&L(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ct,lt,ut,dt,ft,pt,mt=s(()=>{rt(),at(),ct=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},lt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ut=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},dt=(e,t,n,r)=>{let i=I(t,r),a=I(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&L(`Can't set a session config entry: ${t} - ${n}.`)},ft=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,dt(e,`session.disable_quant_qdq`,`1`,n),dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof t!=`string`){let r=t?.deviceType;r&&dt(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);dt(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=I(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&L(`Can't append execution provider: ${r}.`)}},pt=async e=>{let t=F(),n=0,r=[],i=e||{};ut(i);try{let e=ct(i.graphOptimizationLevel??`all`),a=lt(i.executionMode??`sequential`),o=typeof i.logId==`string`?I(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?I(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&L(`Can't create session options.`),i.executionProviders&&await ft(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=I(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&L(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&it(i.extra,``,new WeakSet,(e,t)=>{dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&L(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ht,gt,_t,vt,yt,bt,xt,St,R=s(()=>{ht=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},_t=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},vt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},yt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,xt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,St=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ct,wt=s(()=>{Ae(),Ct=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Tt,Et,Dt,Ot,kt,At,z,jt,Mt,Nt,B,Pt,Ft,It=s(()=>{N(),st(),mt(),R(),rt(),at(),wt(),Tt=(e,t)=>{F()._OrtInit(e,t)!==0&&L(`Can't initialize onnxruntime.`)},Et=async e=>{Tt(e.wasm.numThreads,yt(e.logLevel))},Dt=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`)},Ot=new Map,kt=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&L(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},At=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&L(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},z=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},jt=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=z(e);let a=0,o=0,s=[],c=[],l=[];try{if([o,s]=await pt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Ct(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&L(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,u]=kt(a),d=!!t?.enableGraphCapture,f=[],p=[],m=[],h=[];for(let t=0;t<e;t++){let[e,n,r]=At(a,t);e===0&&L(`Can't get an input name.`),c.push(e);let o=i.UTF8ToString(e);f.push(o),m.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:gt(n),shape:r})}for(let t=0;t<u;t++){let[n,r,o]=At(a,t+e);n===0&&L(`Can't get an output name.`),l.push(n);let s=i.UTF8ToString(n);p.push(s),h.push(r===0?{name:s,isTensor:!1}:{name:s,isTensor:!0,type:gt(r),shape:o})}return Ot.set(a,[a,c,l,null,d,!1]),[a,f,p,m,h]}catch(e){throw c.forEach(e=>i._OrtFree(e)),l.forEach(e=>i._OrtFree(e)),a!==0&&i._OrtReleaseSession(a)!==0&&L(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&L(`Can't release session options.`),s.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Mt=e=>{let t=F(),n=Ot.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&L(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&L(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&L(`Can't release session.`),Ot.delete(e)},Nt=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=_t(ht(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=_t(ht(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,ht(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,I(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ht(l);m=_t(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ht(l),p,m,g,u.length,St(f));e===0&&L(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},B=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=Ot.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];c[5];let m=t.length,h=r.length,g=0,_=[],v=[],y=[],b=[],x=[],S=o.stackSave(),C=o.stackAlloc(m*s),w=o.stackAlloc(m*s),T=o.stackAlloc(h*s),E=o.stackAlloc(h*s);try{[g,_]=ot(a),ve(`wasm prepareInputOutputTensor`);for(let r=0;r<m;r++)await Nt(n[r],v,b,e,u[t[r]],t[r],p);for(let t=0;t<h;t++)await Nt(i[t],y,b,e,d[r[t]],m+r[t],p);ye(`wasm prepareInputOutputTensor`);for(let e=0;e<m;e++)o.setValue(C+e*s,v[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<h;e++)o.setValue(T+e*s,y[e],`*`),o.setValue(E+e*s,d[r[e]],`*`);o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=await o._OrtRun(l,w,C,m,E,h,T,g),c!==0&&L(`failed to call OrtRun().`);let S=[],ee=[];ve(`wasm ProcessOutputTensor`);for(let t=0;t<h;t++){let n=Number(o.getValue(T+t*s,`*`));if(n===y[t]||x.includes(y[t])){S.push(i[t]),n!==y[t]&&o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&L(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&L(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=gt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}S.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=_t(a,g);if(r===void 0||!bt(u))throw Error(`Unsupported data type: ${u}`);l=!0,S.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(_t(a,g)===void 0||!xt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,S.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=S.length;l=!0,ee.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(vt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&L(`Can't clear bound outputs.`),Ot.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(ee))S[e][2]=t;return ye(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),v.forEach(e=>o._OrtReleaseTensor(e)),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._free(e)),g!==0&&o._OrtReleaseRunOptions(g),_.forEach(e=>o._free(e))}},Pt=e=>{let t=F(),n=Ot.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&L(`Can't get an profile file name.`),t._OrtFree(i)},Ft=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Lt,V,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en=s(()=>{N(),It(),rt(),Je(),Lt=()=>!!C.wasm.proxy&&typeof document<`u`,Rt=!1,zt=!1,Bt=!1,Ut=new Map,Wt=(e,t)=>{let n=Ut.get(e);n?n.push(t):Ut.set(e,[t])},Gt=()=>{if(Rt||!zt||Bt||!V)throw Error(`worker not ready`)},Kt=e=>{switch(e.data.type){case`init-wasm`:Rt=!1,e.data.err?(Bt=!0,Ht[1](e.data.err)):(zt=!0,Ht[0]()),Vt&&=(URL.revokeObjectURL(Vt),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Ut.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},qt=async()=>{if(!zt){if(Rt)throw Error(`multiple calls to 'initWasm()' detected.`);if(Bt)throw Error(`previous call to 'initWasm()' failed.`);if(Rt=!0,Lt())return new Promise((e,t)=>{V?.terminate(),Ge().then(([n,r])=>{try{V=r,V.onerror=e=>t(e),V.onmessage=Kt,Ht=[e,t];let i={type:`init-wasm`,in:C};if(!i.in.wasm.wasmPaths&&n){let e=Re();e&&(i.in.wasm.wasmPaths=e)}V.postMessage(i),Vt=n}catch(e){t(e)}},t)});try{await nt(C.wasm),await Et(C),zt=!0}catch(e){throw Bt=!0,e}finally{Rt=!1}}},Jt=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:C}};V.postMessage(r)});await Dt(C,e)},Yt=async e=>Lt()?(Gt(),new Promise((t,n)=>{Wt(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};V.postMessage(r,[e.buffer])})):z(e),Xt=async(e,t)=>{if(Lt()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Gt(),new Promise((n,r)=>{Wt(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),V.postMessage(i,a)})}else return jt(e,t)},Zt=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`release`,[t,n]);let r={type:`release`,in:e};V.postMessage(r)});Mt(e)},Qt=async(e,t,n,r,i,a)=>{if(Lt()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Gt(),new Promise((i,o)=>{Wt(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};V.postMessage(c,Ft(s))})}else return B(e,t,n,r,i,a)},$t=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};V.postMessage(r)});Pt(e)}}),tn,nn,rn,an=s(()=>{N(),en(),R(),Ae(),wt(),tn=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},nn=e=>{switch(e[3]){case`cpu`:return new A(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!bt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return A.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!xt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return A.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},rn=class{async fetchModelAndCopyToWasmMemory(e){return Yt(await Ct(e))}async loadModel(e,t){j();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Xt(n,t),M()}async dispose(){return Zt(this.sessionId)}async run(e,t,n){j();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>tn(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?tn(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Qt(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??nn(l[e]);return M(),u}startProfiling(){}endProfiling(){$t(this.sessionId)}}}),on={};c(on,{OnnxruntimeWebAssemblyBackend:()=>cn,initializeFlags:()=>sn,wasmBackend:()=>ln});var sn,cn,ln,un=s(()=>{N(),en(),an(),sn=()=>{(typeof C.wasm.initTimeout!=`number`||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!=`boolean`&&(C.wasm.proxy=!1),typeof C.wasm.trace!=`boolean`&&(C.wasm.trace=!1),typeof C.wasm.numThreads!=`number`||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},cn=class{async init(e){sn(),await qt(),await Jt(e)}async createInferenceSessionHandler(e,t){let n=new rn;return await n.loadModel(e,t),n}},ln=new cn}),dn={};c(dn,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,default:()=>pn,env:()=>C,registerBackend:()=>p}),N(),N(),N();var fn=`1.26.0`,pn=ke;{let e=(un(),u(on)).wasmBackend;p(`cpu`,e,10),p(`wasm`,e,10)}return Object.defineProperty(C.versions,"web",{value:fn,enumerable:!0}),u(dn)})();typeof t==`object`&&typeof i==`object`&&(i.exports=a)})),v=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;var i=r(_()),l=a(),u=c(),d=o(),f=s(),h=p(),g=m();e.DEFAULT_MODEL=`legacy`,e.ort=i;var v=`vad.worklet.bundle.min.js`,y=`silero_vad_v5.onnx`,b=`silero_vad_legacy.onnx`;e.getDefaultRealTimeVADOptions=e=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{d.log.debug(`VAD misfire`)},onSpeechStart:()=>{d.log.debug(`Detected speech start`)},onSpeechEnd:()=>{d.log.debug(`Detected speech end`)},onSpeechRealStart:()=>{d.log.debug(`Detected real speech start`)},baseAssetPath:`./`,onnxWASMBasePath:`./`,model:e,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async e=>{e.getTracks().forEach(e=>{e.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:e=>{e.env.logLevel=`error`},startOnLoad:!0,processorType:`auto`});var x=e=>`audioWorklet`in e&&typeof AudioWorkletNode==`function`?`AudioWorklet`:`ScriptProcessor`;async function S(e,t,n,r,i){await n.audioWorklet.addModule(e),t.processorOptions={...t.processorOptions??{},frameSamples:r};let a=new AudioWorkletNode(n,`vad-helper-worklet`,t);return a.port.onmessage=async e=>{let t=e.data;if(!(typeof t==`object`&&t&&`message`in t)){console.error(`Invalid message event`,t);return}switch(t.message){case f.Message.AudioFrame:if(!(`data`in t&&t.data instanceof ArrayBuffer)){console.log(`Audio frame message has no data`);return}await i(new Float32Array(t.data));break}},a}async function C(e,t,n){let r=new g.Resampler({nativeSampleRate:e.sampleRate,targetSampleRate:16e3,targetFrameSize:t});d.log.debug(`using script processor`);let i=e.createScriptProcessor(4096,1,1),a=!1;return i.onaudioprocess=async e=>{if(!a){a=!0;try{let t=e.inputBuffer.getChannelData(0);e.outputBuffer.getChannelData(0).fill(0);let i=r.process(t);for(let e of i)await n(e)}catch(e){console.error(`Error processing audio:`,e)}finally{a=!1}}},i.connect(e.destination),i}e.MicVAD=class t{constructor(e,t,n,r,i=!1,a=null,o=null,s=null,c=null,l=null,u=null,p=`uninitialized`,m=!1){this.options=e,this.frameProcessor=t,this.model=n,this.frameSamples=r,this.listening=i,this.errored=a,this._stream=o,this._audioContext=s,this._vadNode=c,this._mediaStreamAudioSourceNode=l,this._audioProcessorAdapterType=u,this.initializationState=p,this.ownsAudioContext=m,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw Error(`MicVAD has null stream, audio context, or processor adapter`);return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=e=>{this.initializationState=`errored`,this.errored=e},this.start=async()=>{switch(this.initializationState){case`uninitialized`:d.log.debug(`initializing micVAD`),this.initializationState=`initializing`,this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(e){throw e instanceof Error?this.setErrored(e.message):this.setErrored(String(e)),e}if(this.options.audioContext?(console.log(`using custom audio context`),this._audioContext=this.options.audioContext):(console.log(`using default audio context`),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored(`Audio context is null`),Error(`Audio context is null`);switch(this._audioProcessorAdapterType=this.options.processorType==`auto`?x(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case`AudioWorklet`:this._vadNode=await S(this.options.baseAssetPath+v,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case`ScriptProcessor`:this._vadNode=await C(this._audioContext,this.frameSamples,this.processFrame);break;default:throw Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),d.log.debug(`started micVAD`),this.listening=!0,this.initializationState=`initialized`;break;case`initializing`:d.log.warn(`start called while initializing`);break;case`initialized`:{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();let{stream:e,audioContext:t,vadNode:n}=this.getAudioInstances();this._stream=await this.options.resumeStream(e);let r=new MediaStreamAudioSourceNode(t,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=r,r.connect(n);break}case`destroyed`:d.log.warn(`start called after destroyed`);break;case`errored`:d.log.error(`start called after errored`);break;default:d.log.warn(`weird initialization state`);break}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;let{stream:e,mediaStreamAudioSourceNode:t}=this.getAudioInstances();await this.options.pauseStream(e),t.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{d.log.debug(`destroy called`),this.initializationState=`destroyed`;let{vadNode:e}=this.getAudioInstances();e instanceof AudioWorkletNode&&e.port.postMessage(f.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=e=>{this.frameProcessor.setOptions(e)},this.processFrame=async e=>{await this.frameProcessor.process(e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=e=>{switch(e.msg){case f.Message.FrameProcessed:this.options.onFrameProcessed(e.probs,e.frame);break;case f.Message.SpeechStart:this.options.onSpeechStart();break;case f.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case f.Message.VADMisfire:this.options.onVADMisfire();break;case f.Message.SpeechEnd:this.options.onSpeechEnd(e.audio);break}}}static async new(n={}){let r={...(0,e.getDefaultRealTimeVADOptions)(n.model??e.DEFAULT_MODEL),...n};(0,u.validateOptions)(r),e.ort.env.wasm.wasmPaths=r.onnxWASMBasePath,r.ortConfig!==void 0&&r.ortConfig(e.ort);let i=r.model===`v5`?y:b,a=r.baseAssetPath+i,o=r.model===`v5`?h.SileroV5.new:h.SileroLegacy.new,s;try{s=await o(e.ort,()=>(0,l.defaultModelFetcher)(a))}catch(e){throw console.error(`Encountered an error while loading model file ${a}`),e}let c=r.model===`v5`?512:1536,d=c/16,f=new t(r,new u.FrameProcessor(s.process,s.reset_state,{positiveSpeechThreshold:r.positiveSpeechThreshold,negativeSpeechThreshold:r.negativeSpeechThreshold,redemptionMs:r.redemptionMs,preSpeechPadMs:r.preSpeechPadMs,minSpeechMs:r.minSpeechMs,submitUserSpeechOnPause:r.submitUserSpeechOnPause},d),s,c);if(r.startOnLoad)try{await f.start()}catch(e){throw console.error(`Error starting micVad`,e),e}return f}}})),y=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var t=i();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return t.baseAssetPath}});var n=a();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var r=c();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var o=s();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=h();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});var u=g();e.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var d=v();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return d.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return d.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return d.getDefaultRealTimeVADOptions}})}));export default y();
|
|
2785
|
+
${a}`,s=n.createShaderModule({code:o,label:e.name});z(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return M(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}return[o,o,1]}}}),hu={};c(hu,{WebGpuBackend:()=>yu});var gu,_u,vu,yu,bu=s(()=>{N(),R(),jt(),zt(),pn(),fu(),mu(),gu=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},_u=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${gu(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},vu=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},yu=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new vu(t.info||await t.requestAdapterInfo()),this.gpuDataManager=fn(this),this.programManager=new pu(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,kt(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;j(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:gt(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:gt(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${gt(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${gt(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}ge(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),M()}run(e,t,n,r,i,a){j(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return M(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${gt(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=_u(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),z(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(z(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),M(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=du.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),z(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await un(this,e,t);return Rt(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){z(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){z(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){z(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),xu={};c(xu,{init:()=>wu});var Su,Cu,wu,Tu=s(()=>{R(),jt(),V(),tn(),Su=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=B.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(B.size(t)!==B.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},Cu=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new Su(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new Su(this.module,t,this.output(e,n),n),(e,t)=>{let n=_t(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new Su(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},wu=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(bu(),u(hu)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)z(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{z(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{z(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{z(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new Cu(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new en(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),Eu,Du,Ou,ku,Au,ju,Mu,Nu,Pu,Fu,Iu,Lu,Ru,zu=s(()=>{N(),st(),mt(),R(),rt(),at(),wt(),Eu=(e,t)=>{F()._OrtInit(e,t)!==0&&L(`Can't initialize onnxruntime.`)},Du=async e=>{Eu(e.wasm.numThreads,yt(e.logLevel))},Ou=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);{let r=(Tu(),u(xu)).init;t===`webgpu`&&await r(`webgpu`,F(),e,n),t===`webnn`&&await r(`webnn`,F(),e)}},ku=new Map,Au=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&L(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},ju=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&L(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Mu=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Nu=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Mu(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await pt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Ct(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&L(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Au(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=ju(a,t);e===0&&L(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:gt(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=ju(a,n+e);r===0&&L(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:gt(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&L(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>St(e))}),ku.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&L(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&L(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&L(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Pu=e=>{let t=F(),n=ku.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&L(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&L(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&L(`Can't release session.`),ku.delete(e)},Fu=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=_t(ht(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=_t(ht(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,ht(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,I(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ht(l);m=_t(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ht(l),p,m,g,u.length,St(f));e===0&&L(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Iu=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=ku.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),ee=o.stackAlloc(g*s);try{[_,v]=ot(a),ve(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await Fu(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await Fu(i[t],b,x,e,d[r[t]],h+r[t],p);ye(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(ee+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);ve(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&L(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&L(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&L(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}ye(`wasm bindInputsOutputs`),ku.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,ee,g,E,_),c!==0&&L(`failed to call OrtRun().`);let C=[],D=[];ve(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&L(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&L(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=gt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=_t(a,g);if(r===void 0||!bt(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(_t(a,g)===void 0||!xt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,D.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(vt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&L(`Can't clear bound outputs.`),ku.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(D))C[e][2]=t;return ye(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Lu=e=>{let t=F(),n=ku.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&L(`Can't get an profile file name.`),t._OrtFree(i)},Ru=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Bu,Vu,Hu,Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id=s(()=>{N(),zu(),rt(),Je(),Bu=()=>!!C.wasm.proxy&&typeof document<`u`,Hu=!1,Uu=!1,Wu=!1,qu=new Map,Ju=(e,t)=>{let n=qu.get(e);n?n.push(t):qu.set(e,[t])},Yu=()=>{if(Hu||!Uu||Wu||!Vu)throw Error(`worker not ready`)},Xu=e=>{switch(e.data.type){case`init-wasm`:Hu=!1,e.data.err?(Wu=!0,Ku[1](e.data.err)):(Uu=!0,Ku[0]()),Gu&&=(URL.revokeObjectURL(Gu),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=qu.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Zu=async()=>{if(!Uu){if(Hu)throw Error(`multiple calls to 'initWasm()' detected.`);if(Wu)throw Error(`previous call to 'initWasm()' failed.`);if(Hu=!0,Bu())return new Promise((e,t)=>{Vu?.terminate(),Ge().then(([n,r])=>{try{Vu=r,Vu.onerror=e=>t(e),Vu.onmessage=Xu,Ku=[e,t];let i={type:`init-wasm`,in:C};if(!i.in.wasm.wasmPaths&&n){let e=Re();e&&(i.in.wasm.wasmPaths=e)}Vu.postMessage(i),Gu=n}catch(e){t(e)}},t)});try{await nt(C.wasm),await Du(C),Uu=!0}catch(e){throw Wu=!0,e}finally{Hu=!1}}},Qu=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:C}};Vu.postMessage(r)});await Ou(C,e)},$u=async e=>Bu()?(Yu(),new Promise((t,n)=>{Ju(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Vu.postMessage(r,[e.buffer])})):Mu(e),ed=async(e,t)=>{if(Bu()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Yu(),new Promise((n,r)=>{Ju(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Vu.postMessage(i,a)})}return Nu(e,t)},td=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`release`,[t,n]);let r={type:`release`,in:e};Vu.postMessage(r)});Pu(e)},nd=async(e,t,n,r,i,a)=>{if(Bu()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Yu(),new Promise((i,o)=>{Ju(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Vu.postMessage(c,Ru(s))})}return Iu(e,t,n,r,i,a)},rd=async e=>{if(Bu())return Yu(),new Promise((t,n)=>{Ju(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Vu.postMessage(r)});Lu(e)}}),ad,od,sd,cd=s(()=>{N(),id(),R(),Ae(),wt(),ad=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},od=e=>{switch(e[3]){case`cpu`:return new A(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!bt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return A.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!xt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return A.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},sd=class{async fetchModelAndCopyToWasmMemory(e){return $u(await Ct(e))}async loadModel(e,t){j();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ed(n,t),M()}async dispose(){return td(this.sessionId)}async run(e,t,n){j();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>ad(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?ad(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await nd(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??od(l[e]);return M(),u}startProfiling(){}endProfiling(){rd(this.sessionId)}}}),ld={};c(ld,{OnnxruntimeWebAssemblyBackend:()=>dd,initializeFlags:()=>ud,wasmBackend:()=>fd});var ud,dd,fd,pd=s(()=>{N(),id(),cd(),ud=()=>{(typeof C.wasm.initTimeout!=`number`||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!=`boolean`&&(C.wasm.proxy=!1),typeof C.wasm.trace!=`boolean`&&(C.wasm.trace=!1),typeof C.wasm.numThreads!=`number`||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},dd=class{async init(e){ud(),await Zu(),await Qu(e)}async createInferenceSessionHandler(e,t){let n=new sd;return await n.loadModel(e,t),n}},fd=new dd}),md={};c(md,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,default:()=>gd,env:()=>C,registerBackend:()=>p}),N(),N(),N();var hd=`1.26.0`,gd=ke;{let e=(pd(),u(ld)).wasmBackend;p(`webgpu`,e,5),p(`webnn`,e,5),p(`cpu`,e,10),p(`wasm`,e,10)}return Object.defineProperty(C.versions,"web",{value:hd,enumerable:!0}),u(md)})();typeof t==`object`&&typeof i==`object`&&(i.exports=a)})),u=t((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),d=t((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroLegacy=void 0;var n=o(),r=class{constructor(e,t,n,r,i){this.ortInstance=e,this._session=t,this._h=n,this._c=r,this._sr=i,this.reset_state=()=>{let e=Array(128).fill(0);this._h=new this.ortInstance.Tensor(`float32`,e,[2,1,64]),this._c=new this.ortInstance.Tensor(`float32`,e,[2,1,64])},this.process=async e=>{let t={input:new this.ortInstance.Tensor(`float32`,e,[1,e.length]),h:this._h,c:this._c,sr:this._sr},n=await this._session.run(t);this._h=n.hn,this._c=n.cn;let[r]=n.output?.data;return{notSpeech:1-r,isSpeech:r}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}};e.SileroLegacy=r,t=r,r.new=async(e,r)=>{n.log.debug(`initializing vad`);let i=await r(),a=await e.InferenceSession.create(i),o=new e.Tensor(`int64`,[16000n]),s=Array(128).fill(0),c=new e.Tensor(`float32`,s,[2,1,64]),l=new e.Tensor(`float32`,s,[2,1,64]);return n.log.debug(`vad is initialized`),new t(e,a,c,l,o)}})),f=t((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=void 0;var n=o();function r(e){let t=Array(256).fill(0);return new e.Tensor(`float32`,t,[2,1,128])}var i=class{constructor(e,t,n,i){this._session=e,this._state=t,this._sr=n,this.ortInstance=i,this.reset_state=()=>{this._state=r(this.ortInstance)},this.process=async e=>{let t={input:new this.ortInstance.Tensor(`float32`,e,[1,e.length]),state:this._state,sr:this._sr},n=await this._session.run(t);if(!n.stateN)throw Error(`No state from model`);if(this._state=n.stateN,!n.output?.data)throw Error(`No output from model`);let r=n.output.data[0];if(typeof r!=`number`)throw Error(`Weird output data`);return{notSpeech:1-r,isSpeech:r}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}};e.SileroV5=i,t=i,i.new=async(e,i)=>{n.log.debug(`Loading VAD...`);let a=await i(),o=await e.InferenceSession.create(a),s=new e.Tensor(`int64`,[16000n]),c=r(e);return n.log.debug(`...finished loading VAD`),new t(o,c,s,e)}})),p=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=e.SileroLegacy=void 0,n(u(),e);var r=d();Object.defineProperty(e,"SileroLegacy",{enumerable:!0,get:function(){return r.SileroLegacy}});var i=f();Object.defineProperty(e,"SileroV5",{enumerable:!0,get:function(){return i.SileroV5}})})),m=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Resampler=void 0;var t=o();e.Resampler=class{constructor(e){this.options=e,this.process=e=>{let t=[];for(let n of e)for(this.inputBuffer.push(n);this.hasEnoughDataForFrame();){let e=this.generateOutputFrame();t.push(e)}return t},e.nativeSampleRate<16e3&&t.log.error(`nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate`),this.inputBuffer=[]}async*stream(e){for(let t of e)for(this.inputBuffer.push(t);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){let e=new Float32Array(this.options.targetFrameSize),t=0,n=0;for(;t<this.options.targetFrameSize;){let r=0,i=0;for(;n<Math.min(this.inputBuffer.length,(t+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){let e=this.inputBuffer[n];e!==void 0&&(r+=e,i++),n++}e[t]=r/i,t++}return this.inputBuffer=this.inputBuffer.slice(n),e}}})),h=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.NonRealTimeVAD=e.defaultNonRealTimeVADOptions=void 0;var o=r(l()),u=i(),d=a(),f=c(),h=s(),g=p(),_=m();e.defaultNonRealTimeVADOptions={...f.defaultFrameProcessorOptions,modelURL:u.baseAssetPath+`silero_vad_legacy.onnx`,modelFetcher:d.defaultModelFetcher},e.NonRealTimeVAD=class{static async new(t={}){let n={...e.defaultNonRealTimeVADOptions,...t};(0,f.validateOptions)(n),n.ortConfig!==void 0&&n.ortConfig(o);let r=()=>n.modelFetcher(n.modelURL),i=await g.SileroLegacy.new(o,r),a=new f.FrameProcessor(i.process,i.reset_state,{positiveSpeechThreshold:n.positiveSpeechThreshold,negativeSpeechThreshold:n.negativeSpeechThreshold,redemptionMs:n.redemptionMs,preSpeechPadMs:n.preSpeechPadMs,minSpeechMs:n.minSpeechMs,submitUserSpeechOnPause:n.submitUserSpeechOnPause},96);return a.resume(),new this(r,o,n,a)}constructor(e,t,n,r){this.modelFetcher=e,this.ort=t,this.options=n,this.frameProcessor=r,this.frameSamples=1536}async*run(e,t){let n={nativeSampleRate:t,targetSampleRate:16e3,targetFrameSize:this.frameSamples},r=new _.Resampler(n),i=0,a=0,o=0;for await(let t of r.stream(e)){let e=[];await this.frameProcessor.process(t,t=>{e.push(t)});for(let t of e)switch(t.msg){case h.Message.SpeechStart:i=o*this.frameSamples/16;break;case h.Message.SpeechEnd:a=(o+1)*this.frameSamples/16,yield{audio:t.audio,start:i,end:a}}o++}let s=[];this.frameProcessor.endSegment(e=>{s.push(e)});for(let e of s)switch(e.msg){case h.Message.SpeechEnd:yield{audio:e.audio,start:i,end:o*this.frameSamples/16}}}}})),g=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.audioFileToArray=e.encodeWAV=e.arrayBufferToBase64=e.minFramesForTargetMS=void 0;function t(e,t,n=16e3){return Math.ceil(e*n/1e3/t)}e.minFramesForTargetMS=t;function n(e){let t=new Uint8Array(e),n=t.byteLength,r=Array(n);for(let e=0;e<n;e++){let n=t[e];if(n===void 0)break;r[e]=String.fromCharCode(n)}return btoa(r.join(``))}e.arrayBufferToBase64=n;function r(e,t=3,n=16e3,r=1,s=32){let c=s/8,l=r*c,u=new ArrayBuffer(44+e.length*c),d=new DataView(u);return o(d,0,`RIFF`),d.setUint32(4,36+e.length*c,!0),o(d,8,`WAVE`),o(d,12,`fmt `),d.setUint32(16,16,!0),d.setUint16(20,t,!0),d.setUint16(22,r,!0),d.setUint32(24,n,!0),d.setUint32(28,n*l,!0),d.setUint16(32,l,!0),d.setUint16(34,s,!0),o(d,36,`data`),d.setUint32(40,e.length*c,!0),t===1?a(d,44,e):i(d,44,e),u}e.encodeWAV=r;function i(e,t,n){for(let r=0;r<n.length;r++,t+=4)e.setFloat32(t,n[r],!0)}function a(e,t,n){for(let r=0;r<n.length;r++,t+=2){let i=Math.max(-1,Math.min(1,n[r]));e.setInt16(t,i<0?i*32768:i*32767,!0)}}function o(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}async function s(e){let t=new OfflineAudioContext(1,1,44100),n=new FileReader,r=null;if(await new Promise(i=>{n.addEventListener(`loadend`,()=>{let e=n.result;t.decodeAudioData(e,e=>{r=e,t.startRendering().then(()=>{console.log(`Rendering completed successfully`),i()}).catch(e=>{console.error(`Rendering failed: `,e)})},e=>{console.log(`Error with decoding audio data: `,e)})}),n.readAsArrayBuffer(e)}),r===null)throw Error(`some shit`);let i=r,a=new Float32Array(i.length);for(let e=0;e<i.length;e++)for(let t=0;t<i.numberOfChannels;t++){let n=i.getChannelData(t)[e],r=a[e];if(n===void 0||r===void 0)throw Error(`sample or out[i] is undefined`);a[e]=r+n}return{audio:a,sampleRate:i.sampleRate}}e.audioFileToArray=s})),_=t(((t,i)=>{n();var a=(()=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),s=(e,t)=>()=>(e&&(t=e(e=0)),t),c=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},l=(e,r,o,s)=>{if(r&&typeof r==`object`||typeof r==`function`)for(let c of i(r))!a.call(e,c)&&c!==o&&t(e,c,{get:()=>r[c],enumerable:!(s=n(r,c))||s.enumerable});return e},u=e=>l(t({},`__esModule`,{value:!0}),e),d,f,p,m,h,g=s(()=>{d=new Map,f=[],p=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}return}throw TypeError(`not a valid backend`)},m=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},h=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=new Set;for(let e of r){let t=await m(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),_=s(()=>{g()}),v,y=s(()=>{v=`1.26.0`}),b,x,S=s(()=>{y(),b=`warning`,x={wasm:{},webgl:{},webgpu:{},versions:{common:v},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);b=e}},get logLevel(){return b}},Object.defineProperty(x,"logLevel",{enumerable:!0})}),C,w=s(()=>{S(),C=x}),T,E,ee=s(()=>{T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},E=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),D,O,te,ne,re,ie,ae=s(()=>{me(),D=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new k(`float32`,u,[1,4,n,r]):new k(`float32`,u,[1,3,n,r])},O=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,D(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(D(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return D(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},te=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new k({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ne=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},re=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new k({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ie=(e,t,n)=>new k({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),oe,se,ce,le,ue=s(()=>{oe=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),se=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ce=!1,le=()=>{if(!ce){ce=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(oe.set(`int64`,BigInt64Array),se.set(BigInt64Array,`int64`)),t&&(oe.set(`uint64`,BigUint64Array),se.set(BigUint64Array,`uint64`)),r?(oe.set(`float16`,n),se.set(n,`float16`)):oe.set(`float16`,Uint16Array)}}}),de,fe,pe=s(()=>{me(),de=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},fe=(e,t)=>{switch(e.location){case`cpu`:return new k(e.type,e.data,t);case`cpu-pinned`:return new k({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new k({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new k({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new k({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),k,me=s(()=>{ee(),ae(),ue(),pe(),k=class{constructor(e,t,n){le();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=oe.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=oe.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=se.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=de(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return O(e,t)}static fromTexture(e,t){return te(e,t)}static fromGpuBuffer(e,t){return ne(e,t)}static fromMLTensor(e,t){return re(e,t)}static fromPinnedBuffer(e,t,n){return ie(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return E(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return fe(this,e)}}}),A,he=s(()=>{me(),A=k}),ge,_e,j,M,ve,ye,be=s(()=>{S(),ge=(e,t)=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeStamp(`${e}::ORT::${t}`)},_e=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ge(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},j=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`BEGIN`,e)},M=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||_e(`END`,e)},ve=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.time(`ORT::${e}`)},ye=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeEnd(`ORT::${e}`)}}),xe,Se=s(()=>{g(),he(),be(),xe=class e{constructor(e){this.handler=e}async run(e,t,n){j(),ve(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof A||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof A)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof A)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof A?t:new A(t.type,t.data,t.dims)}return ye(`InferenceSession.run`),M(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){j(),ve(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await h(o),l=await s.createInferenceSessionHandler(a,c);return ye(`InferenceSession.create`),M(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ce,we=s(()=>{Se(),Ce=xe}),Te=s(()=>{}),Ee=s(()=>{}),De=s(()=>{}),Oe=s(()=>{}),ke={};c(ke,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,env:()=>C,registerBackend:()=>p});var N=s(()=>{_(),w(),we(),he(),Te(),Ee(),be(),De(),Oe()}),Ae=s(()=>{}),je={};c(je,{default:()=>Pe});var Me,Ne,Pe,Fe=s(()=>{It(),rt(),Je(),Me=`ort-wasm-proxy-worker`,Ne=globalThis.self?.name===Me,Ne&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:nt(n.wasm).then(()=>{Et(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;Dt(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=z(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;jt(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Mt(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;B(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Ft([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Pt(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),Pe=Ne?null:e=>new Worker(e??P,{type:`classic`,name:Me})}),Ie,Le,P,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je=s(()=>{Ae(),Ie=typeof location>`u`?void 0:location.origin,Le=()=>typeof document<`u`?document.currentScript?.src:typeof self<`u`?self.location?.href:void 0,P=Le(),Re=()=>{if(P&&!P.startsWith(`blob:`))return P.substring(0,P.lastIndexOf(`/`)+1)},ze=(e,t)=>{try{let n=t??P;return(n?new URL(e,n):new URL(e)).origin===Ie}catch{return!1}},Be=(e,t)=>{let n=t??P;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Ve=(e,t)=>`${t??`./`}${e}`,He=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Ue=async e=>(await r(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,We=(Fe(),u(je)).default,Ge=async()=>{if(!P)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(ze(P))return[void 0,We()];let e=await He(P);return[e,We(e)]},Ke=void 0,qe=async(e,t,n,r)=>{let i=Ke&&!(e||t);if(i){if(P)i=ze(P)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,Ke];{let r=`ort-wasm-simd-threaded.mjs`,i=e??Be(r,t),a=n&&i&&!ze(i,t),o=a?await He(i):i??Ve(r,t);return[a?o:void 0,await Ue(o)]}}}),Ye,Xe,Ze,Qe,$e,et,tt,nt,F,rt=s(()=>{Je(),Xe=!1,Ze=!1,Qe=!1,$e=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},et=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tt=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nt=async e=>{if(Xe)return Promise.resolve();if(Ze)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Qe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Ze=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!tt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!et())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=$e();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await qe(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Re();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Ze=!1,Xe=!0,Ye=t,e(),d&&URL.revokeObjectURL(d)},e=>{Ze=!1,Qe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Xe&&Ye)return Ye;throw Error(`WebAssembly is not initialized yet.`)}}),I,it,L,at=s(()=>{rt(),I=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},it=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)it(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},L=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),ot,st=s(()=>{rt(),at(),ot=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=I(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&L(`Can't create run options.`),e?.extra!==void 0&&it(e.extra,``,new WeakSet,(e,i)=>{let a=I(e,r),o=I(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&L(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ct,lt,ut,dt,ft,pt,mt=s(()=>{rt(),at(),ct=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},lt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ut=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},dt=(e,t,n,r)=>{let i=I(t,r),a=I(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&L(`Can't set a session config entry: ${t} - ${n}.`)},ft=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,dt(e,`session.disable_quant_qdq`,`1`,n),dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof t!=`string`){let r=t?.deviceType;r&&dt(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);dt(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=I(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&L(`Can't append execution provider: ${r}.`)}},pt=async e=>{let t=F(),n=0,r=[],i=e||{};ut(i);try{let e=ct(i.graphOptimizationLevel??`all`),a=lt(i.executionMode??`sequential`),o=typeof i.logId==`string`?I(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?I(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&L(`Can't create session options.`),i.executionProviders&&await ft(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=I(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&L(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&it(i.extra,``,new WeakSet,(e,t)=>{dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&L(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ht,gt,_t,vt,yt,bt,xt,St,R=s(()=>{ht=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},_t=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},vt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},yt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,xt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,St=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ct,wt=s(()=>{Ae(),Ct=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Tt,Et,Dt,Ot,kt,At,z,jt,Mt,Nt,B,Pt,Ft,It=s(()=>{N(),st(),mt(),R(),rt(),at(),wt(),Tt=(e,t)=>{F()._OrtInit(e,t)!==0&&L(`Can't initialize onnxruntime.`)},Et=async e=>{Tt(e.wasm.numThreads,yt(e.logLevel))},Dt=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`)},Ot=new Map,kt=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&L(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},At=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&L(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},z=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},jt=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=z(e);let a=0,o=0,s=[],c=[],l=[];try{if([o,s]=await pt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Ct(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&L(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,u]=kt(a),d=!!t?.enableGraphCapture,f=[],p=[],m=[],h=[];for(let t=0;t<e;t++){let[e,n,r]=At(a,t);e===0&&L(`Can't get an input name.`),c.push(e);let o=i.UTF8ToString(e);f.push(o),m.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:gt(n),shape:r})}for(let t=0;t<u;t++){let[n,r,o]=At(a,t+e);n===0&&L(`Can't get an output name.`),l.push(n);let s=i.UTF8ToString(n);p.push(s),h.push(r===0?{name:s,isTensor:!1}:{name:s,isTensor:!0,type:gt(r),shape:o})}return Ot.set(a,[a,c,l,null,d,!1]),[a,f,p,m,h]}catch(e){throw c.forEach(e=>i._OrtFree(e)),l.forEach(e=>i._OrtFree(e)),a!==0&&i._OrtReleaseSession(a)!==0&&L(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&L(`Can't release session options.`),s.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Mt=e=>{let t=F(),n=Ot.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&L(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&L(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&L(`Can't release session.`),Ot.delete(e)},Nt=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=_t(ht(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=_t(ht(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,ht(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,I(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ht(l);m=_t(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ht(l),p,m,g,u.length,St(f));e===0&&L(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},B=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=Ot.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];c[5];let m=t.length,h=r.length,g=0,_=[],v=[],y=[],b=[],x=[],S=o.stackSave(),C=o.stackAlloc(m*s),w=o.stackAlloc(m*s),T=o.stackAlloc(h*s),E=o.stackAlloc(h*s);try{[g,_]=ot(a),ve(`wasm prepareInputOutputTensor`);for(let r=0;r<m;r++)await Nt(n[r],v,b,e,u[t[r]],t[r],p);for(let t=0;t<h;t++)await Nt(i[t],y,b,e,d[r[t]],m+r[t],p);ye(`wasm prepareInputOutputTensor`);for(let e=0;e<m;e++)o.setValue(C+e*s,v[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<h;e++)o.setValue(T+e*s,y[e],`*`),o.setValue(E+e*s,d[r[e]],`*`);o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=await o._OrtRun(l,w,C,m,E,h,T,g),c!==0&&L(`failed to call OrtRun().`);let S=[],ee=[];ve(`wasm ProcessOutputTensor`);for(let t=0;t<h;t++){let n=Number(o.getValue(T+t*s,`*`));if(n===y[t]||x.includes(y[t])){S.push(i[t]),n!==y[t]&&o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&L(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&L(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=gt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}S.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=_t(a,g);if(r===void 0||!bt(u))throw Error(`Unsupported data type: ${u}`);l=!0,S.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&L(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(_t(a,g)===void 0||!xt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,S.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=S.length;l=!0,ee.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(vt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&L(`Can't clear bound outputs.`),Ot.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(ee))S[e][2]=t;return ye(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),v.forEach(e=>o._OrtReleaseTensor(e)),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._free(e)),g!==0&&o._OrtReleaseRunOptions(g),_.forEach(e=>o._free(e))}},Pt=e=>{let t=F(),n=Ot.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&L(`Can't get an profile file name.`),t._OrtFree(i)},Ft=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Lt,V,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en=s(()=>{N(),It(),rt(),Je(),Lt=()=>!!C.wasm.proxy&&typeof document<`u`,Rt=!1,zt=!1,Bt=!1,Ut=new Map,Wt=(e,t)=>{let n=Ut.get(e);n?n.push(t):Ut.set(e,[t])},Gt=()=>{if(Rt||!zt||Bt||!V)throw Error(`worker not ready`)},Kt=e=>{switch(e.data.type){case`init-wasm`:Rt=!1,e.data.err?(Bt=!0,Ht[1](e.data.err)):(zt=!0,Ht[0]()),Vt&&=(URL.revokeObjectURL(Vt),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Ut.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},qt=async()=>{if(!zt){if(Rt)throw Error(`multiple calls to 'initWasm()' detected.`);if(Bt)throw Error(`previous call to 'initWasm()' failed.`);if(Rt=!0,Lt())return new Promise((e,t)=>{V?.terminate(),Ge().then(([n,r])=>{try{V=r,V.onerror=e=>t(e),V.onmessage=Kt,Ht=[e,t];let i={type:`init-wasm`,in:C};if(!i.in.wasm.wasmPaths&&n){let e=Re();e&&(i.in.wasm.wasmPaths=e)}V.postMessage(i),Vt=n}catch(e){t(e)}},t)});try{await nt(C.wasm),await Et(C),zt=!0}catch(e){throw Bt=!0,e}finally{Rt=!1}}},Jt=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:C}};V.postMessage(r)});await Dt(C,e)},Yt=async e=>Lt()?(Gt(),new Promise((t,n)=>{Wt(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};V.postMessage(r,[e.buffer])})):z(e),Xt=async(e,t)=>{if(Lt()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Gt(),new Promise((n,r)=>{Wt(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),V.postMessage(i,a)})}return jt(e,t)},Zt=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`release`,[t,n]);let r={type:`release`,in:e};V.postMessage(r)});Mt(e)},Qt=async(e,t,n,r,i,a)=>{if(Lt()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Gt(),new Promise((i,o)=>{Wt(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};V.postMessage(c,Ft(s))})}return B(e,t,n,r,i,a)},$t=async e=>{if(Lt())return Gt(),new Promise((t,n)=>{Wt(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};V.postMessage(r)});Pt(e)}}),tn,nn,rn,an=s(()=>{N(),en(),R(),Ae(),wt(),tn=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},nn=e=>{switch(e[3]){case`cpu`:return new A(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!bt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return A.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!xt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return A.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},rn=class{async fetchModelAndCopyToWasmMemory(e){return Yt(await Ct(e))}async loadModel(e,t){j();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Xt(n,t),M()}async dispose(){return Zt(this.sessionId)}async run(e,t,n){j();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>tn(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?tn(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Qt(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??nn(l[e]);return M(),u}startProfiling(){}endProfiling(){$t(this.sessionId)}}}),on={};c(on,{OnnxruntimeWebAssemblyBackend:()=>cn,initializeFlags:()=>sn,wasmBackend:()=>ln});var sn,cn,ln,un=s(()=>{N(),en(),an(),sn=()=>{(typeof C.wasm.initTimeout!=`number`||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!=`boolean`&&(C.wasm.proxy=!1),typeof C.wasm.trace!=`boolean`&&(C.wasm.trace=!1),typeof C.wasm.numThreads!=`number`||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},cn=class{async init(e){sn(),await qt(),await Jt(e)}async createInferenceSessionHandler(e,t){let n=new rn;return await n.loadModel(e,t),n}},ln=new cn}),dn={};c(dn,{InferenceSession:()=>Ce,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>ve,TRACE_EVENT_END:()=>ye,TRACE_FUNC_BEGIN:()=>j,TRACE_FUNC_END:()=>M,Tensor:()=>A,default:()=>pn,env:()=>C,registerBackend:()=>p}),N(),N(),N();var fn=`1.26.0`,pn=ke;{let e=(un(),u(on)).wasmBackend;p(`cpu`,e,10),p(`wasm`,e,10)}return Object.defineProperty(C.versions,"web",{value:fn,enumerable:!0}),u(dn)})();typeof t==`object`&&typeof i==`object`&&(i.exports=a)})),v=t((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;var i=r(_()),l=a(),u=c(),d=o(),f=s(),h=p(),g=m();e.DEFAULT_MODEL=`legacy`,e.ort=i;var v=`vad.worklet.bundle.min.js`,y=`silero_vad_v5.onnx`,b=`silero_vad_legacy.onnx`;e.getDefaultRealTimeVADOptions=e=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{d.log.debug(`VAD misfire`)},onSpeechStart:()=>{d.log.debug(`Detected speech start`)},onSpeechEnd:()=>{d.log.debug(`Detected speech end`)},onSpeechRealStart:()=>{d.log.debug(`Detected real speech start`)},baseAssetPath:`./`,onnxWASMBasePath:`./`,model:e,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async e=>{e.getTracks().forEach(e=>{e.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:e=>{e.env.logLevel=`error`},startOnLoad:!0,processorType:`auto`});var x=e=>`audioWorklet`in e&&typeof AudioWorkletNode==`function`?`AudioWorklet`:`ScriptProcessor`;async function S(e,t,n,r,i){await n.audioWorklet.addModule(e),t.processorOptions={...t.processorOptions??{},frameSamples:r};let a=new AudioWorkletNode(n,`vad-helper-worklet`,t);return a.port.onmessage=async e=>{let t=e.data;if(!(typeof t==`object`&&t&&`message`in t)){console.error(`Invalid message event`,t);return}switch(t.message){case f.Message.AudioFrame:if(!(`data`in t&&t.data instanceof ArrayBuffer)){console.log(`Audio frame message has no data`);return}await i(new Float32Array(t.data))}},a}async function C(e,t,n){let r=new g.Resampler({nativeSampleRate:e.sampleRate,targetSampleRate:16e3,targetFrameSize:t});d.log.debug(`using script processor`);let i=e.createScriptProcessor(4096,1,1),a=!1;return i.onaudioprocess=async e=>{if(!a){a=!0;try{let t=e.inputBuffer.getChannelData(0);e.outputBuffer.getChannelData(0).fill(0);let i=r.process(t);for(let e of i)await n(e)}catch(e){console.error(`Error processing audio:`,e)}finally{a=!1}}},i.connect(e.destination),i}e.MicVAD=class t{constructor(e,t,n,r,i=!1,a=null,o=null,s=null,c=null,l=null,u=null,p=`uninitialized`,m=!1){this.options=e,this.frameProcessor=t,this.model=n,this.frameSamples=r,this.listening=i,this.errored=a,this._stream=o,this._audioContext=s,this._vadNode=c,this._mediaStreamAudioSourceNode=l,this._audioProcessorAdapterType=u,this.initializationState=p,this.ownsAudioContext=m,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw Error(`MicVAD has null stream, audio context, or processor adapter`);return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=e=>{this.initializationState=`errored`,this.errored=e},this.start=async()=>{switch(this.initializationState){case`uninitialized`:d.log.debug(`initializing micVAD`),this.initializationState=`initializing`,this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(e){throw e instanceof Error?this.setErrored(e.message):this.setErrored(String(e)),e}if(this.options.audioContext?(console.log(`using custom audio context`),this._audioContext=this.options.audioContext):(console.log(`using default audio context`),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored(`Audio context is null`),Error(`Audio context is null`);switch(this._audioProcessorAdapterType=this.options.processorType==`auto`?x(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case`AudioWorklet`:this._vadNode=await S(this.options.baseAssetPath+v,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case`ScriptProcessor`:this._vadNode=await C(this._audioContext,this.frameSamples,this.processFrame);break;default:throw Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),d.log.debug(`started micVAD`),this.listening=!0,this.initializationState=`initialized`;break;case`initializing`:d.log.warn(`start called while initializing`);break;case`initialized`:{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();let{stream:e,audioContext:t,vadNode:n}=this.getAudioInstances();this._stream=await this.options.resumeStream(e);let r=new MediaStreamAudioSourceNode(t,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=r,r.connect(n);break}case`destroyed`:d.log.warn(`start called after destroyed`);break;case`errored`:d.log.error(`start called after errored`);break;default:d.log.warn(`weird initialization state`)}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;let{stream:e,mediaStreamAudioSourceNode:t}=this.getAudioInstances();await this.options.pauseStream(e),t.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{d.log.debug(`destroy called`),this.initializationState=`destroyed`;let{vadNode:e}=this.getAudioInstances();e instanceof AudioWorkletNode&&e.port.postMessage(f.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=e=>{this.frameProcessor.setOptions(e)},this.processFrame=async e=>{await this.frameProcessor.process(e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=e=>{switch(e.msg){case f.Message.FrameProcessed:this.options.onFrameProcessed(e.probs,e.frame);break;case f.Message.SpeechStart:this.options.onSpeechStart();break;case f.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case f.Message.VADMisfire:this.options.onVADMisfire();break;case f.Message.SpeechEnd:this.options.onSpeechEnd(e.audio)}}}static async new(n={}){let r={...(0,e.getDefaultRealTimeVADOptions)(n.model??e.DEFAULT_MODEL),...n};(0,u.validateOptions)(r),e.ort.env.wasm.wasmPaths=r.onnxWASMBasePath,r.ortConfig!==void 0&&r.ortConfig(e.ort);let i=r.model===`v5`?y:b,a=r.baseAssetPath+i,o=r.model===`v5`?h.SileroV5.new:h.SileroLegacy.new,s;try{s=await o(e.ort,()=>(0,l.defaultModelFetcher)(a))}catch(e){throw console.error(`Encountered an error while loading model file ${a}`),e}let c=r.model===`v5`?512:1536,d=c/16,f=new u.FrameProcessor(s.process,s.reset_state,{positiveSpeechThreshold:r.positiveSpeechThreshold,negativeSpeechThreshold:r.negativeSpeechThreshold,redemptionMs:r.redemptionMs,preSpeechPadMs:r.preSpeechPadMs,minSpeechMs:r.minSpeechMs,submitUserSpeechOnPause:r.submitUserSpeechOnPause},d),p=new t(r,f,s,c);if(r.startOnLoad)try{await p.start()}catch(e){throw console.error(`Error starting micVad`,e),e}return p}}})),y=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var t=i();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return t.baseAssetPath}});var n=a();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var r=c();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var o=s();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=h();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});var u=g();e.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var d=v();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return d.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return d.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return d.getDefaultRealTimeVADOptions}})}));export default y();
|