From d8e170131ab286913e557c2da1a12d8a709a70df Mon Sep 17 00:00:00 2001 From: cbossut Date: Sun, 12 Apr 2020 16:24:21 +0200 Subject: [PATCH 01/85] add crude logging to the node server --- index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/index.js b/index.js index 7b35093..ae6c94a 100644 --- a/index.js +++ b/index.js @@ -147,6 +147,7 @@ const internCallback = staticRoute({dir:__dirname, tryfiles:['ports.html']}) , callback = (req, res) => { + console.log(new Date(), req.method + ' ' + req.headers.host + req.url) const dir = req.url.split('/')[1] , cb = (dir == 'sons' || dir == 'saves') ? externCallback : dynamicCallbacks[dir] ;(cb || internCallback)(req, res) From 6e753d02e53c70df149b65d7f123cd12fbc018de Mon Sep 17 00:00:00 2001 From: cbossut Date: Sun, 12 Apr 2020 16:25:28 +0200 Subject: [PATCH 02/85] First stage of loop cut Downloads instead of uploading --- ports.js | 21 ++++++++++ src/Editor/Mobile.elm | 90 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+) diff --git a/ports.js b/ports.js index 1f68105..30bebdf 100644 --- a/ports.js +++ b/ports.js @@ -4,6 +4,7 @@ if (app.ports.loadSound) app.ports.loadSound.subscribe(createBuffer) if (app.ports.toEngine) app.ports.toEngine.subscribe(engine) if (app.ports.toggleRecord) app.ports.toggleRecord.subscribe(toggleRecord) if (app.ports.requestSoundDraw) app.ports.requestSoundDraw.subscribe(drawSound) +if (app.ports.requestCutSample) app.ports.requestCutSample.subscribe(cutSample) const buffers = {} , ro = new ResizeObserver(sendSize) @@ -56,6 +57,26 @@ function toggleRecord(bool) { } } +function cutSample(infos) { + if (!buffers[infos.old]) {console.err("infos.old " + "ain’t loaded, cannot cut");return;} + + let buf = buffers[infos.old]._buffer + , start = infos.percents[0] * buf.length - 1 + , end = infos.percents[1] * buf.length + 1 + , newBuf = new AudioBuffer( + { length : end - start + , numberOfChannels : buf.numberOfChannels + , sampleRate : buf.sampleRate + }) + + for (let i = 0 ; i < buf.numberOfChannels ; i++) { + let chan = buf.getChannelData(i).slice(start, end) + newBuf.copyToChannel(chan, i) + } + + app.ports.gotNewSample.send(URL.createObjectURL(new Blob([audioBufferToWav(newBuf)], {type: "audio/wav"}))) +} + function engine(o) { let model = null switch ( o.action ) { diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index 98a36e9..43c46fc 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -47,6 +47,12 @@ port toggleRecord : Bool -> Cmd msg port gotRecord : (D.Value -> msg) -> Sub msg +port requestCutSample : { old : String, new : String, percents : ( Float, Float ) } -> Cmd msg + + +port gotNewSample : (D.Value -> msg) -> Sub msg + + -- TODO Maybe delegate Coll dependence to Data.Mobile (except Id) @@ -56,6 +62,11 @@ svgId = "svg" +charsInFile : List Char +charsInFile = + [ '_', '-', ' ' ] + + blinkOnTime : Float blinkOnTime = 800 @@ -73,6 +84,7 @@ type alias Model = , edit : List (Id Geer) , beadCursor : Int , link : Maybe LinkInfo + , newSampleName : String , parentUid : String -- TODO Two sources of truth !! same in Engine , engine : Engine , interact : Interact.State Interactable Zone @@ -156,6 +168,7 @@ init = , edit = [] , beadCursor = 0 , link = Nothing + , newSampleName = "" , parentUid = "" , engine = Engine.init , interact = Interact.init @@ -210,6 +223,9 @@ type Msg | Capsuled (List (Id Geer)) | Collared (Id Geer) | UnCollar (Id Geer) + | EnteredNewSampleName String + | CutNewSample + | GotNewSample (Result D.Error String) | Blink | InteractMsg (Interact.Msg Interactable Zone) | SvgMsg PanSvg.Msg @@ -748,6 +764,44 @@ update msg ( model, mobile ) = _ -> return + EnteredNewSampleName str -> + { return + | model = + { model + | newSampleName = + if String.all (\c -> Char.isAlphaNum c || List.member c charsInFile) str then + str + + else + model.newSampleName + } + } + + CutNewSample -> + case model.edit of + [ id ] -> + let + g = + Coll.get id mobile.gears + in + case Wheel.getContent g of + Content.S s -> + { return | cmd = requestCutSample { old = Sound.toString s, new = model.newSampleName, percents = Wheel.getLoopPercents g } } + + _ -> + return + + _ -> + return + + GotNewSample res -> + case res of + Ok url -> + { return | cmd = DL.url url } + + Err err -> + Debug.log (D.errorToString err) return + Blink -> case model.dragging of Alterning x y ( b, _ ) -> @@ -895,6 +949,7 @@ subs { interact, dragging } = PanSvg.newSVGSize (SVGSize << D.decodeValue PanSvg.sizeDecoder) :: Sub.map WaveMsg Waveform.sub :: (gotRecord <| (GotRecord << D.decodeValue D.string)) + :: (gotNewSample <| (GotNewSample << D.decodeValue D.string)) :: (List.map (Sub.map InteractMsg) <| Interact.subs interact) ++ (case dragging of Alterning _ _ ( _, t ) -> @@ -1587,6 +1642,41 @@ viewEditDetails model mobile = "Contenu : " ++ (Round.round 2 <| CommonData.getContentLength <| Wheel.getContent g) ] + ++ (case Wheel.getContent g of + Content.S s -> + let + ok = + model.newSampleName + /= Sound.toString s + && (not <| String.isEmpty model.newSampleName) + in + [ Input.button + [ Font.color <| + if ok then + rgb 1 1 1 + + else + rgb 0 0 0 + ] + { label = text "Couper en tant que" + , onPress = + if ok then + Just <| CutNewSample + + else + Nothing + } + , Input.text [ Font.color <| rgb 0 0 0 ] + { label = Input.labelHidden "Nouveau nom" + , text = model.newSampleName + , placeholder = Just <| Input.placeholder [] <| text "Nouveau nom" + , onChange = EnteredNewSampleName + } + ] + + _ -> + [] + ) ] _ :: _ -> From b8f46a4f48b272bd4ce2536097752c054f78fcc3 Mon Sep 17 00:00:00 2001 From: cbossut Date: Mon, 13 Apr 2020 11:36:46 +0200 Subject: [PATCH 03/85] notes about server launch procedure --- notes.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/notes.txt b/notes.txt index 427f13c..af33021 100644 --- a/notes.txt +++ b/notes.txt @@ -1,6 +1,14 @@ elm-live src/Main.elm -s ports.html -- --debug --output=elmApp.js pkg -c pkgConfig.json --targets linux,macos,win,linux-x86,win-x86 --out-path dist index.js +Serveur : log gears mdp GearsPassWord +cd server +node index.js >> log +screen +ctrd + a -> d +OU nohup OU disown +ps aux | grep node pour vérifier si ça tourne + Type Data avec tout ce qui doit être sauvegardé et undo/redo (est-ce bien les mêmes choses ?) Cummule UndoList et Saved, et fonctionnalité ajoutée de UndoGroup From 52fb9e1d6d80501983b278599797d205e1cb48f4 Mon Sep 17 00:00:00 2001 From: cbossut Date: Tue, 21 Apr 2020 23:26:03 +0200 Subject: [PATCH 04/85] node switch to file dir regardless of launch dir --- index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/index.js b/index.js index ae6c94a..4447d92 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ Copyright ou © ou Copr. Clément Bossut, (2018) */ +process.chdir(__dirname) console.log('args : port soundDir saveDir backUpDir') From 26a9d010acce6aac14f04de0465cfaf7a21668e2 Mon Sep 17 00:00:00 2001 From: cbossut Date: Wed, 22 Apr 2020 03:06:33 +0200 Subject: [PATCH 05/85] final loop cut --- ports.js | 6 +++--- src/Editor/Mobile.elm | 26 +++++++------------------- src/Main.elm | 13 +++++++++++++ 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/ports.js b/ports.js index 30bebdf..5bc3e40 100644 --- a/ports.js +++ b/ports.js @@ -58,9 +58,9 @@ function toggleRecord(bool) { } function cutSample(infos) { - if (!buffers[infos.old]) {console.err("infos.old " + "ain’t loaded, cannot cut");return;} + if (!buffers[infos.fromFileName]) {console.err(infos.fromFileName + " ain’t loaded, cannot cut");return;} - let buf = buffers[infos.old]._buffer + let buf = buffers[infos.fromFileName]._buffer , start = infos.percents[0] * buf.length - 1 , end = infos.percents[1] * buf.length + 1 , newBuf = new AudioBuffer( @@ -74,7 +74,7 @@ function cutSample(infos) { newBuf.copyToChannel(chan, i) } - app.ports.gotNewSample.send(URL.createObjectURL(new Blob([audioBufferToWav(newBuf)], {type: "audio/wav"}))) + app.ports.gotNewSample.send(new File([audioBufferToWav(newBuf)], infos.newFileName + ".wav", {type: "audio/wav"})) } function engine(o) { diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index 43c46fc..fe711bb 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -47,10 +47,7 @@ port toggleRecord : Bool -> Cmd msg port gotRecord : (D.Value -> msg) -> Sub msg -port requestCutSample : { old : String, new : String, percents : ( Float, Float ) } -> Cmd msg - - -port gotNewSample : (D.Value -> msg) -> Sub msg +port requestCutSample : { fromFileName : String, newFileName : String, percents : ( Float, Float ) } -> Cmd msg @@ -225,7 +222,6 @@ type Msg | UnCollar (Id Geer) | EnteredNewSampleName String | CutNewSample - | GotNewSample (Result D.Error String) | Blink | InteractMsg (Interact.Msg Interactable Zone) | SvgMsg PanSvg.Msg @@ -786,7 +782,7 @@ update msg ( model, mobile ) = in case Wheel.getContent g of Content.S s -> - { return | cmd = requestCutSample { old = Sound.toString s, new = model.newSampleName, percents = Wheel.getLoopPercents g } } + { return | cmd = requestCutSample { fromFileName = Sound.toString s, newFileName = model.newSampleName, percents = Wheel.getLoopPercents g } } _ -> return @@ -794,14 +790,6 @@ update msg ( model, mobile ) = _ -> return - GotNewSample res -> - case res of - Ok url -> - { return | cmd = DL.url url } - - Err err -> - Debug.log (D.errorToString err) return - Blink -> case model.dragging of Alterning x y ( b, _ ) -> @@ -946,11 +934,11 @@ update msg ( model, mobile ) = subs : Model -> List (Sub Msg) subs { interact, dragging } = - PanSvg.newSVGSize (SVGSize << D.decodeValue PanSvg.sizeDecoder) - :: Sub.map WaveMsg Waveform.sub - :: (gotRecord <| (GotRecord << D.decodeValue D.string)) - :: (gotNewSample <| (GotNewSample << D.decodeValue D.string)) - :: (List.map (Sub.map InteractMsg) <| Interact.subs interact) + [ PanSvg.newSVGSize (SVGSize << D.decodeValue PanSvg.sizeDecoder) + , Sub.map WaveMsg Waveform.sub + , gotRecord <| (GotRecord << D.decodeValue D.string) + ] + ++ (List.map (Sub.map InteractMsg) <| Interact.subs interact) ++ (case dragging of Alterning _ _ ( _, t ) -> [ Time.every t <| always <| Blink ] diff --git a/src/Main.elm b/src/Main.elm index dfd7b2b..c770464 100644 --- a/src/Main.elm +++ b/src/Main.elm @@ -41,6 +41,9 @@ port loadSound : String -> Cmd msg port soundLoaded : (D.Value -> msg) -> Sub msg +port gotNewSample : (D.Value -> msg) -> Sub msg + + -- TODO refactor existing Debug.log with "key" value -- TODO check bug visibility hidden not emitted on window change but on tab change @@ -137,6 +140,7 @@ type Msg | SoundLoaded (Result D.Error Sound) | ClickedUploadSound | UploadSounds File (List File) + | GotNewSample (Result D.Error File) | ClickedUploadSave | UploadSaves File (List File) | ChangedExplorerTab ExTab @@ -489,6 +493,14 @@ update msg model = (f :: lf) ) + GotNewSample res -> + case res of + Ok file -> + update (UploadSounds file []) model + + Err err -> + Debug.log (D.errorToString err) ( model, Cmd.none ) + ClickedUploadSave -> ( model, Select.files [] UploadSaves ) @@ -653,6 +665,7 @@ subs { doc } = Sub.batch <| [ soundLoaded (SoundLoaded << D.decodeValue Sound.decoder) , BE.onResize (\w h -> GotScreenSize { width = w, height = h }) + , gotNewSample <| (GotNewSample << D.decodeValue File.decoder) ] ++ List.map (Sub.map DocMsg) (Doc.subs doc) ++ List.map (Sub.map KeysMsg) Keys.subs From b2a99f9826782ecfbcaecbac91b07e0f111202e6 Mon Sep 17 00:00:00 2001 From: cbossut Date: Wed, 22 Apr 2020 03:07:17 +0200 Subject: [PATCH 06/85] cmd to launch server from IDE --- notes.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/notes.txt b/notes.txt index af33021..f50409b 100644 --- a/notes.txt +++ b/notes.txt @@ -1,3 +1,4 @@ +start /MIN node index.js elm-live src/Main.elm -s ports.html -- --debug --output=elmApp.js pkg -c pkgConfig.json --targets linux,macos,win,linux-x86,win-x86 --out-path dist index.js From 6f2f45455e3138b525d988239d84e774d6dc5712 Mon Sep 17 00:00:00 2001 From: cbossut Date: Wed, 22 Apr 2020 23:28:36 +0200 Subject: [PATCH 07/85] clean Harmo --- src/Harmony.elm | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/src/Harmony.elm b/src/Harmony.elm index c750f9a..f6dd259 100644 --- a/src/Harmony.elm +++ b/src/Harmony.elm @@ -56,7 +56,7 @@ view : Id (Harmonized g) -> Coll (Harmonized g) -> (Id (Harmonized g) -> String) view id coll getName = let harmo = - (Coll.get id coll).harmony + getHarmo id coll in Fract.toString harmo.fract ++ " de " @@ -81,11 +81,7 @@ defaultRef = clean : Id (Harmonized g) -> Coll (Harmonized g) -> Coll (Harmonized g) clean id coll = - let - harmo = - (Coll.get id coll).harmony - in - case harmo.ref of + case (getHarmo id coll).ref of Other rId -> Coll.update (Coll.idMap rId) (remove id) coll @@ -114,28 +110,12 @@ changeSelf id length coll = resizeFree : Id (Harmonized g) -> Float -> Coll (Harmonized g) -> Coll (Harmonized g) resizeFree id length coll = - let - g = - Coll.get id coll - - harmo = - g.harmony - in - case harmo.ref of - Self r -> - Coll.update id - (always { g | harmony = { harmo | ref = Self { r | unit = length / Fract.toFloat harmo.fract } } }) - coll - - Other rId -> - coll - |> Coll.update id (always { g | harmony = newSelf length }) - |> Coll.update (Coll.idMap rId) (remove id) + changeSelf id (length / Fract.toFloat (getHarmo id coll).fract) coll getLengthId : Id (Harmonized g) -> Coll (Harmonized g) -> Float getLengthId id coll = - getLength (Coll.get id coll).harmony coll + getLength (getHarmo id coll) coll getLength : Harmony -> Coll (Harmonized g) -> Float @@ -178,7 +158,7 @@ hasHarmonics h = getHarmonicGroup : Id (Harmonized g) -> Coll (Harmonized g) -> List (Id (Harmonized g)) getHarmonicGroup id coll = - case (Coll.get id coll).harmony.ref of + case (getHarmo id coll).ref of Self { group } -> id :: List.map Coll.idMap group @@ -272,6 +252,11 @@ getLinks h = List.map Link.map links +getHarmo : Id (Harmonized g) -> Coll (Harmonized g) -> Harmony +getHarmo id coll = + (Coll.get id coll).harmony + + encoder : Harmony -> List ( String, E.Value ) encoder h = [ ( "ref", refEncoder h.ref ) From 2d0637f27681c481e696412970ff3678bf6358d6 Mon Sep 17 00:00:00 2001 From: cbossut Date: Thu, 23 Apr 2020 00:34:34 +0200 Subject: [PATCH 08/85] Autoresize when changing loop points --- src/Editor/Mobile.elm | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index fe711bb..0b3a31c 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -2159,7 +2159,27 @@ manageInteractEvent event model mobile = in case interactWave g event model mobile of Just subMsg -> - update (WheelMsgs [ ( ( id, [] ), subMsg ) ]) ( model, mobile ) + let + ret = + update (WheelMsgs [ ( ( id, [] ), subMsg ) ]) ( model, mobile ) + + newMob = + ret.mobile + + oldPercents = + Wheel.getLoopPercents (Coll.get id mobile.gears) + + newPercents = + Wheel.getLoopPercents (Coll.get id newMob.gears) + + ratio = + (Tuple.second newPercents - Tuple.first newPercents) + / (Tuple.second oldPercents - Tuple.first oldPercents) + + oldLength = + Harmo.getLengthId id mobile.gears + in + { ret | mobile = { newMob | gears = Harmo.resizeFree id (ratio * oldLength) newMob.gears } } Nothing -> return From 3f33efa13d5fd66dee598d23b3faa097e9ca2084 Mon Sep 17 00:00:00 2001 From: cbossut Date: Thu, 23 Apr 2020 01:17:46 +0200 Subject: [PATCH 09/85] Autoresize when add Bead --- src/Editor/Mobile.elm | 107 +++++++++++++++++++++++++----------------- 1 file changed, 64 insertions(+), 43 deletions(-) diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index 0b3a31c..8df7f00 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -2,7 +2,7 @@ port module Editor.Mobile exposing (..) import Coll exposing (Coll, Id) import Color -import Data.Collar as Collar +import Data.Collar as Collar exposing (Beed) import Data.Common as CommonData exposing (Identifier) import Data.Content as Content exposing (Content) import Data.Gear as Gear @@ -386,57 +386,41 @@ update msg ( model, mobile ) = return NewBead c -> - case model.edit of - [ id ] -> - case Wheel.getWheelContent <| CommonData.getWheel ( id, [] ) mobile of - Content.C col -> - { return - | mobile = - CommonData.updateWheel ( id, [] ) - (Wheel.ChangeContent <| Content.C <| Collar.add model.beadCursor (Collar.beadFromContent c) col) - mobile - , toUndo = Group - , model = { model | beadCursor = model.beadCursor + 1 } - , cmd = Random.generate (\color -> WheelMsgs [ ( ( id, [ model.beadCursor ] ), Wheel.ChangeColor color ) ]) colorGen - } - - _ -> - return + case addBead model mobile <| Collar.beadFromContent c of + Just ( newModel, newMobile, id ) -> + { return + | model = newModel + , mobile = newMobile + , toUndo = Group + , cmd = Random.generate (\color -> WheelMsgs [ ( ( id, [ model.beadCursor ] ), Wheel.ChangeColor color ) ]) colorGen + } _ -> return UnpackBead ( w, l ) new -> - case model.edit of - [ id ] -> - case Wheel.getWheelContent <| CommonData.getWheel ( id, [] ) mobile of - Content.C col -> - if new then - { return - | mobile = - CommonData.updateWheel ( id, [] ) - (Wheel.ChangeContent <| Content.C <| Collar.add model.beadCursor { wheel = w, length = l } col) - mobile - , toUndo = Do - , model = { model | beadCursor = model.beadCursor + 1 } - } - - else - Debug.todo "ChangeContent of bead, has to select bead" + if new then + case addBead model mobile { wheel = w, length = l } of + Just ( newModel, newMobile, _ ) -> + { return + | model = newModel + , mobile = newMobile + , toUndo = Do + } - {- case model.common.edit of - [ B i ] -> - update (WheelMsg ( i, Wheel.ChangeContent <| Wheel.getContent { wheel = w } )) ( model, collar ) + _ -> + return - _ -> - return - -} - _ -> - return + else + Debug.todo "ChangeContent of bead, has to select bead" - _ -> - return + {- case model.common.edit of + [ B i ] -> + update (WheelMsg ( i, Wheel.ChangeContent <| Wheel.getContent { wheel = w } )) ( model, collar ) + _ -> + return + -} CopyGear id -> { return | mobile = { mobile | gears = Gear.copy id mobile.gears }, toUndo = Do } @@ -1879,6 +1863,43 @@ doChangeContent id c mayColor model mobile = } +addBead : Model -> Mobeel -> Beed -> Maybe ( Model, Mobeel, Id Geer ) +addBead model mobile bead = + case model.edit of + [ id ] -> + case Wheel.getWheelContent <| CommonData.getWheel ( id, [] ) mobile of + Content.C col -> + let + newCol = + Collar.add model.beadCursor bead col + + newMob = + CommonData.updateWheel ( id, [] ) + (Wheel.ChangeContent <| Content.C newCol) + mobile + + oldLength = + Harmo.getLengthId id mobile.gears + + oldContentLength = + Collar.getTotalLength col + + newContentLength = + Collar.getTotalLength newCol + in + Just + ( { model | beadCursor = model.beadCursor + 1 } + , { newMob | gears = Harmo.resizeFree id (newContentLength * oldLength / oldContentLength) newMob.gears } + , id + ) + + _ -> + Nothing + + _ -> + Nothing + + computeCuts : ( Vec2, Vec2 ) -> Coll Geer -> List (Link Geer) computeCuts cut gears = Motor.getAllLinks gears From 7c5469e047d25f1d6944867115701caa64d43f0e Mon Sep 17 00:00:00 2001 From: cbossut Date: Thu, 23 Apr 2020 03:12:51 +0200 Subject: [PATCH 10/85] Autoresize when rm bead --- src/Editor/Mobile.elm | 48 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index 8df7f00..1b9b83b 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -448,6 +448,52 @@ update msg ( model, mobile ) = } DeleteWheel ( id, l ) -> + let + newMob = + CommonData.deleteWheel ( id, l ) mobile Mobile.rm Collar.rm + + finalMob = + case l of + [ i ] -> + let + colId = + ( id, [] ) + + mayOldCol = + case Wheel.getWheelContent <| CommonData.getWheel colId mobile of + Content.C col -> + Just col + + _ -> + Nothing + + mayNewCol = + case Wheel.getWheelContent <| CommonData.getWheel colId newMob of + Content.C col -> + Just col + + _ -> + Nothing + + mayOldContentLength = + Maybe.map Collar.getTotalLength mayOldCol + + mayNewContentLength = + Maybe.map Collar.getTotalLength mayNewCol + + oldLength = + Harmo.getLengthId id mobile.gears + in + case Maybe.map2 Tuple.pair mayOldContentLength mayNewContentLength of + Just ( oldCL, newCL ) -> + { newMob | gears = Harmo.resizeFree id (newCL * oldLength / oldCL) newMob.gears } + + Nothing -> + newMob + + _ -> + newMob + in { return | model = { model @@ -481,7 +527,7 @@ update msg ( model, mobile ) = } , toUndo = Do , toEngine = [ Engine.stop ] - , mobile = CommonData.deleteWheel ( id, l ) mobile Mobile.rm Collar.rm + , mobile = finalMob } EnteredFract isNumerator str -> From c2f01ec6da3dad890729e9b17485a186d039fd2b Mon Sep 17 00:00:00 2001 From: cbossut Date: Thu, 23 Apr 2020 23:07:18 +0200 Subject: [PATCH 11/85] Fix autoresize with fract --- src/Editor/Mobile.elm | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm index 1b9b83b..1a44322 100644 --- a/src/Editor/Mobile.elm +++ b/src/Editor/Mobile.elm @@ -486,7 +486,7 @@ update msg ( model, mobile ) = in case Maybe.map2 Tuple.pair mayOldContentLength mayNewContentLength of Just ( oldCL, newCL ) -> - { newMob | gears = Harmo.resizeFree id (newCL * oldLength / oldCL) newMob.gears } + { newMob | gears = Harmo.changeSelf id (newCL * oldLength / oldCL) newMob.gears } Nothing -> newMob @@ -1935,7 +1935,7 @@ addBead model mobile bead = in Just ( { model | beadCursor = model.beadCursor + 1 } - , { newMob | gears = Harmo.resizeFree id (newContentLength * oldLength / oldContentLength) newMob.gears } + , { newMob | gears = Harmo.changeSelf id (newContentLength * oldLength / oldContentLength) newMob.gears } , id ) @@ -2246,7 +2246,7 @@ manageInteractEvent event model mobile = oldLength = Harmo.getLengthId id mobile.gears in - { ret | mobile = { newMob | gears = Harmo.resizeFree id (ratio * oldLength) newMob.gears } } + { ret | mobile = { newMob | gears = Harmo.changeSelf id (ratio * oldLength) newMob.gears } } Nothing -> return From 5db33e4da6e57967aeab230fd4d8e8b2966aaa0b Mon Sep 17 00:00:00 2001 From: cbossut Date: Fri, 24 Apr 2020 00:05:02 +0200 Subject: [PATCH 12/85] move startOffset cursor handle --- src/Waveform.elm | 52 ++++++++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/src/Waveform.elm b/src/Waveform.elm index 44ae64b..f31b8fc 100644 --- a/src/Waveform.elm +++ b/src/Waveform.elm @@ -32,6 +32,7 @@ border = type alias Waveform = { size : Int + , height : Int , drawn : Drawing , sel : Maybe ( Int, Int ) } @@ -46,6 +47,7 @@ type Drawing init : Waveform init = { size = 1000 + , height = 150 , drawn = None , sel = Nothing } @@ -161,9 +163,9 @@ view visible wave cursors interState wrapInter = ([ selection ( toPx 0, toPx cursors.start ) Nothing <| rgba 0.5 0.5 0.5 0.5 , selection ( toPx cursors.end, toPx 1 ) Nothing <| rgba 0.5 0.5 0.5 0.5 , selection ( toPx cursors.start, toPx cursors.end ) (Just IWaveSel) <| rgba 0 0 0 0 - , cursor (toPx cursors.start) LoopStart - , cursor (toPx cursors.end) LoopEnd - , cursor (toPx cursors.offset) StartOffset + , cursor (toPx cursors.start) LoopStart wave.height + , cursor (toPx cursors.end) LoopEnd wave.height + , cursor (toPx cursors.offset) StartOffset wave.height ] ++ (case wave.sel of Just points -> @@ -187,15 +189,11 @@ view visible wave cursors interState wrapInter = [] -cursor : Int -> Cursor -> Attribute (Interact.Msg Interactable zone) -cursor pos cur = - inFront <| - el - ([ htmlAttribute <| Attr.style "cursor" "ew-resize" - , Border.width <| border - , height fill - , moveRight <| toFloat <| pos - border - , inFront <| +cursor : Int -> Cursor -> Int -> Attribute (Interact.Msg Interactable zone) +cursor pos cur h = + let + handle attrs = + inFront <| el ([ htmlAttribute <| Attr.style "cursor" "grab" , height <| px <| border * 8 @@ -204,19 +202,29 @@ cursor pos cur = , Bg.color <| rgb 0 0 0 , moveLeft <| toFloat <| border * 4 ] - ++ (case cur of - LoopStart -> - [ alignTop, moveUp <| toFloat border ] - - LoopEnd -> - [ alignBottom, moveDown <| toFloat border ] - - StartOffset -> - [ centerY ] - ) + ++ attrs ) none + in + inFront <| + el + ([ htmlAttribute <| Attr.style "cursor" "ew-resize" + , Border.width <| border + , height fill + , moveRight <| toFloat <| pos - border ] + ++ (case cur of + LoopStart -> + [ handle [ alignTop, moveUp <| toFloat border ] ] + + LoopEnd -> + [ handle [ alignBottom, moveDown <| toFloat border ] ] + + StartOffset -> + [ handle [ centerY, moveDown <| toFloat h / 4 ] + , handle [ centerY, moveUp <| toFloat h / 4 ] + ] + ) ++ (List.map htmlAttribute <| Interact.draggableEvents <| IWaveCursor cur) ) none From 67c431aa0126333efad5b98c4bdc4b1b4db6f4a4 Mon Sep 17 00:00:00 2001 From: cbossut Date: Fri, 24 Apr 2020 00:06:32 +0200 Subject: [PATCH 13/85] Move pack to top --- src/Pack.elm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Pack.elm b/src/Pack.elm index 0b3809a..b8b7d51 100644 --- a/src/Pack.elm +++ b/src/Pack.elm @@ -174,7 +174,7 @@ view pack events wrap interactable surfaceInter wrapInteract = ([ Border.color <| rgb 0 0 0 , Border.width 4 , Bg.color <| rgb 1 1 1 - , alignBottom + , alignTop , alignRight ] ++ (List.map Element.htmlAttribute <| From 537924d0643faaa79aaeeaf8e6eb7bdd36812891 Mon Sep 17 00:00:00 2001 From: cbossut Date: Fri, 24 Apr 2020 00:24:52 +0200 Subject: [PATCH 14/85] =?UTF-8?q?don=E2=80=99t=20display=20sound=20extensi?= =?UTF-8?q?ons?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Main.elm | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/Main.elm b/src/Main.elm index c770464..e915146 100644 --- a/src/Main.elm +++ b/src/Main.elm @@ -862,7 +862,7 @@ viewSoundInLib model s id playing loading = else rgb 1 1 1 ] - { label = text s + { label = text <| cutExtension s , onPress = Just <| if model.mode == Downloading then @@ -944,7 +944,7 @@ soundView s = <| Interact.draggableEvents (Interacting.ISound s) ) - (text (Sound.toString s)) + (text <| cutExtension <| Sound.toString s) viewSaveFiles : Model -> List (Element Msg) @@ -952,7 +952,7 @@ viewSaveFiles model = [ column [ height <| fillPortion 1, width fill, spacing 20, scrollbarY ] <| viewOpenRefreshButtons ClickedUploadSave RequestSavesList model.connected ++ [ column [ width fill, spacing 5, padding 2, scrollbarY ] <| - (List.map (\s -> el [ onClick (RequestSaveLoad s) ] (text <| cutGearsExtension s)) <| + (List.map (\s -> el [ onClick (RequestSaveLoad s) ] (text <| cutExtension s)) <| List.sortWith Natural.compare <| Set.toList model.savesList ) @@ -1019,12 +1019,16 @@ fetchSaveFile url name = , headers = [ Http.header "Cache-Control" "no-cache" ] , url = Url.toString { url | path = "/saves/" ++ name } , body = Http.emptyBody - , expect = Http.expectJson (GotLoadedFile <| cutGearsExtension name) Doc.decoder + , expect = Http.expectJson (GotLoadedFile <| cutExtension name) Doc.decoder , timeout = Nothing , tracker = Nothing } -cutGearsExtension : String -> String -cutGearsExtension = - String.dropRight 6 +cutExtension : String -> String +cutExtension fullName = + let + l = + String.split "." fullName + in + String.join "." <| List.take (List.length l - 1) l From c08fb3fa74e0ed8480ae3b19c47007d369cdf1d9 Mon Sep 17 00:00:00 2001 From: cbossut Date: Fri, 24 Apr 2020 00:59:13 +0200 Subject: [PATCH 15/85] factorize Tab button --- src/Main.elm | 47 +++++++++++++++++------------------------------ 1 file changed, 17 insertions(+), 30 deletions(-) diff --git a/src/Main.elm b/src/Main.elm index e915146..0c9474f 100644 --- a/src/Main.elm +++ b/src/Main.elm @@ -752,36 +752,9 @@ viewFileExplorer model = in column [ height fill, Bg.color bgColor, Font.color (rgb 1 1 1), Font.size 16, spacing 20, padding 10 ] <| ([ row [ Font.size 14, spacing 20 ] - [ Input.button - (if model.fileExplorerTab == Sounds then - [ padding 5, Bg.color (rgb 0.2 0.2 0.2) ] - - else - [ padding 5 ] - ) - { label = text "Sons" - , onPress = Just <| ChangedExplorerTab Sounds - } - , Input.button - (if model.fileExplorerTab == LoadedSounds then - [ padding 5, Bg.color (rgb 0.1 0.1 0.1) ] - - else - [ padding 5 ] - ) - { label = text "Chargés" - , onPress = Just <| ChangedExplorerTab LoadedSounds - } - , Input.button - (if model.fileExplorerTab == Saves then - [ padding 5, Bg.color (rgb 0.1 0.1 0.1) ] - - else - [ padding 5 ] - ) - { label = text "Saves" - , onPress = Just <| ChangedExplorerTab Saves - } + [ viewExplorerTab model.fileExplorerTab Sounds "Sons" + , viewExplorerTab model.fileExplorerTab LoadedSounds "Chargés" + , viewExplorerTab model.fileExplorerTab Saves "Saves" ] ] ++ (case model.fileExplorerTab of @@ -797,6 +770,20 @@ viewFileExplorer model = ) +viewExplorerTab : ExTab -> ExTab -> String -> Element Msg +viewExplorerTab seled tab name = + Input.button + (if seled == tab then + [ padding 5, Bg.color (rgb 0.2 0.2 0.2) ] + + else + [ padding 5 ] + ) + { label = text name + , onPress = Just <| ChangedExplorerTab tab + } + + viewOpenRefreshButtons : Msg -> Msg -> Bool -> List (Element Msg) viewOpenRefreshButtons openMsg refreshMsg connected = [ Input.button [] From 1799d26066879eb7efafb911586ebbf87d1a87e2 Mon Sep 17 00:00:00 2001 From: cbossut Date: Fri, 24 Apr 2020 01:12:17 +0200 Subject: [PATCH 16/85] Can hide full path in loaded sounds tab --- src/Main.elm | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/src/Main.elm b/src/Main.elm index 0c9474f..d0d3533 100644 --- a/src/Main.elm +++ b/src/Main.elm @@ -74,6 +74,7 @@ type alias Model = , currentUrl : Url.Url , soundList : Dict String SoundListType , loadedSoundList : List Sound + , showDirLoad : Bool , savesList : Set String , doc : Doc.Model , screenSize : ScreenSize @@ -107,6 +108,7 @@ init screen url _ = url Dict.empty [] + True Set.empty (Doc.init <| Just url) screen @@ -144,6 +146,7 @@ type Msg | ClickedUploadSave | UploadSaves File (List File) | ChangedExplorerTab ExTab + | ToggleShowDirLoad Bool | ChangedMode Mode | GotScreenSize ScreenSize | DocMsg Doc.Msg @@ -571,6 +574,9 @@ update msg model = ChangedExplorerTab tab -> ( { model | fileExplorerTab = tab }, Cmd.none ) + ToggleShowDirLoad b -> + ( { model | showDirLoad = b }, Cmd.none ) + -- FIXME Code smell? ChangedMode mode -> case mode of @@ -913,16 +919,35 @@ viewDirInLib model str id dict opened = viewLoaded : Model -> List (Element Msg) viewLoaded model = - [ column [ width fill, height <| fillPortion 3, spacing 10, padding 2, scrollbarY ] <| - List.map soundView <| - List.sortWith - (\s t -> Natural.compare (Sound.toString s) (Sound.toString t)) - model.loadedSoundList + [ column [ width fill, height <| fillPortion 3, spacing 10, padding 2, scrollbarY ] + ([ Input.checkbox [] + { label = Input.labelLeft [] <| text "Voir dossiers" + , checked = model.showDirLoad + , onChange = ToggleShowDirLoad + , icon = Input.defaultCheckbox + } + ] + ++ (List.map (soundView model.showDirLoad) <| + List.sortWith + (\s t -> Natural.compare (Sound.toString s) (Sound.toString t)) + model.loadedSoundList + ) + ) ] -soundView : Sound -> Element Msg -soundView s = +soundView : Bool -> Sound -> Element Msg +soundView showDir s = + let + fullPath = + cutExtension <| Sound.toString s + + l = + List.concatMap (String.split "/") <| String.split "\\" fullPath + + justName = + String.join "/" <| List.drop (List.length l - 1) l + in el (List.map (Element.htmlAttribute @@ -931,7 +956,13 @@ soundView s = <| Interact.draggableEvents (Interacting.ISound s) ) - (text <| cutExtension <| Sound.toString s) + (text <| + if showDir then + fullPath + + else + justName + ) viewSaveFiles : Model -> List (Element Msg) From cefc2c4183b904deef3dac91bf08782181a534fb Mon Sep 17 00:00:00 2001 From: cbossut Date: Mon, 27 Apr 2020 03:18:06 +0200 Subject: [PATCH 17/85] remove'n'ignore index.html --- .gitignore | 1 + index.html | 5163 ---------------------------------------------------- 2 files changed, 1 insertion(+), 5163 deletions(-) delete mode 100644 index.html diff --git a/.gitignore b/.gitignore index e44b01b..f606ccc 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ saves # compiled elmApp.js +index.html # elm-package generated files elm-stuff diff --git a/index.html b/index.html deleted file mode 100644 index cb868d2..0000000 --- a/index.html +++ /dev/null @@ -1,5163 +0,0 @@ - - - - - Wheel - - - - - -

-
-
-
-
-
\ No newline at end of file

From 2f86d7186fe4a6ec8b8bd8c78b2b2b51cf101f43 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Wed, 6 May 2020 14:39:37 +0200
Subject: [PATCH 18/85] search filter in file explorer

---
 src/Main.elm | 136 +++++++++++++++++++++++++++++++++++----------------
 1 file changed, 93 insertions(+), 43 deletions(-)

diff --git a/src/Main.elm b/src/Main.elm
index d0d3533..0839819 100644
--- a/src/Main.elm
+++ b/src/Main.elm
@@ -79,6 +79,7 @@ type alias Model =
     , doc : Doc.Model
     , screenSize : ScreenSize
     , fileExplorerTab : ExTab
+    , fileFilter : String
     , mode : Mode
     , keys : Keys.State
     }
@@ -113,6 +114,7 @@ init screen url _ =
         (Doc.init <| Just url)
         screen
         Sounds
+        ""
         NoMode
         Keys.init
     , Cmd.batch [ fetchSoundList url, fetchSavesList url ]
@@ -147,6 +149,7 @@ type Msg
     | UploadSaves File (List File)
     | ChangedExplorerTab ExTab
     | ToggleShowDirLoad Bool
+    | ChgFilter String
     | ChangedMode Mode
     | GotScreenSize ScreenSize
     | DocMsg Doc.Msg
@@ -577,6 +580,9 @@ update msg model =
         ToggleShowDirLoad b ->
             ( { model | showDirLoad = b }, Cmd.none )
 
+        ChgFilter s ->
+            ( { model | fileFilter = s }, Cmd.none )
+
         -- FIXME Code smell?
         ChangedMode mode ->
             case mode of
@@ -757,13 +763,18 @@ viewFileExplorer model =
                     rgb 0.5 0.5 0.5
     in
     column [ height fill, Bg.color bgColor, Font.color (rgb 1 1 1), Font.size 16, spacing 20, padding 10 ] <|
-        ([ row [ Font.size 14, spacing 20 ]
+        (row [ Font.size 14, spacing 20 ]
             [ viewExplorerTab model.fileExplorerTab Sounds "Sons"
             , viewExplorerTab model.fileExplorerTab LoadedSounds "Chargés"
             , viewExplorerTab model.fileExplorerTab Saves "Saves"
             ]
-         ]
-            ++ (case model.fileExplorerTab of
+            :: Input.text [ Font.color (rgb 0 0 0), paddingXY 5 0 ]
+                { label = Input.labelLeft [] <| text "Filtrer\u{202F}:"
+                , text = model.fileFilter
+                , placeholder = Nothing
+                , onChange = ChgFilter
+                }
+            :: (case model.fileExplorerTab of
                     Sounds ->
                         viewSounds model
 
@@ -814,31 +825,54 @@ viewSounds : Model -> List (Element Msg)
 viewSounds model =
     [ column [ width fill, height <| fillPortion 2, spacing 20, scrollbarY ] <|
         viewOpenRefreshButtons ClickedUploadSound RequestSoundList model.connected
-            ++ [ viewLib model [] model.soundList ]
+            ++ [ viewLibColumn <| viewLib model [] model.soundList ]
     ]
 
 
-viewLib : Model -> List String -> Dict String SoundListType -> Element Msg
+viewLibColumn : List (Element Msg) -> Element Msg
+viewLibColumn =
+    column [ width fill, spacing 5, padding 2, scrollbarY ]
+
+
+viewLib : Model -> List String -> Dict String SoundListType -> List (Element Msg)
 viewLib model id dict =
-    column [ width fill, spacing 5, padding 2, scrollbarY ] <|
-        List.concatMap
-            (\( s, sType ) ->
-                case sType of
-                    Stopped ->
-                        [ viewSoundInLib model s (id ++ [ s ]) False False ]
+    List.concatMap
+        (\( s, sType ) ->
+            let
+                newId =
+                    id ++ [ s ]
 
-                    Playing ->
-                        [ viewSoundInLib model s (id ++ [ s ]) True False ]
+                filterOut =
+                    not <| String.contains (String.toLower model.fileFilter) <| String.toLower <| String.join "/" newId
+            in
+            case sType of
+                Stopped ->
+                    if filterOut then
+                        []
 
-                    Loading ->
-                        [ viewSoundInLib model s (id ++ [ s ]) False True ]
+                    else
+                        [ viewSoundInLib model s newId False False ]
 
-                    Directory opened dir ->
-                        viewDirInLib model s (id ++ [ s ]) dir opened
-            )
-        <|
-            List.sortWith (\t1 t2 -> Natural.compare (Tuple.first t1) (Tuple.first t2)) <|
-                Dict.toList dict
+                Playing ->
+                    if filterOut then
+                        []
+
+                    else
+                        [ viewSoundInLib model s newId True False ]
+
+                Loading ->
+                    if filterOut then
+                        []
+
+                    else
+                        [ viewSoundInLib model s newId False True ]
+
+                Directory opened dir ->
+                    viewDirInLib model s newId dir opened
+        )
+    <|
+        List.sortWith (\t1 t2 -> Natural.compare (Tuple.first t1) (Tuple.first t2)) <|
+            Dict.toList dict
 
 
 viewSoundInLib : Model -> String -> List String -> Bool -> Bool -> Element Msg
@@ -895,26 +929,34 @@ viewSoundInLib model s id playing loading =
 
 viewDirInLib : Model -> String -> List String -> Dict String SoundListType -> Bool -> List (Element Msg)
 viewDirInLib model str id dict opened =
-    Input.button [ Font.color <| rgb 1 1 1 ]
-        { label =
-            el [ Font.bold ] <|
-                text <|
-                    (if opened then
-                        "▽"
+    let
+        subView =
+            viewLib model id dict
+    in
+    if not <| List.isEmpty subView then
+        Input.button [ Font.color <| rgb 1 1 1 ]
+            { label =
+                el [ Font.bold ] <|
+                    text <|
+                        (if opened then
+                            "▽"
 
-                     else
-                        "◿"
-                    )
-                        ++ " "
-                        ++ str
-        , onPress = Just <| ExpandDir id
-        }
-        :: (if opened then
-                [ el [ moveRight 10 ] <| viewLib model id dict ]
+                         else
+                            "◿"
+                        )
+                            ++ " "
+                            ++ str
+            , onPress = Just <| ExpandDir id
+            }
+            :: (if opened then
+                    [ el [ moveRight 10 ] <| viewLibColumn subView ]
 
-            else
-                []
-           )
+                else
+                    []
+               )
+
+    else
+        []
 
 
 viewLoaded : Model -> List (Element Msg)
@@ -928,9 +970,8 @@ viewLoaded model =
             }
          ]
             ++ (List.map (soundView model.showDirLoad) <|
-                    List.sortWith
-                        (\s t -> Natural.compare (Sound.toString s) (Sound.toString t))
-                        model.loadedSoundList
+                    List.sortWith (\s t -> Natural.compare (Sound.toString s) (Sound.toString t)) <|
+                        filterFiles model.fileFilter Sound.toString model.loadedSoundList
                )
         )
     ]
@@ -972,7 +1013,8 @@ viewSaveFiles model =
             ++ [ column [ width fill, spacing 5, padding 2, scrollbarY ] <|
                     (List.map (\s -> el [ onClick (RequestSaveLoad s) ] (text <| cutExtension s)) <|
                         List.sortWith Natural.compare <|
-                            Set.toList model.savesList
+                            filterFiles model.fileFilter identity <|
+                                Set.toList model.savesList
                     )
                ]
     ]
@@ -1043,6 +1085,14 @@ fetchSaveFile url name =
         }
 
 
+filterFiles : String -> (a -> String) -> List a -> List a
+filterFiles filter toString =
+    List.filter <|
+        (String.contains <| String.toLower filter)
+            << String.toLower
+            << toString
+
+
 cutExtension : String -> String
 cutExtension fullName =
     let

From b09469ebc187fe540d1a9d8ad95ac8fc0827f8c7 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Wed, 6 May 2020 14:39:54 +0200
Subject: [PATCH 19/85] Edit play works even if muted

---
 src/Editor/Mobile.elm | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index 1a44322..ee5a4d2 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -343,8 +343,12 @@ update msg ( model, mobile ) =
             case model.tool of
                 Edit _ ->
                     let
+                        demutedMobile =
+                            model.edit
+                                |> List.foldl (\id mob -> CommonData.updateWheel ( id, [] ) (Wheel.Mute False) mob) mobile
+
                         ( engine, v ) =
-                            Engine.addPlaying model.edit mobile.gears model.engine
+                            Engine.addPlaying model.edit demutedMobile.gears model.engine
                     in
                     { return | model = { model | engine = engine, tool = Edit True }, toEngine = v }
 

From 422fd260fec8ab25a908aa39b80e5e45876c29ac Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Fri, 3 Jul 2020 13:06:17 +0200
Subject: [PATCH 20/85] ignore generated test things

test with elm-spa, still too much in dev
---
 .gitignore | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/.gitignore b/.gitignore
index f606ccc..dacd9d3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,9 @@ index.html
 # elm-package generated files
 elm-stuff
 
+# elm-spa generated files
+test/src/Generated/
+
 # unknown elm stuff ?
 .elm*
 

From 5f6641e0e72fa7c3e5435f9e5960cbab34cda4f9 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Fri, 3 Jul 2020 18:25:54 +0200
Subject: [PATCH 21/85] No selection outside input

---
 ports.html | 24 ++++++++++++------------
 style.css  | 23 ++++++++++++-----------
 2 files changed, 24 insertions(+), 23 deletions(-)

diff --git a/ports.html b/ports.html
index 421b037..bba8f72 100644
--- a/ports.html
+++ b/ports.html
@@ -6,20 +6,20 @@
 
 
 
-
-  
-  
-  
-  
-  
-  
-  
-
 
+  
+    
+    
+    
+    
+    
+    
+    
+      
+  
+  
   
-    
     
-
   
 
-
+
\ No newline at end of file
diff --git a/style.css b/style.css
index f5996d5..7e11676 100644
--- a/style.css
+++ b/style.css
@@ -1,16 +1,17 @@
-
-svg {
-  touch-action: none;
+* {
+  user-select: none;
+  -webkit-user-select: none;
+  -moz-user-select: none;
+  -ms-user-select: none;
 }
 
-
-
-#gear {
-  transition: 5s
+input {
+  user-select: auto;
+  -webkit-user-select: auto;
+  -moz-user-select: auto;
+  -ms-user-select: auto;
 }
 
-.rotate {
-  transition: 5s;
-  transform-origin: center;
-  transform: rotate(36deg);
+#svgResizeObserver {
+  touch-action: none;
 }

From bb96567eabec65467b2e62d57e88007188b35589 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Wed, 8 Jul 2020 15:06:38 +0200
Subject: [PATCH 22/85] Try n prevent push to refresh

---
 ports.html | 2 +-
 style.css  | 8 ++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/ports.html b/ports.html
index bba8f72..e3eb04c 100644
--- a/ports.html
+++ b/ports.html
@@ -15,7 +15,7 @@
     
     
     
-      
+    
   
   
   
diff --git a/style.css b/style.css
index 7e11676..768b453 100644
--- a/style.css
+++ b/style.css
@@ -5,6 +5,14 @@
   -ms-user-select: none;
 }
 
+body {
+  overscroll-behavior: contain;
+}
+
+div {
+  overscroll-behavior: contain;
+}
+
 input {
   user-select: auto;
   -webkit-user-select: auto;

From cf6d871db95ad3f62e8f19c926b2fc568f5bc337 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Thu, 8 Oct 2020 20:17:17 +0200
Subject: [PATCH 23/85] minor

---
 notes.txt | 1 +
 ports.js  | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/notes.txt b/notes.txt
index f50409b..71c82af 100644
--- a/notes.txt
+++ b/notes.txt
@@ -1,5 +1,6 @@
 start /MIN node index.js
 elm-live src/Main.elm -s ports.html -- --debug --output=elmApp.js
+
 pkg -c pkgConfig.json --targets linux,macos,win,linux-x86,win-x86 --out-path dist index.js
 
 Serveur : log gears mdp GearsPassWord
diff --git a/ports.js b/ports.js
index 5bc3e40..71bc77e 100644
--- a/ports.js
+++ b/ports.js
@@ -58,7 +58,7 @@ function toggleRecord(bool) {
 }
 
 function cutSample(infos) {
-    if (!buffers[infos.fromFileName]) {console.err(infos.fromFileName + " ain’t loaded, cannot cut");return;}
+    if (!buffers[infos.fromFileName]) {console.error(infos.fromFileName + " ain’t loaded, cannot cut");return;}
 
     let buf = buffers[infos.fromFileName]._buffer
       , start = infos.percents[0] * buf.length - 1

From 4418346678e7d66acd33e8a431a40c00b7c09968 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Thu, 8 Oct 2020 20:21:31 +0200
Subject: [PATCH 24/85] basic mic record to sound list

---
 ports.js     | 22 ++++++++++++++++
 src/Main.elm | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 92 insertions(+), 1 deletion(-)

diff --git a/ports.js b/ports.js
index 71bc77e..e6ef456 100644
--- a/ports.js
+++ b/ports.js
@@ -5,12 +5,18 @@ if (app.ports.toEngine) app.ports.toEngine.subscribe(engine)
 if (app.ports.toggleRecord) app.ports.toggleRecord.subscribe(toggleRecord)
 if (app.ports.requestSoundDraw) app.ports.requestSoundDraw.subscribe(drawSound)
 if (app.ports.requestCutSample) app.ports.requestCutSample.subscribe(cutSample)
+if (app.ports.openMic) app.ports.openMic.subscribe(openMic)
+if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
     , nodeToRecord = Tone.context.createGain()
     , recorder = new Recorder(nodeToRecord)
+    , mic = new Tone.UserMedia()
+    , micToRecord = Tone.context.createGain()
+    , micRecorder = new Recorder(micToRecord)
 Tone.Master.connect(nodeToRecord)
+mic.connect(micToRecord)
 ro.observe(document.getElementById('svgResizeObserver'))
 
 let playing = {}
@@ -57,6 +63,22 @@ function toggleRecord(bool) {
     }
 }
 
+function openMic() {
+  Tone.start()
+  mic.open().then(
+    () => app.ports.micOpened.send(null)
+  ).catch(console.error)
+}
+
+function inputRec(name) {
+  if (name) {
+    micRecorder.stop()
+    micRecorder.exportWAV(bl => app.ports.gotNewSample.send(new File([bl], name + ".wav", {type: "audio/wav"})))
+    micRecorder.clear()
+  } else if (mic.state == "started") micRecorder.record()
+  else console.error("won’t record mic if it ain’t opened !")
+}
+
 function cutSample(infos) {
     if (!buffers[infos.fromFileName]) {console.error(infos.fromFileName + " ain’t loaded, cannot cut");return;}
 
diff --git a/src/Main.elm b/src/Main.elm
index 0839819..1d534f8 100644
--- a/src/Main.elm
+++ b/src/Main.elm
@@ -41,6 +41,15 @@ port loadSound : String -> Cmd msg
 port soundLoaded : (D.Value -> msg) -> Sub msg
 
 
+port openMic : () -> Cmd msg
+
+
+port micOpened : (() -> msg) -> Sub msg
+
+
+port inputRec : String -> Cmd msg
+
+
 port gotNewSample : (D.Value -> msg) -> Sub msg
 
 
@@ -72,6 +81,7 @@ main =
 type alias Model =
     { connected : Bool
     , currentUrl : Url.Url
+    , micState : Maybe ( Bool, String )
     , soundList : Dict String SoundListType
     , loadedSoundList : List Sound
     , showDirLoad : Bool
@@ -107,6 +117,7 @@ init screen url _ =
     ( Model
         False
         url
+        Nothing
         Dict.empty
         []
         True
@@ -142,6 +153,11 @@ type Msg
     | GotSavesList (Result Http.Error String)
     | GotLoadedFile String (Result Http.Error Doc)
     | SoundLoaded (Result D.Error Sound)
+    | RequestOpenMic
+    | MicOpened
+    | StartMicRec
+    | EndMicRec String
+    | EnteredNewRecName String
     | ClickedUploadSound
     | UploadSounds File (List File)
     | GotNewSample (Result D.Error File)
@@ -475,6 +491,27 @@ update msg model =
                 Ok s ->
                     ( { model | loadedSoundList = s :: model.loadedSoundList }, Cmd.none )
 
+        RequestOpenMic ->
+            ( model, openMic () )
+
+        MicOpened ->
+            ( { model | micState = Just ( False, "" ) }, Cmd.none )
+
+        StartMicRec ->
+            ( { model | micState = Maybe.map (Tuple.mapFirst <| always True) model.micState }
+            , inputRec ""
+            )
+
+        EndMicRec fileName ->
+            ( { model | micState = Maybe.map (Tuple.mapFirst <| always False) model.micState }
+            , inputRec fileName
+            )
+
+        EnteredNewRecName fileName ->
+            ( { model | micState = Maybe.map (Tuple.mapSecond <| always fileName) model.micState }
+            , Cmd.none
+            )
+
         ClickedUploadSound ->
             ( model, Select.files soundMimeTypes UploadSounds )
 
@@ -677,6 +714,7 @@ subs { doc } =
     Sub.batch <|
         [ soundLoaded (SoundLoaded << D.decodeValue Sound.decoder)
         , BE.onResize (\w h -> GotScreenSize { width = w, height = h })
+        , micOpened <| always MicOpened
         , gotNewSample <| (GotNewSample << D.decodeValue File.decoder)
         ]
             ++ List.map (Sub.map DocMsg) (Doc.subs doc)
@@ -824,7 +862,38 @@ viewOpenRefreshButtons openMsg refreshMsg connected =
 viewSounds : Model -> List (Element Msg)
 viewSounds model =
     [ column [ width fill, height <| fillPortion 2, spacing 20, scrollbarY ] <|
-        viewOpenRefreshButtons ClickedUploadSound RequestSoundList model.connected
+        [ row [ width fill, spacing 40 ]
+            [ column [ spacing 20 ] <|
+                viewOpenRefreshButtons ClickedUploadSound RequestSoundList model.connected
+            , column [ width fill, spacing 20 ] <|
+                case model.micState of
+                    Just ( False, name ) ->
+                        [ Input.button []
+                            { onPress =
+                                if String.isEmpty name then
+                                    Nothing
+
+                                else
+                                    Just StartMicRec
+                            , label = text "Rec Mic"
+                            }
+                        , Input.text [ Font.color (rgb 0 0 0), paddingXY 5 0 ]
+                            { text = name
+                            , placeholder = Just <| Input.placeholder [] <| text "Nom du fichier"
+                            , label = Input.labelHidden "New File Name"
+                            , onChange = EnteredNewRecName
+                            }
+                        ]
+
+                    Just ( True, name ) ->
+                        [ Input.button [] { onPress = Just <| EndMicRec name, label = text "Stop Mic" }
+                        , text name
+                        ]
+
+                    Nothing ->
+                        [ Input.button [] { onPress = Just RequestOpenMic, label = text "Activer Micro" } ]
+            ]
+        ]
             ++ [ viewLibColumn <| viewLib model [] model.soundList ]
     ]
 

From ed4acd22e1829a18c80d8b99bc77a9ccf303fa40 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Thu, 8 Oct 2020 20:39:53 +0200
Subject: [PATCH 25/85] fix wrong svg size due to overflow

---
 src/Doc.elm | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/Doc.elm b/src/Doc.elm
index aa22992..55ece0f 100644
--- a/src/Doc.elm
+++ b/src/Doc.elm
@@ -303,6 +303,10 @@ view doc =
                 [ width fill
                 , height fill
                 , Element.htmlAttribute <| Html.Attributes.id "svgResizeObserver"
+
+                -- THX to https://discourse.elm-lang.org/t/elm-ui-parent-element-grows-to-encompass-children-instead-of-scrolling/5032
+                , clip
+                , htmlAttribute <| Html.Attributes.style "flex-shrink" "1"
                 ]
                <|
                 viewContent doc

From eb4ae746e5cc607ee7cb4a6c9f8f2b8ebb375883 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 10 Oct 2020 14:27:03 +0200
Subject: [PATCH 26/85] =?UTF-8?q?add=20favicon=E2=80=AF!?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 icone.svg  | 312 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 ports.html |   1 +
 2 files changed, 313 insertions(+)
 create mode 100644 icone.svg

diff --git a/icone.svg b/icone.svg
new file mode 100644
index 0000000..4025062
--- /dev/null
+++ b/icone.svg
@@ -0,0 +1,312 @@
+
+
+
+
+  
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+  
+  
+  
+    
+      
+        image/svg+xml
+        
+        
+      
+    
+  
+  
+    
+      
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+      
+    
+    
+      
+        
+          
+        
+        
+          
+        
+      
+    
+    
+      
+        
+          
+        
+      
+    
+    
+      
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+      
+    
+    
+      
+        
+          
+        
+        
+          
+        
+        
+          
+        
+      
+    
+  
+
diff --git a/ports.html b/ports.html
index e3eb04c..0626a68 100644
--- a/ports.html
+++ b/ports.html
@@ -16,6 +16,7 @@
     
     
     
+    
   
   
   

From 49ae0df800a857048534d4018ab25dadad9e9e62 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 10 Oct 2020 20:03:36 +0200
Subject: [PATCH 27/85] enhance wave drawing

---
 ports.js | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/ports.js b/ports.js
index e6ef456..cb9e0c8 100644
--- a/ports.js
+++ b/ports.js
@@ -161,18 +161,24 @@ function drawSamples(samples) {
       if (pxPerSample < 0.5) {
         for (let x = 0 ; x < width ; x++) {
           let px = samples.slice(Math.floor(x / pxPerSample), Math.floor((x + 1) / pxPerSample))
+            , minPoint = (Math.min.apply(null, px) + 1) * height / 2
+            , maxPoint = (Math.max.apply(null, px) + 1) * height / 2
           ctx.strokeStyle = 'black'
           ctx.beginPath()
-          ctx.moveTo(x, (Math.min.apply(null, px) + 1) * height / 2)
-          ctx.lineTo(x, (Math.max.apply(null, px) + 1) * height / 2)
+          ctx.moveTo(x, minPoint)
+          ctx.lineTo(x, maxPoint)
           ctx.stroke()
 
           let rms = Math.sqrt(px.reduce((acc,v,i,a) => acc + Math.pow(v, 2)) / px.length)
-          ctx.strokeStyle = 'gray'
-          ctx.beginPath()
-          ctx.moveTo(x, (1 - rms) * height / 2)
-          ctx.lineTo(x, (1 + rms) * height / 2)
-          ctx.stroke()
+            , minRmsPoint = (1 - rms) * height / 2
+            , maxRmsPoint = (1 + rms) * height / 2
+          if (minRmsPoint > minPoint && maxRmsPoint < maxPoint) {
+              ctx.strokeStyle = 'gray'
+              ctx.beginPath()
+              ctx.moveTo(x, minRmsPoint)
+              ctx.lineTo(x, maxRmsPoint)
+              ctx.stroke()
+          }
         }
       } else {
         ctx.strokeStyle = 'black'

From 1716969dc121ad6ad2f5f60d2c1658e6f1df1a39 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 11 Oct 2020 20:17:29 +0200
Subject: [PATCH 28/85] crude tonejs 14.7 update

---
 lib/Tone.js | 26 ++++++++++++++++++++------
 1 file changed, 20 insertions(+), 6 deletions(-)

diff --git a/lib/Tone.js b/lib/Tone.js
index e6cf9dd..7f8f33d 100644
--- a/lib/Tone.js
+++ b/lib/Tone.js
@@ -1,8 +1,22 @@
-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Tone=e():t.Tone=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function i(s){if(e[s])return e[s].exports;var n=e[s]={i:s,l:!1,exports:{}};return t[s].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=t,i.c=e,i.d=function(t,e,s){i.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:s})},i.r=function(t){Object.defineProperty(t,"__esModule",{value:!0})},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=148)}([function(t,e,i){"use strict";i.r(e),function(t){var s=i(93),n=function(){if(!(this instanceof n))throw new Error("constructor needs to be called with the 'new' keyword")};
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Tone=e():t.Tone=e()}("undefined"!=typeof self?self:this,(function(){return function(t){var e={};function n(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return t[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,s){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:s})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(s,i,function(e){return t[e]}.bind(null,i));return s},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=684)}([function(t,e,n){"use strict";n.d(e,"a",(function(){return s})),n.d(e,"b",(function(){return i})),n.d(e,"c",(function(){return o})),n.d(e,"d",(function(){return r})),n.d(e,"e",(function(){return a})),n.d(e,"f",(function(){return c})),n.d(e,"g",(function(){return u})),n.d(e,"i",(function(){return h})),n.d(e,"h",(function(){return l})),n.d(e,"j",(function(){return d})),n.d(e,"k",(function(){return p}));const s=new WeakSet,i=new WeakMap,o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,u=new WeakMap,h=new WeakMap,l=new WeakMap,d=new WeakMap,p=new WeakMap},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(4);const i=(t,e)=>{Object(s.a)(t,e,"channelCount"),Object(s.a)(t,e,"channelCountMode"),Object(s.a)(t,e,"channelInterpretation")}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s})),n.d(e,"b",(function(){return i}));const s=-34028234663852886e22,i=-s},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>t.context===e},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n]&&(t[n]=s)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n].value&&(t[n].value=s)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.c,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","InvalidStateError")}catch(t){return t.code=11,t.name="InvalidStateError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.b,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>{const n=t.get(e);if(void 0===n)throw new Error("A value with the given key could not be found.");return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","NotSupportedError")}catch(t){return t.code=9,t.name="NotSupportedError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"inputs"in t},function(t,e,n){"use strict";n.d(e,"AudioContext",(function(){return Oi})),n.d(e,"AudioWorkletNode",(function(){return qi})),n.d(e,"OfflineAudioContext",(function(){return Vi})),n.d(e,"isAnyAudioContext",(function(){return Ni})),n.d(e,"isAnyAudioNode",(function(){return Pi})),n.d(e,"isAnyAudioParam",(function(){return Li})),n.d(e,"isAnyOfflineAudioContext",(function(){return zi})),n.d(e,"isSupported",(function(){return Bi}));var s=n(18),i=n(516),o=n(517),r=n(518),a=n(667),c=n(519),u=n(520),h=n(521),l=n(522),d=n(523),p=n(524),f=n(525),_=n(526),m=n(527),g=n(528),v=n(529),y=n(665),b=n(530),x=n(531),w=n(532),T=n(670),O=n(533),S=n(534),C=n(535),k=n(536),A=n(537),D=n(538),M=n(539),j=n(540),E=n(541),R=n(542),q=n(543),I=n(544),F=n(545),V=n(546),N=n(547),P=n(548),L=n(549),z=n(550),B=n(671),W=n(551),U=n(552),G=n(553),Y=n(554),Q=n(672),Z=n(555),X=n(556),H=n(557),$=n(558),J=n(559),K=n(560),tt=n(561),et=n(562),nt=n(563),st=n(564),it=n(565),ot=n(566),rt=n(567),at=n(568),ct=n(569),ut=n(673),ht=n(570),lt=n(571),dt=n(15),pt=n(37),ft=n(7),_t=n(572),mt=n(573),gt=n(574),vt=n(575),yt=n(576),bt=n(577),xt=n(578),wt=n(579),Tt=n(580),Ot=n(581),St=n(582),Ct=n(583),kt=n(584),At=n(585),Dt=n(586),Mt=n(587),jt=n(588),Et=n(589),Rt=n(590),qt=n(668),It=n(591),Ft=n(669),Vt=n(592),Nt=n(593),Pt=n(594),Lt=n(595),zt=n(674),Bt=n(666),Wt=n(596),Ut=n(597),Gt=n(675),Yt=n(598),Qt=n(599),Zt=n(600),Xt=n(601),Ht=n(602),$t=n(603),Jt=n(604),Kt=n(605),te=n(606),ee=n(607),ne=n(608),se=n(609),ie=n(610),oe=n(611),re=n(612),ae=n(613),ce=n(614),ue=n(615),he=n(616),le=n(617),de=n(618),pe=n(619),fe=n(620),_e=n(10),me=n(621),ge=n(622),ve=n(623),ye=n(624),be=n(625),xe=n(626),we=n(627),Te=n(628),Oe=n(629),Se=n(630),Ce=n(631),ke=n(632),Ae=n(633),De=n(634),Me=n(635),je=n(636),Ee=n(637),Re=n(638),qe=n(639),Ie=n(640),Fe=n(641),Ve=n(642),Ne=n(643),Pe=n(644),Le=n(645),ze=n(646),Be=n(647),We=n(648),Ue=n(649),Ge=n(650),Ye=n(651),Qe=n(652),Ze=n(653),Xe=n(654),He=n(44),$e=n(655),Je=n(656),Ke=n(657),tn=n(658),en=n(659),nn=n(660),sn=n(661),on=n(662),rn=n(0),an=n(33),cn=n(34),un=n(8),hn=n(26),ln=n(6),dn=n(27),pn=n(9),fn=n(16),_n=n(23),mn=n(45),gn=n(19),vn=n(38),yn=n(32),bn=n(14),xn=n(663),wn=n(664),Tn=n(28);n(46),n(130);const On=Object(k.a)(new Map,new WeakMap),Sn=Object(Ke.a)(),Cn=Object(oe.a)(Sn),kn=Object(Tt.a)(Cn),An=Object(Vt.a)(Sn),Dn=Object(rt.a)(kn,An,Cn),Mn=Object(Pt.a)(Dn),jn=Object(qt.a)(On,dt.a,Mn),En=Object(it.a)(un.a),Rn=Object(Te.a)(un.a,En,gn.a),qn=Object(l.a)(jn,ln.a,Rn),In=new WeakMap,Fn=Object(at.a)(rn.g),Vn=new WeakMap,Nn=Object(K.a)(Tn.a),Pn=Object(yt.a)(An),Ln=Object(bt.a)(Sn),zn=Object(xt.a)(Sn),Bn=Object(y.a)(Object(o.a)(rn.b),In,On,Object(lt.a)(rn.h,cn.a,un.a,ln.a,dn.a,_n.a),dt.a,pt.a,_e.a,Object(W.a)(an.a,rn.h,un.a,ln.a,dn.a,Fn,_n.a,kn),Object(Q.a)(Vn,un.a,pn.a),Nn,Fn,Pn,Ln,zn,kn),Wn=Object(h.a)(Bn,qn,dt.a,jn,Fn,kn),Un=new WeakSet,Gn=Object(It.a)(Sn),Yn=Object(V.a)(new Uint32Array(1)),Qn=Object(tn.a)(Yn,dt.a),Zn=Object(en.a)(Yn),Xn=Object(d.a)(Un,On,_e.a,Gn,Cn,Object(De.a)(Gn),Qn,Zn),Hn=Object(Jt.a)(Mn),$n=Object(c.a)(Hn),Jn=Object(Pe.a)(Mn),Kn=Object(Le.a)(Mn),ts=Object(ze.a)(Mn),es=Object(sn.a)(Mn),ns=Object(Oe.a)(En,hn.a,gn.a),ss=Object(E.a)(ns),is=Object(Ft.a)($n,On,Mn,Object(je.a)(Mn),Object(Ee.a)(Cn),Object(Re.a)(Mn),Object(qe.a)(Mn),Jn,Kn,ts,wn.a,Object(nn.a)(vn.a),es),os=Object(we.a)(Object(ot.a)(hn.a),ns),rs=Object(f.a)(ss,is,ln.a,os,Rn),as=Object(b.a)(Object(r.a)(rn.d),Vn,rn.e,x.a,s.createCancelAndHoldAutomationEvent,s.createCancelScheduledValuesAutomationEvent,s.createExponentialRampToValueAutomationEvent,s.createLinearRampToValueAutomationEvent,s.createSetTargetAutomationEvent,s.createSetValueAutomationEvent,s.createSetValueCurveAutomationEvent,An),cs=Object(p.a)(Bn,rs,as,ft.a,is,Fn,kn,Tn.a),us=Object(m.a)(Bn,g.a,dt.a,ft.a,Object(Nt.a)(Hn,vn.a),Fn,kn,Rn),hs=Object(Wt.a)(Mn),ls=Object(C.a)(ss,hs,ln.a,os,Rn),ds=Object(S.a)(Bn,as,ls,pt.a,hs,Fn,kn),ps=Object(Rt.a)(fn.a,Ln),fs=Object(on.a)(ft.a,Mn,ps),_s=Object(Ut.a)(Mn,fs),ms=Object(D.a)(_s,ln.a,Rn),gs=Object(A.a)(Bn,ms,_s,Fn,kn),vs=Object(Gt.a)(Mn),ys=Object(j.a)(vs,ln.a,Rn),bs=Object(M.a)(Bn,ys,vs,Fn,kn),xs=Object(Qt.a)($n,is,Hn,ps),ws=Object(Yt.a)($n,On,Mn,xs,Jn,ts),Ts=Object(F.a)(ss,ws,ln.a,os,Rn),Os=Object(I.a)(Bn,as,Ts,ws,Fn,kn,Tn.a),Ss=Object(Xt.a)(Mn,Hn,ps),Cs=Object(Zt.a)(Mn,Ss,_e.a,vn.a),ks=Object(P.a)(Cs,ln.a,Rn),As=Object(N.a)(Bn,ks,Cs,Fn,kn),Ds=Object(Ht.a)(Mn),Ms=Object(G.a)(ss,Ds,ln.a,os,Rn),js=Object(U.a)(Bn,as,Ms,Ds,Fn,kn),Es=Object($t.a)(Mn,_e.a),Rs=Object(H.a)(ss,Es,ln.a,os,Rn),qs=Object(X.a)(Bn,as,Rs,Es,_e.a,Fn,kn),Is=Object(st.a)(ss,Hn,ln.a,os,Rn),Fs=Object(nt.a)(Bn,as,Is,Hn,Fn,kn),Vs=Object(he.a)(Mn),Ns=Object(te.a)(pt.a,ft.a,Vs,_e.a),Ps=Object(Se.a)(On,Hn,Vs,Object(Ze.a)(Hn,Cn)),Ls=Object(ht.a)(is,Mn,ln.a,Cn,Rn,Ps),zs=Object(Kt.a)(Mn,Ns),Bs=Object(ut.a)(Bn,zs,Ls,Fn,kn),Ws=Object(v.a)(as,_s,ws,Vs,kn),Us=new WeakMap,Gs=Object(jt.a)(us,Ws,Nn,kn,Us,Tn.a),Ys=Object(re.a)($n,On,Mn,Jn,Kn,ts,es),Qs=Object(ve.a)(ss,Ys,ln.a,os,Rn),Zs=Object(ge.a)(Bn,as,ft.a,Ys,Qs,Fn,kn,Tn.a),Xs=Object(q.a)(is),Hs=Object(fe.a)(Xs,ft.a,Mn,Hn,mn.a,ps),$s=Object(pe.a)(Xs,ft.a,Mn,Hs,mn.a,ps,vn.a),Js=Object(ce.a)(an.a,ft.a,Mn,_s,Hn,Vs,$s,_e.a,cn.a,ps),Ks=Object(ae.a)(Mn,Js),ti=Object(be.a)(ss,_s,ws,Hn,Ks,ln.a,Cn,os,Rn,Ps),ei=Object(ye.a)(Bn,as,Ks,ti,Fn,kn),ni=Object(ue.a)(Dn),si=Object(xe.a)(ni,Fn,new WeakSet),ii=Object(de.a)(_s,vs,Hn,$s,_e.a,ps),oi=Object(le.a)(Mn,ii,_e.a),ri=Object(Ae.a)(ss,oi,ln.a,os,Rn),ai=Object(ke.a)(Bn,as,oi,ri,Fn,kn),ci=Object(Je.a)($s,ln.a,Rn),ui=Object($e.a)(Bn,ft.a,$s,ci,Fn,kn),hi=Object(Ot.a)(Sn),li=Object(tt.a)(Sn),di=hi?Object(a.a)(_e.a,Object(J.a)(Sn),li,Object(et.a)(i.a),Dn,Fn,new WeakMap,new WeakMap,Sn):void 0,pi=Object(wt.a)(Pn,kn),fi=Object(B.a)(Un,On,z.a,$.a,new WeakSet,Fn,pi,kn,Cn,yn.a,bn.a,Qn,Zn),_i=Object(O.a)(di,Wn,Xn,cs,ds,gs,bs,Os,As,fi,js,qs,Fs,Bs,Gs,Zs,ei,si,ai,ui),mi=Object(ee.a)(Mn),gi=Object(Ct.a)(Bn,mi,Fn,kn),vi=Object(ne.a)(Mn,_e.a),yi=Object(kt.a)(Bn,vi,Fn,kn),bi=Object(se.a)(Mn),xi=Object(At.a)(Bn,bi,Fn,kn),wi=Object(ie.a)(ft.a,Mn,kn),Ti=Object(Dt.a)(Bn,wi,Fn),Oi=Object(_.a)(_i,ft.a,_e.a,He.a,gi,yi,xi,Ti,An),Si=Object(ct.a)(Us),Ci=Object(u.a)(Si),ki=Object(R.a)(dt.a),Ai=Object(Y.a)(Si),Di=Object(Z.a)(dt.a),Mi=Object(Bt.a)(In,ki,dt.a,ft.a,_s,vs,ws,Hn,Vs,_e.a,Di,li,ps),ji=Object(zt.a)(ft.a,Mn,Mi,Hn,_e.a,ps),Ei=Object(Lt.a)(Sn),Ri=Object(T.a)(ss,ki,is,_s,vs,ws,Hn,Ai,Di,li,ln.a,Ei,Cn,os,Rn,Ps),qi=hi?Object(w.a)(Ci,Bn,as,Ri,ji,Fn,kn,Ei,Tn.a):void 0,Ii=(Object(Mt.a)(ft.a,_e.a,He.a,Gs,An),Object(L.a)(_e.a,Cn)),Fi=Object(Ce.a)(Un,On,En,Si,Ps,yn.a,Qn,Zn),Vi=(Object(Et.a)(On,ft.a,Ii,Gs,Fi),Object(me.a)(_i,On,ft.a,Ii,Fi)),Ni=Object(_t.a)(rn.g,Pn),Pi=Object(mt.a)(rn.c,Ln),Li=Object(gt.a)(rn.e,zn),zi=Object(vt.a)(rn.g,kn),Bi=()=>Object(St.a)(On,Object(Me.a)(Cn),Object(Ie.a)(An),Object(Fe.a)(Cn),Object(Ve.a)(An),Object(Ne.a)(Cn),Object(Be.a)(Ei,Cn),Object(We.a)(Mn,Cn),Object(Ue.a)(Mn,Cn),Object(Ge.a)(Cn),Object(Ye.a)(Sn),Object(Qe.a)(An),Object(Xe.a)(Cn),xn.a)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const n=t.decodeAudioData(e.buffer,()=>{});return void 0!==n&&(n.catch(()=>{}),!0)}catch{}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","IndexSizeError")}catch(t){return t.code=1,t.name="IndexSizeError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>{for(const e of t)if(n(e)){if(s)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(20);const o=t=>{if(s.a.has(t))throw new Error("The AudioNode is already stored.");s.a.add(t),Object(i.a)(t).forEach(t=>t(!0))}},function(t,e,n){!function(t,e,n,s){"use strict";e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e,n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n,s=s&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s;var i=function(t,e,n){return{endTime:e,insertTime:n,type:"exponentialRampToValue",value:t}},o=function(t,e,n){return{endTime:e,insertTime:n,type:"linearRampToValue",value:t}},r=function(t,e){return{startTime:e,type:"setValue",value:t}},a=function(t,e,n){return{duration:n,startTime:e,type:"setValueCurve",values:t}},c=function(t,e,n){var s=n.startTime,i=n.target,o=n.timeConstant;return i+(e-i)*Math.exp((s-t)/o)},u=function(t){return"exponentialRampToValue"===t.type},h=function(t){return"linearRampToValue"===t.type},l=function(t){return u(t)||h(t)},d=function(t){return"setValue"===t.type},p=function(t){return"setValueCurve"===t.type},f=function t(e,n,s,i){var o=e[n];return void 0===o?i:l(o)||d(o)?o.value:p(o)?o.values[o.values.length-1]:c(s,t(e,n-1,o.startTime,i),o)},_=function(t,e,n,s,i){return void 0===n?[s.insertTime,i]:l(n)?[n.endTime,n.value]:d(n)?[n.startTime,n.value]:p(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,f(t,e-1,n.startTime,i)]},m=function(t){return"cancelAndHold"===t.type},g=function(t){return"cancelScheduledValues"===t.type},v=function(t){return m(t)||g(t)?t.cancelTime:u(t)||h(t)?t.endTime:t.startTime},y=function(t,e,n,s){var i=s.endTime,o=s.value;return n===o?o:0=e})),s=this._automationEvents[n];if(-1!==n&&(this._automationEvents=this._automationEvents.slice(0,n)),m(t)){var c=this._automationEvents[this._automationEvents.length-1];if(void 0!==s&&l(s)){if(w(c))throw new Error("The internal list is malformed.");var d=p(c)?c.startTime+c.duration:v(c),f=p(c)?c.values[c.values.length-1]:c.value,_=u(s)?y(e,d,f,s):b(e,d,f,s),x=u(s)?i(_,e,this._currenTime):o(_,e,this._currenTime);this._automationEvents.push(x)}void 0!==c&&w(c)&&this._automationEvents.push(r(this.getValue(e),e)),void 0!==c&&p(c)&&c.startTime+c.duration>e&&(this._automationEvents[this._automationEvents.length-1]=a(new Float32Array([6,7]),c.startTime,e-c.startTime))}}else{var T=this._automationEvents.findIndex((function(t){return v(t)>e})),O=-1===T?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[T-1];if(void 0!==O&&p(O)&&v(O)+O.duration>e)return!1;var S=u(t)?i(t.value,t.endTime,this._currenTime):h(t)?o(t.value,e,this._currenTime):t;if(-1===T)this._automationEvents.push(S);else{if(p(t)&&e+t.duration>v(this._automationEvents[T]))return!1;this._automationEvents.splice(T,0,S)}}return!0}},{key:"flush",value:function(t){var e=this._automationEvents.findIndex((function(e){return v(e)>t}));if(e>1){var n=this._automationEvents.slice(e-1),s=n[0];w(s)&&n.unshift(r(f(this._automationEvents,e-2,s.startTime,this._defaultValue),s.startTime)),this._automationEvents=n}}},{key:"getValue",value:function(t){if(0===this._automationEvents.length)return this._defaultValue;var n=this._automationEvents[this._automationEvents.length-1],s=this._automationEvents.findIndex((function(e){return v(e)>t})),i=this._automationEvents[s],o=v(n)<=t?n:this._automationEvents[s-1];if(void 0!==o&&w(o)&&(void 0===i||!l(i)||i.insertTime>t))return c(t,f(this._automationEvents,s-2,o.startTime,this._defaultValue),o);if(void 0!==o&&d(o)&&(void 0===i||!l(i)))return o.value;if(void 0!==o&&p(o)&&(void 0===i||!l(i)||o.startTime+o.duration>t))return ts.h.has(t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.i,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(20);const o=t=>{if(!s.a.has(t))throw new Error("The AudioNode is not stored.");s.a.delete(t),Object(i.a)(t).forEach(t=>t(!1))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(24);const i=t=>Object(s.a)(t[0])},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=t=>s.a.has(t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"context"in t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"context"in t},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.d,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.e,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s={value:t};return Object.defineProperties(n,{currentTarget:s,target:s}),"function"==typeof e?e.call(t,n):e.handleEvent.call(t,n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(15);const i=t=>{var e;t.getChannelData=(e=t.getChannelData,n=>{try{return e.call(t,n)}catch(t){if(12===t.code)throw Object(s.a)();throw t}})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.start=(e=t.start,(n=0,s=0,i)=>{if("number"==typeof i&&i<0||s<0||n<0)throw new RangeError("The parameters can't be negative.");e.call(t,n,s,i)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.stop=(e=t.stop,(n=0)=>{if(n<0)throw new RangeError("The parameter can't be negative.");e.call(t,n)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(12);const i=(t,e,n,i)=>{if(Object(s.a)(e)){const s=e.inputs[i];return t.connect(s,n,0),[s,n,0]}return t.connect(e,n,i),[e,n,i]}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(12);const i=(t,e,n,i)=>{Object(s.a)(e)?t.disconnect(e.inputs[i],n,0):t.disconnect(e,n,i)}},function(t,e,n){"use strict";function s(t,e,n,s,i){if("function"==typeof t.copyFromChannel)0===e[n].byteLength&&(e[n]=new Float32Array(128)),t.copyFromChannel(e[n],s,i);else{const o=t.getChannelData(s);if(0===e[n].byteLength)e[n]=o.slice(i,i+128);else{const t=new Float32Array(o.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[n].set(t)}}}n.d(e,"a",(function(){return s}))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>{const n=[];for(let s=0;s{try{return new DOMException("","InvalidAccessError")}catch(t){return t.code=15,t.name="InvalidAccessError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>{let i=Object.getPrototypeOf(t);for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:o,set:r}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:n(o),set:s(r)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>void 0===t||"number"==typeof t||"string"==typeof t&&("balanced"===t||"interactive"===t||"playback"===t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));class s{constructor(t){this._map=new Map(t)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(t,e=null){return this._map.forEach((n,s)=>t.call(e,n,s,this))}get(t){return this._map.get(t)}has(t){return this._map.has(t)}keys(){return this._map.keys()}values(){return this._map.values()}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i)=>{"function"==typeof t.copyToChannel?0!==e[n].byteLength&&t.copyToChannel(e[n],s,i):0!==e[n].byteLength&&t.getChannelData(s).set(e[n],i)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a,c,u,h)=>{const l=u.length;let d=a;for(let a=0;anull===t?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e)))))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","UnknownError")}catch(t){return t.name="UnknownError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{if(null===t)return!1;const e=t.length;return e%2!=0?0!==t[Math.floor(e/2)]:t[e/2-1]+t[e/2]!==0}},function(t,e,n){"use strict";n(47),n(48),n(49),n(50),n(51),n(52),n(53),n(54),n(55),n(56),n(57),n(58),n(59),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(67),n(68),n(69),n(70),n(71),n(72),n(73),n(74),n(75),n(76),n(77),n(78),n(79),n(80),n(81),n(82),n(83),n(84),n(85),n(86),n(87),n(88),n(89),n(90),n(91),n(92),n(93),n(94),n(95),n(96),n(97),n(98),n(99),n(100),n(101),n(102),n(103),n(104),n(105),n(106),n(107),n(108),n(109),n(110),n(111),n(112),n(113),n(114),n(115),n(116),n(117),n(118),n(119),n(120),n(121),n(122),n(123),n(124),n(125),n(126),n(127),n(128),n(129)},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";n(131),n(132),n(133),n(134),n(135),n(136),n(137),n(138),n(139),n(140),n(141),n(142),n(143),n(144),n(145),n(146),n(147),n(148),n(149),n(150),n(151),n(152),n(153),n(154),n(155),n(156),n(157),n(158),n(159),n(160),n(161),n(162),n(163),n(164),n(165),n(166),n(167),n(168),n(169),n(170),n(171),n(172),n(173),n(174),n(175),n(176),n(177),n(178),n(179),n(180),n(181),n(182),n(183),n(184),n(185),n(186),n(187),n(188),n(189),n(190),n(191),n(192),n(193),n(194),n(195),n(196),n(197),n(198),n(199),n(200),n(201),n(202),n(203),n(204),n(205),n(206),n(207),n(208),n(209),n(210),n(211),n(212),n(213),n(214),n(215),n(216),n(217),n(218),n(219),n(220),n(221),n(222),n(223),n(224),n(225),n(226),n(227),n(228),n(229),n(230),n(231),n(232),n(233),n(234),n(235),n(236),n(237),n(238),n(239),n(240),n(241),n(242),n(243),n(244),n(245),n(246),n(247),n(248),n(249),n(250),n(251),n(252),n(253),n(254),n(255),n(256),n(257),n(258),n(259),n(260),n(261),n(262),n(263),n(264),n(265),n(266),n(267),n(268),n(269),n(270),n(271),n(272),n(273),n(274),n(275),n(276),n(277),n(278),n(279),n(280),n(281),n(282),n(283),n(284),n(285),n(286),n(287),n(288),n(289),n(290),n(291),n(292),n(293),n(294),n(295),n(296),n(297),n(298),n(299),n(300),n(301),n(302),n(303),n(304),n(305),n(306),n(307),n(308),n(309),n(310),n(311),n(312),n(313),n(314),n(315),n(316),n(317),n(318),n(319),n(320),n(321),n(322),n(323),n(324),n(325),n(326),n(327),n(328),n(329),n(330),n(331),n(332),n(333),n(334),n(335),n(336),n(337),n(338),n(339),n(340),n(341),n(342),n(343),n(344),n(345),n(346),n(347),n(348),n(349),n(350),n(351),n(352),n(353),n(354),n(355),n(356),n(357),n(358),n(359),n(360),n(361),n(362),n(363),n(364),n(365),n(366),n(367),n(368),n(369),n(370),n(371),n(372),n(373),n(374),n(375),n(376),n(377),n(378),n(379),n(380),n(381),n(382),n(383),n(384),n(385),n(386),n(387),n(388),n(389),n(390),n(391),n(392),n(393),n(394),n(395),n(396),n(397),n(398),n(399),n(400),n(401),n(402),n(403),n(404),n(405),n(406),n(407),n(408),n(409),n(410),n(411),n(412),n(413),n(414),n(415),n(416),n(417),n(418),n(419),n(420),n(421),n(422),n(423),n(424),n(425),n(426),n(427),n(428),n(429),n(430),n(431),n(432),n(433),n(434),n(435),n(436),n(437),n(438),n(439),n(440),n(441),n(442),n(443),n(444),n(445),n(446),n(447),n(448),n(449),n(450),n(451),n(452),n(453),n(454),n(455),n(456),n(457),n(458),n(459),n(460),n(461),n(462),n(463),n(464),n(465),n(466),n(467),n(468),n(469),n(470),n(471),n(472),n(473),n(474),n(475),n(476),n(477),n(478),n(479),n(480),n(481),n(482),n(483),n(484),n(485),n(486),n(487),n(488),n(489),n(490),n(491),n(492),n(493),n(494),n(495),n(496),n(497),n(498),n(499),n(500),n(501),n(502),n(503),n(504),n(505),n(506),n(507),n(508),n(509),n(510),n(511),n(512),n(513),n(514)},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","AbortError")}catch(t){return t.code=20,t.name="AbortError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s)=>{const i=[];for(let t=0;t(e,n)=>{t.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.connect(s).connect(s.context.destination);const i=()=>{n.removeEventListener("ended",i),n.disconnect(s),s.disconnect()};n.addEventListener("ended",i)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{t(e).add(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},i=(t,e,n,i,o,r)=>class extends t{constructor(t,n=s){const a=o(t),c={...s,...n},u=i(a,c);super(t,!1,u,r(a)?e():null),this._nativeAnalyserNode=u}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(t){this._nativeAnalyserNode.fftSize=t}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(t){const e=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=t,!(t>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=e,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(t){const e=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=t,!(this._nativeAnalyserNode.maxDecibels>t))throw this._nativeAnalyserNode.minDecibels=e,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(t){this._nativeAnalyserNode.smoothingTimeConstant=t}getByteFrequencyData(t){this._nativeAnalyserNode.getByteFrequencyData(t)}getByteTimeDomainData(t){this._nativeAnalyserNode.getByteTimeDomainData(t)}getFloatFrequencyData(t){this._nativeAnalyserNode.getFloatFrequencyData(t)}getFloatTimeDomainData(t){this._nativeAnalyserNode.getFloatTimeDomainData(t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,fftSize:c.fftSize,maxDecibels:c.maxDecibels,minDecibels:c.minDecibels,smoothingTimeConstant:c.smoothingTimeConstant};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(32),i=n(29);const o={numberOfChannels:1},r=(t,e,n,r,a,c,u,h)=>{let l=null;return class d{constructor(d){if(null===a)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:p,numberOfChannels:f,sampleRate:_}={...o,...d};null===l&&(l=new a(1,1,44100));const m=null!==r&&e(c,c)?new r({length:p,numberOfChannels:f,sampleRate:_}):l.createBuffer(f,p,_);if(0===m.numberOfChannels)throw n();return"function"!=typeof m.copyFromChannel?(u(m),Object(i.a)(m)):e(s.a,()=>Object(s.a)(m))||h(m),t.add(m),m}static[Symbol.hasInstance](e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===d.prototype||t.has(e)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(2),i=n(17),o=n(21);const r={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},a=(t,e,n,a,c,u,h,l)=>class extends t{constructor(t,i=r){const o=u(t),a={...r,...i},l=c(o,a),d=h(o),p=d?e():null;super(t,!1,l,p),this._audioBufferSourceNodeRenderer=p,this._isBufferNullified=!1,this._isBufferSet=null!==i.buffer&&void 0!==i.buffer,this._nativeAudioBufferSourceNode=l,this._onended=null,this._playbackRate=n(this,d,l.playbackRate,s.b,s.a)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(t){try{this._nativeAudioBufferSourceNode.buffer=t}catch(e){if(null!==t||17!==e.code)throw e;if(null!==this._nativeAudioBufferSourceNode.buffer){const t=this._nativeAudioBufferSourceNode.buffer,e=t.numberOfChannels;for(let n=0;n{this._nativeAudioBufferSourceNode.removeEventListener("ended",t),setTimeout(()=>Object(o.a)(this),1e3)};this._nativeAudioBufferSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeAudioBufferSourceNode.stop(t),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null;return{set start(t){a=t},set stop(t){c=t},render(u,h,l){const d=r.get(h);return void 0!==d?Promise.resolve(d):(async(u,h,l)=>{let d=n(u);const p=Object(s.a)(d,h);if(!p){const t={buffer:d.buffer,channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,loop:d.loop,loopEnd:d.loopEnd,loopStart:d.loopStart,playbackRate:d.playbackRate.value};d=e(h,t),null!==a&&d.start(...a),null!==c&&d.stop(c)}return r.set(h,d),p?await t(h,u.playbackRate,d.playbackRate,l):await i(h,u.playbackRate,d.playbackRate,l),await o(u,h,d,l),d})(u,h,l)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(39);const i=(t,e,n,i,o,r,a,c,u)=>class extends t{constructor(t={}){if(null===u)throw new Error("Missing the native AudioContext constructor.");const e=new u(t);if(null===e)throw i();if(!Object(s.a)(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&e.sampleRate!==t.sampleRate)throw n();super(e,2);const{latencyHint:o}=t,{sampleRate:r}=e;if(this._baseLatency="number"==typeof e.baseLatency?e.baseLatency:"balanced"===o?512/r:"interactive"===o||void 0===o?256/r:"playback"===o?1024/r:128*Math.max(2,Math.min(128,Math.round(o*r/128)))/r,this._nativeAudioContext=e,this._state=null,"running"===e.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw e()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close())}createMediaElementSource(t){return new o(this,{mediaElement:t})}createMediaStreamDestination(){return new r(this)}createMediaStreamSource(t){return new a(this,{mediaStream:t})}createMediaStreamTrackSource(t){return new c(this,{mediaStreamTrack:t})}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(t=>{if(void 0===t||15===t.code)throw e();throw t})}suspend(){return this._nativeAudioContext.suspend().catch(t=>{if(void 0===t)throw e();throw t})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a)=>class extends t{constructor(t,n){const s=o(t),c=r(s),u=i(s,n,c);super(t,!1,u,c?e(a):null),this._isNodeOfNativeOfflineAudioContext=c,this._nativeAudioDestinationNode=u}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();if(t>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=t}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();this._nativeAudioDestinationNode.channelCountMode=t}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{let e=null;return{render:(n,s,i)=>(null===e&&(e=(async(e,n,s)=>{const i=n.destination;return await t(e,n,i,s),i})(n,s,i)),e)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(2);const i=(t,e,n,i,o)=>(r,a)=>{const c=a.listener,{forwardX:u,forwardY:h,forwardZ:l,positionX:d,positionY:p,positionZ:f,upX:_,upY:m,upZ:g}=void 0===c.forwardX?(()=>{const u=e(a,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),h=o(a),l=i(a,256,9,0),d=(e,i)=>{const o=n(a,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:i});return o.connect(u,0,e),o.start(),Object.defineProperty(o.offset,"defaultValue",{get:()=>i}),t({context:r},h,o.offset,s.b,s.a)};let p=[0,0,-1,0,1,0],f=[0,0,0];return l.onaudioprocess=({inputBuffer:t})=>{const e=[t.getChannelData(0)[0],t.getChannelData(1)[0],t.getChannelData(2)[0],t.getChannelData(3)[0],t.getChannelData(4)[0],t.getChannelData(5)[0]];e.some((t,e)=>t!==p[e])&&(c.setOrientation(...e),p=e);const n=[t.getChannelData(6)[0],t.getChannelData(7)[0],t.getChannelData(8)[0]];n.some((t,e)=>t!==f[e])&&(c.setPosition(...n),f=n)},u.connect(l),{forwardX:d(0,0),forwardY:d(1,0),forwardZ:d(2,-1),positionX:d(6,0),positionY:d(7,0),positionZ:d(8,0),upX:d(3,0),upY:d(4,1),upZ:d(5,0)}})():c;return{get forwardX(){return u},get forwardY(){return h},get forwardZ(){return l},get positionX(){return d},get positionY(){return p},get positionZ(){return f},get upX(){return _},get upY(){return m},get upZ(){return g}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(18);const i=(t,e,n,i,o,r,a,c,u,h,l,d)=>(p,f,_,m=null,g=null)=>{const v=new s.AutomationEventList(_.defaultValue),y=f?i(v):null,b={get defaultValue(){return _.defaultValue},get maxValue(){return null===m?_.maxValue:m},get minValue(){return null===g?_.minValue:g},get value(){return _.value},set value(t){_.value=t,b.setValueAtTime(t,p.context.currentTime)},cancelAndHoldAtTime(t){if("function"==typeof _.cancelAndHoldAtTime)null===y&&v.flush(p.context.currentTime),v.add(o(t)),_.cancelAndHoldAtTime(t);else{const e=Array.from(v).pop();null===y&&v.flush(p.context.currentTime),v.add(o(t));const n=Array.from(v).pop();_.cancelScheduledValues(t),e!==n&&void 0!==n&&("exponentialRampToValue"===n.type?_.exponentialRampToValueAtTime(n.value,n.endTime):"linearRampToValue"===n.type?_.linearRampToValueAtTime(n.value,n.endTime):"setValue"===n.type?_.setValueAtTime(n.value,n.startTime):"setValueCurve"===n.type&&_.setValueCurveAtTime(n.values,n.startTime,n.duration))}return b},cancelScheduledValues:t=>(null===y&&v.flush(p.context.currentTime),v.add(r(t)),_.cancelScheduledValues(t),b),exponentialRampToValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(a(t,e)),_.exponentialRampToValueAtTime(t,e),b),linearRampToValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(c(t,e)),_.linearRampToValueAtTime(t,e),b),setTargetAtTime:(t,e,n)=>(null===y&&v.flush(p.context.currentTime),v.add(u(t,e,n)),_.setTargetAtTime(t,e,n),b),setValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(h(t,e)),_.setValueAtTime(t,e),b),setValueCurveAtTime(t,e,n){if(null!==d&&"webkitAudioContext"===d.name){const s=e+n,i=p.context.sampleRate,o=Math.ceil(e*i),r=Math.floor(s*i),a=r-o,c=new Float32Array(a);for(let s=0;s({replay(e){for(const n of t)if("exponentialRampToValue"===n.type){const{endTime:t,value:s}=n;e.exponentialRampToValueAtTime(s,t)}else if("linearRampToValue"===n.type){const{endTime:t,value:s}=n;e.linearRampToValueAtTime(s,t)}else if("setTarget"===n.type){const{startTime:t,target:s,timeConstant:i}=n;e.setTargetAtTime(s,t,i)}else if("setValue"===n.type){const{startTime:t,value:s}=n;e.setValueAtTime(s,t)}else{if("setValueCurve"!==n.type)throw new Error("Can't apply an unknown automation.");{const{duration:t,startTime:s,values:i}=n;e.setValueCurveAtTime(i,s,t)}}}})},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(0),i=n(40);const o={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:void 0,parameterData:{},processorOptions:{}},r=t=>{const e=[];for(let n=0;nclass extends e{constructor(e,d,p=o){const f=u(e),_=h(f),m=(t=>({...t,outputChannelCount:void 0!==t.outputChannelCount?t.outputChannelCount:1===t.numberOfInputs&&1===t.numberOfOutputs?[t.channelCount]:r(t.numberOfOutputs)}))({...o,...p}),g=s.j.get(f),v=void 0===g?void 0:g.get(d),y=c(f,_?null:e.baseLatency,l,d,v,m);super(e,!0,y,_?a(d,m,v):null);const b=[];y.parameters.forEach((t,e)=>{const s=n(this,_,t);b.push([e,s])}),this._nativeAudioWorkletNode=y,this._onprocessorerror=null,this._parameters=new i.a(b),_&&t(f,this)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(t){const e="function"==typeof t?d(this,t):null;this._nativeAudioWorkletNode.onprocessorerror=e;const n=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=null!==n&&n===e?t:n}get parameters(){return null===this._parameters?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a,c,u,h,l,d,p,f,_,m,g,v,y)=>class extends f{constructor(e,n){super(e,n),this._nativeContext=e,this._audioWorklet=void 0===t?void 0:{addModule:(e,n)=>t(this,e,n)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(t,e,s){return new n({length:e,numberOfChannels:t,sampleRate:s})}createBufferSource(){return new s(this)}createChannelMerger(t=6){return new o(this,{numberOfInputs:t})}createChannelSplitter(t=6){return new r(this,{numberOfOutputs:t})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(t=1){return new h(this,{maxDelayTime:t})}createDynamicsCompressor(){return new l(this)}createGain(){return new d(this)}createIIRFilter(t,e){return new p(this,{feedback:e,feedforward:t})}createOscillator(){return new _(this)}createPanner(){return new m(this)}createPeriodicWave(t,e,n={disableNormalization:!1}){return new g(this,{...n,imag:e,real:t})}createStereoPanner(){return new v(this)}createWaveShaper(){return new y(this)}decodeAudioData(t,e,n){return u(this._nativeContext,t).then(t=>("function"==typeof e&&e(t),t)).catch(t=>{throw"function"==typeof n&&n(t),t})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},o=(t,e,n,o,r,a,c)=>class extends t{constructor(t,o=i){const u=a(t),h={...i,...o},l=r(u,h),d=c(u);super(t,!1,l,d?n():null),this._Q=e(this,d,l.Q,s.b,s.a),this._detune=e(this,d,l.detune,1200*Math.log2(s.b),-1200*Math.log2(s.b)),this._frequency=e(this,d,l.frequency,t.sampleRate/2,0),this._gain=e(this,d,l.gain,40*Math.log10(s.b),s.a),this._nativeBiquadFilterNode=l}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(t){this._nativeBiquadFilterNode.type=t}getFrequencyResponse(t,e,n){if(this._nativeBiquadFilterNode.getFrequencyResponse(t,e,n),t.length!==e.length||e.length!==n.length)throw o()}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={Q:h.Q.value,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,detune:h.detune.value,frequency:h.frequency.value,gain:h.gain.value,type:h.type};h=e(c,t)}return r.set(c,h),l?(await t(c,a.Q,h.Q,u),await t(c,a.detune,h.detune,u),await t(c,a.frequency,h.frequency,u),await t(c,a.gain,h.gain,u)):(await i(c,a.Q,h.Q,u),await i(c,a.detune,h.detune,u),await i(c,a.frequency,h.frequency,u),await i(c,a.gain,h.gain,u)),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s)=>{const i=e.get(n);if(void 0!==i)return i;const o=t.get(n);if(void 0!==o)return o;try{const i=s();return i instanceof Promise?(t.set(n,i),i.catch(()=>!1).then(s=>(t.delete(n),e.set(n,s),s))):(e.set(n,i),i)}catch{return e.set(n,!1),!1}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c={...s,...r};super(t,!1,n(a,c),o(a)?e():null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,numberOfInputs:c.numberOfInputs};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c=(t=>({...t,channelCount:t.numberOfOutputs}))({...s,...r});super(t,!1,n(a,c),o(a)?e():null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,numberOfOutputs:c.numberOfOutputs};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s,i)=>t(n,e,s,i)},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(25);const i=t=>(e,n,i=0,o=0)=>{const r=e[i];if(void 0===r)throw t();return Object(s.a)(n)?r.connect(n,0,o):r.connect(n,0)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e),i=e.createBuffer(1,2,e.sampleRate);return s.buffer=i,s.loop=!0,s.connect(n),s.start(),()=>{s.stop(),s.disconnect(n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(2),i=n(17),o=n(21);const r={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},a=(t,e,n,a,c,u,h)=>class extends t{constructor(t,i=r){const o=c(t),h={...r,...i},l=a(o,h),d=u(o),p=d?n():null;super(t,!1,l,p),this._constantSourceNodeRenderer=p,this._nativeConstantSourceNode=l,this._offset=e(this,d,l.offset,s.b,s.a),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(t){const e="function"==typeof t?h(this,t):null;this._nativeConstantSourceNode.onended=e;const n=this._nativeConstantSourceNode.onended;this._onended=null!==n&&n===e?t:n}start(t=0){if(this._nativeConstantSourceNode.start(t),null!==this._constantSourceNodeRenderer)this._constantSourceNodeRenderer.start=t;else{Object(i.a)(this);const t=()=>{this._nativeConstantSourceNode.removeEventListener("ended",t),setTimeout(()=>Object(o.a)(this),1e3)};this._nativeConstantSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeConstantSourceNode.stop(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null;return{set start(t){a=t},set stop(t){c=t},render(u,h,l){const d=r.get(h);return void 0!==d?Promise.resolve(d):(async(u,h,l)=>{let d=n(u);const p=Object(s.a)(d,h);if(!p){const t={channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,offset:d.offset.value};d=e(h,t),null!==a&&d.start(a),null!==c&&d.stop(c)}return r.set(h,d),p?await t(h,u.offset,d.offset,l):await i(h,u.offset,d.offset,l),await o(u,h,d,l),d})(u,h,l)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>(t[0]=e,t[0])},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c={...s,...r},u=n(a,c);super(t,!1,u,o(a)?e():null),this._isBufferNullified=!1,this._nativeConvolverNode=u}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(t){if(this._nativeConvolverNode.buffer=t,null===t&&null!==this._nativeConvolverNode.buffer){const t=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=t.createBuffer(1,1,t.sampleRate),this._isBufferNullified=!0}else this._isBufferNullified=!1}get normalize(){return this._nativeConvolverNode.normalize}set normalize(t){this._nativeConvolverNode.normalize=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n)=>()=>{const o=new WeakMap;return{render(r,a,c){const u=o.get(a);return void 0!==u?Promise.resolve(u):(async(r,a,c)=>{let u=e(r);if(!Object(i.a)(u,a)){const e={buffer:u.buffer,channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,disableNormalization:!u.normalize};u=t(a,e)}return o.set(a,u),Object(s.a)(u)?await n(r,a,u.inputs[0],c):await n(r,a,u,c),u})(r,a,c)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{if(null===e)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(n,s,i)}catch(e){if("IndexSizeError"===e.name||"SyntaxError"===e.name)throw t();throw e}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","DataCloneError")}catch(t){return t.code=25,t.name="DataCloneError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(22);const i=(t,e,n,i,o,r,a,c)=>(u,h)=>{const l=e.get(u);if(void 0===l)throw new Error("Missing the expected cycle count.");const d=r(u.context),p=c(d);if(l===h){if(e.delete(u),!p&&a(u)){const e=i(u),{outputs:r}=n(u);for(const n of r)if(Object(s.a)(n)){const s=i(n[0]);t(e,s,n[1],n[2])}else{const t=o(n[0]);e.connect(t,n[1])}}}else e.set(u,l-h)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},i=(t,e,n,i,o,r)=>class extends t{constructor(t,a=s){const c=o(t),u={...s,...a},h=i(c,u),l=r(c);super(t,!1,h,l?n(u.maxDelayTime):null),this._delayTime=e(this,l,h.delayTime,u.maxDelayTime,0)}get delayTime(){return this._delayTime}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>r=>{const a=new WeakMap;return{render(c,u,h){const l=a.get(u);return void 0!==l?Promise.resolve(l):(async(c,u,h)=>{let l=n(c);const d=Object(s.a)(l,u);if(!d){const t={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,delayTime:l.delayTime.value,maxDelayTime:r};l=e(u,t)}return a.set(u,l),d?await t(u,c.delayTime,l.delayTime,h):await i(u,c.delayTime,l.delayTime,h),await o(c,u,l,h),l})(c,u,h)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{t(e).delete(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(25);const i=(t,e,n)=>{const s=e[n];if(void 0===s)throw t();return s},o=t=>(e,n,o,r=0)=>void 0===n?e.forEach(t=>t.disconnect()):"number"==typeof n?i(t,e,n).disconnect():Object(s.a)(n)?void 0===o?e.forEach(t=>t.disconnect(n)):void 0===r?i(t,e,o).disconnect(n,0):i(t,e,o).disconnect(n,0,r):void 0===o?e.forEach(t=>t.disconnect(n)):i(t,e,o).disconnect(n,0)},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},i=(t,e,n,i,o,r,a)=>class extends t{constructor(t,o=s){const c=r(t),u={...s,...o},h=i(c,u),l=a(c);super(t,!1,h,l?n():null),this._attack=e(this,l,h.attack,1,0),this._knee=e(this,l,h.knee,40,0),this._nativeDynamicsCompressorNode=h,this._ratio=e(this,l,h.ratio,20,1),this._release=e(this,l,h.release,1,0),this._threshold=e(this,l,h.threshold,0,-100)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(t){const e=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=t,t>2)throw this._nativeDynamicsCompressorNode.channelCount=e,o()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(t){const e=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=t,"max"===t)throw this._nativeDynamicsCompressorNode.channelCountMode=e,o()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return"number"==typeof this._nativeDynamicsCompressorNode.reduction.value?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={attack:h.attack.value,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,knee:h.knee.value,ratio:h.ratio.value,release:h.release.value,threshold:h.threshold.value};h=e(c,t)}return r.set(c,h),l?(await t(c,a.attack,h.attack,u),await t(c,a.knee,h.knee,u),await t(c,a.ratio,h.ratio,u),await t(c,a.release,h.release,u),await t(c,a.threshold,h.threshold,u)):(await i(c,a.attack,h.attack,u),await i(c,a.knee,h.knee,u),await i(c,a.ratio,h.ratio,u),await i(c,a.release,h.release,u),await i(c,a.threshold,h.threshold,u)),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","EncodingError")}catch(t){return t.code=0,t.name="EncodingError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>new Promise((n,s)=>{if(null===t)return void s(new SyntaxError);const i=t.document.head;if(null===i)s(new SyntaxError);else{const o=t.document.createElement("script"),r=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(r),c=t.onerror,u=()=>{t.onerror=c,URL.revokeObjectURL(a)};t.onerror=(e,n,i,o,r)=>n===a||n===t.location.href&&1===i&&1===o?(u(),s(r),!1):null!==c?c(e,n,i,o,r):void 0,o.onerror=()=>{u(),s(new SyntaxError)},o.onload=()=>{u(),n()},o.src=a,o.type="module",i.appendChild(o)}})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(e,n,s){if(null!==n){let i=this._listeners.get(n);void 0===i&&(i=t(this,n),"function"==typeof n&&this._listeners.set(n,i)),this._nativeEventTarget.addEventListener(e,i,s)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,e,n){const s=null===e?void 0:this._listeners.get(e);this._nativeEventTarget.removeEventListener(t,void 0===s?null:s,n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s)=>{Object.defineProperties(t,{currentFrame:{configurable:!0,get:()=>Math.round(e*n)},currentTime:{configurable:!0,get:()=>e}});try{return s()}finally{null!==t&&(delete t.currentFrame,delete t.currentTime)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>async e=>{try{const t=await fetch(e);if(t.ok)return t.text()}catch{}throw t()}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},o=(t,e,n,o,r,a)=>class extends t{constructor(t,c=i){const u=r(t),h={...i,...c},l=o(u,h),d=a(u);super(t,!1,l,d?n():null),this._gain=e(this,d,l.gain,s.b,s.a)}get gain(){return this._gain}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,gain:h.gain.value};h=e(c,t)}return r.set(c,h),l?await t(c,a.gain,h.gain,u):await i(c,a.gain,h.gain,u),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return n.renderer}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return n.renderer}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=(t,e,n)=>i=>{if("closed"===i.state&&null!==e&&"webkitAudioContext"!==e.name){if(!t(i)){const t=s.f.get(i);if(void 0!==t)return t;const n=new e;return s.f.set(i,n),n}{const t=s.f.get(i);if(void 0!==t)return t;if(null!==n){const t=new n(1,1,44100);return s.f.set(i,t),t}}}return null}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(7);const i=t=>e=>{const n=t.get(e);if(void 0===n)throw Object(s.a)();return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t.get(e);if(void 0===n)throw new Error("The context has no set of AudioWorkletNodes.");return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(42),i=n(3);const o=(t,e,n,o,r,a)=>(c,u)=>{const h=new WeakMap;let l=null;const d=async(d,p,f)=>{let _=null,m=n(d);const g=Object(i.a)(m,p);if(void 0===p.createIIRFilter?_=t(p):g||(m=e(p,t=>t.createIIRFilter(u,c))),h.set(p,null===_?m:_),null!==_){if(null===l){if(null===o)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new o(d.context.destination.channelCount,d.context.length,p.sampleRate);l=(async()=>(await r(d,t,t.destination,f),((t,e,n,i)=>{const o=n.length,r=i.length,a=Math.min(o,r);if(1!==n[0]){for(let t=0;ta=>(c,u)=>{const h=t.get(c);if(void 0===h){if(!a&&r(c)){const t=i(c),{outputs:r}=n(c);for(const n of r)if(Object(s.a)(n)){const s=i(n[0]);e(t,s,n[1],n[2])}else{const e=o(n[0]);t.disconnect(e,n[1])}}t.set(c,u)}else t.set(c,h+u)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t.has(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t.has(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&e instanceof t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&"function"==typeof t.AudioNode&&e instanceof t.AudioNode},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&"function"==typeof t.AudioParam&&e instanceof t.AudioParam},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&e instanceof t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null!==t&&t.isSecureContext},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=async(t,e,n,s,i,o,r,a,c,u,h,l,d,p)=>{if(t(e,e)&&t(n,n)&&t(i,i)&&t(o,o)&&t(a,a)&&t(c,c)&&t(u,u)&&t(h,h)&&t(l,l)){return(await Promise.all([t(s,s),t(r,r),t(d,d),t(p,p)])).every(t=>t)}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>class extends t{constructor(t,i){const o=n(t),r=e(o,i);if(s(o))throw TypeError();super(t,!0,r,null),this._mediaElement=i.mediaElement,this._nativeMediaElementAudioSourceNode=r}get mediaElement(){return void 0===this._nativeMediaElementAudioSourceNode.mediaElement?this._mediaElement:this._nativeMediaElementAudioSourceNode.mediaElement}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},i=(t,e,n,i)=>class extends t{constructor(t,o=s){const r=n(t);if(i(r))throw new TypeError;const a={...s,...o},c=e(r,a);super(t,!1,c,null),this._nativeMediaStreamAudioDestinationNode=c}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>class extends t{constructor(t,i){const o=n(t),r=e(o,i);if(s(o))throw new TypeError;super(t,!0,r,null),this._nativeMediaStreamAudioSourceNode=r}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>class extends t{constructor(t,s){const i=n(t);super(t,!0,e(i,s),null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(39);const i=(t,e,n,i,o)=>class extends i{constructor(t={}){if(null===o)throw new Error("Missing the native AudioContext constructor.");const i=new o(t);if(null===i)throw n();if(!Object(s.a)(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&i.sampleRate!==t.sampleRate)throw e();super(i,2);const{latencyHint:r}=t,{sampleRate:a}=i;if(this._baseLatency="number"==typeof i.baseLatency?i.baseLatency:"balanced"===r?512/a:"interactive"===r||void 0===r?256/a:"playback"===r?1024/a:128*Math.max(2,Math.min(128,Math.round(r*a/128)))/a,this._nativeAudioContext=i,this._state=null,"running"===i.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),i.removeEventListener("statechange",t)};i.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw t()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close())}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(e=>{if(void 0===e||15===e.code)throw t();throw e})}suspend(){return this._nativeAudioContext.suspend().catch(e=>{if(void 0===e)throw t();throw e})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=(t,e,n,i,o,r)=>class extends n{constructor(n,r){super(n),this._nativeContext=n,s.g.set(this,n);const a=n.sampleRate;Object.defineProperty(n,"sampleRate",{get:()=>a}),i(n)&&o.set(n,new Set),this._destination=new t(this,r),this._listener=e(this,n),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(t){const e="function"==typeof t?r(this,t):null;this._nativeContext.onstatechange=e;const n=this._nativeContext.onstatechange;this._onstatechange=null!==n&&n===e?t:n}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(14);const i={numberOfChannels:1},o=(t,e,n,o,r)=>class extends o{constructor(e){const{length:o,numberOfChannels:r,sampleRate:a}={...i,...e},c=n(r,o,a);t(s.a,()=>Object(s.a)(c))||c.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(c.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(c,r),this._length=o,this._nativeOfflineAudioContext=c,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(e()):(this._state="running",r(this.destination,this._nativeOfflineAudioContext).then(t=>(this._state=null,t)).catch(t=>{throw this._state=null,t}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{const o=new Set;var r,a;return n.connect=(r=n.connect,(i,a=0,c=0)=>{const u=0===o.size;if(e(i))return r.call(n,i,a,c),t(o,[i,a,c],t=>t[0]===i&&t[1]===a&&t[2]===c,!0),u&&s(),i;r.call(n,i,a),t(o,[i,a],t=>t[0]===i&&t[1]===a,!0),u&&s()}),n.disconnect=(a=n.disconnect,(t,s,r)=>{const c=o.size>0;if(void 0===t)a.apply(n),o.clear();else if("number"==typeof t){a.call(n,t);for(const e of o)e[1]===t&&o.delete(e)}else{e(t)?a.call(n,t,s,r):a.call(n,t,s);for(const e of o)e[0]!==t||void 0!==s&&e[1]!==s||void 0!==r&&e[2]!==r||o.delete(e)}const u=0===o.size;c&&u&&i()}),n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioBuffer")?t.AudioBuffer:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioContext")?t.AudioContext:t.hasOwnProperty("webkitAudioContext")?t.webkitAudioContext:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{const o=n.destination;if(o.channelCount!==s)try{o.channelCount=s}catch{}i&&"explicit"!==o.channelCountMode&&(o.channelCountMode="explicit"),0===o.maxChannelCount&&Object.defineProperty(o,"maxChannelCount",{value:s});const r=t(n,{channelCount:s,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,gain:1});return e(r,"channelCount",t=>()=>t.call(r),t=>e=>{t.call(r,e);try{o.channelCount=e}catch(t){if(e>o.maxChannelCount)throw t}}),e(r,"channelCountMode",t=>()=>t.call(r),t=>e=>{t.call(r,e),o.channelCountMode=e}),e(r,"channelInterpretation",t=>()=>t.call(r),t=>e=>{t.call(r,e),o.channelInterpretation=e}),Object.defineProperty(r,"maxChannelCount",{get:()=>o.maxChannelCount}),r.connect(o),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e);return n(null!==s?s:e)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioWorkletNode")?t.AudioWorkletNode:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(5),i=n(4),o=n(1);const r=t=>(e,n)=>{const r=t(e,t=>t.createBiquadFilter());return Object(o.a)(r,n),Object(s.a)(r,n,"Q"),Object(s.a)(r,n,"detune"),Object(s.a)(r,n,"frequency"),Object(s.a)(r,n,"gain"),Object(i.a)(r,n,"type"),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i)=>{const o=t(n,t=>t.createChannelMerger(i.numberOfInputs));return 1!==o.channelCount&&"explicit"!==o.channelCountMode&&e(n,o),Object(s.a)(o,i),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(5),i=n(1),o=n(30),r=n(31);const a=(t,e,n,a,c,u)=>(h,l)=>{if(void 0===h.createConstantSource)return a(h,l);const d=n(h,t=>t.createConstantSource());return Object(i.a)(d,l),Object(s.a)(d,l,"offset"),e(c,()=>c(h))||Object(o.a)(d),e(u,()=>u(h))||Object(r.a)(d),t(h,d),d}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=(t,e,n,i)=>(o,{offset:r,...a})=>{const c=o.createBuffer(1,2,o.sampleRate),u=e(o),h=n(o,{...a,gain:r}),l=c.getChannelData(0);l[0]=1,l[1]=1,u.buffer=c,u.loop=!0;const d={get bufferSize(){},get channelCount(){return h.channelCount},set channelCount(t){h.channelCount=t},get channelCountMode(){return h.channelCountMode},set channelCountMode(t){h.channelCountMode=t},get channelInterpretation(){return h.channelInterpretation},set channelInterpretation(t){h.channelInterpretation=t},get context(){return h.context},get inputs(){return[]},get numberOfInputs(){return u.numberOfInputs},get numberOfOutputs(){return h.numberOfOutputs},get offset(){return h.gain},get onended(){return u.onended},set onended(t){u.onended=t},addEventListener:(...t)=>u.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>u.dispatchEvent(t[0]),removeEventListener:(...t)=>u.removeEventListener(t[0],t[1],t[2]),start(t=0){u.start.call(u,t)},stop(t=0){u.stop.call(u,t)}};return t(o,u),i(Object(s.a)(d,h),()=>u.connect(h),()=>u.disconnect(h))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(4),i=n(1);const o=(t,e,n,o)=>(r,a)=>{const c=t(r,t=>t.createConvolver());try{c.channelCount=1}catch(t){return e(r,a)}if(Object(i.a)(c,a),a.disableNormalization===c.normalize&&(c.normalize=!a.disableNormalization),Object(s.a)(c,a,"buffer"),a.channelCount>2)throw n();if(o(c,"channelCount",t=>()=>t.call(c),t=>e=>{if(e>2)throw n();return t.call(c,e)}),"max"===a.channelCountMode)throw n();return o(c,"channelCountMode",t=>()=>t.call(c),t=>e=>{if("max"===e)throw n();return t.call(c,e)}),c}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n)=>(o,{buffer:r,channelCount:a,channelCountMode:c,channelInterpretation:u,disableNormalization:h})=>{const l=t(o,t=>t.createConvolver());Object(s.a)(l,{channelCount:Math.max(a,2),channelCountMode:"max"===c?c:"clamped-max",channelInterpretation:u});const d=e(o,{channelCount:a,channelCountMode:c,channelInterpretation:u,gain:1}),p={get buffer(){return l.buffer},set buffer(t){l.buffer=t},get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){t>2&&(l.channelCount=t),d.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){"max"===t&&(l.channelCountMode=t),d.channelCountMode=t},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(t){l.channelInterpretation=t,d.channelInterpretation=t},get context(){return l.context},get inputs(){return[l]},get numberOfInputs(){return l.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get normalize(){return l.normalize},set normalize(t){l.normalize=t},addEventListener:(...t)=>l.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>l.dispatchEvent(t[0]),removeEventListener:(...t)=>l.removeEventListener(t[0],t[1],t[2])};h===p.normalize&&(p.normalize=!h),r!==p.buffer&&(p.buffer=r);return n(Object(i.a)(p,d),()=>l.connect(d),()=>l.disconnect(d))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=t=>(e,n)=>{const o=t(e,t=>t.createDelay(n.maxDelayTime));return Object(i.a)(o,n),Object(s.a)(o,n,"delayTime"),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=(t,e)=>(n,o)=>{const r=t(n,t=>t.createDynamicsCompressor());if(Object(i.a)(r,o),o.channelCount>2)throw e();if("max"===o.channelCountMode)throw e();return Object(s.a)(r,o,"attack"),Object(s.a)(r,o,"knee"),Object(s.a)(r,o,"ratio"),Object(s.a)(r,o,"release"),Object(s.a)(r,o,"threshold"),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=t=>(e,n)=>{const o=t(e,t=>t.createGain());return Object(i.a)(o,n),Object(s.a)(o,n,"gain"),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i,o)=>{if(void 0===n.createIIRFilter)return e(n,i,o);const r=t(n,t=>t.createIIRFilter(o.feedforward,o.feedback));return Object(s.a)(r,o),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return c}));var s=n(43),i=n(42),o=n(11);function r(t,e){const n=e[0]*e[0]+e[1]*e[1];return[(t[0]*e[0]+t[1]*e[1])/n,(t[1]*e[0]-t[0]*e[1])/n]}function a(t,e){let n=[0,0];for(let o=t.length-1;o>=0;o-=1)i=e,n=[(s=n)[0]*i[0]-s[1]*i[1],s[0]*i[1]+s[1]*i[0]],n[0]+=t[o];var s,i;return n}const c=(t,e,n,c)=>(u,h,{channelCount:l,channelCountMode:d,channelInterpretation:p,feedback:f,feedforward:_})=>{const m=Object(s.a)(h,u.sampleRate),g=f.length,v=_.length,y=Math.min(g,v);if(0===f.length||f.length>20)throw c();if(0===f[0])throw e();if(0===_.length||_.length>20)throw c();if(0===_[0])throw e();if(1!==f[0]){for(let t=0;t{const e=t.inputBuffer,n=t.outputBuffer,s=e.numberOfChannels;for(let t=0;tb.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>b.dispatchEvent(t[0]),getFrequencyResponse(e,n,s){if(e.length!==n.length||n.length!==s.length)throw t();const i=e.length;for(let t=0;tb.removeEventListener(t[0],t[1],t[2])};return Object(o.a)(S,b)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>t(e,t=>t.createMediaElementSource(n.mediaElement))},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i)=>{if(void 0===n.createMediaStreamDestination)throw e();const o=t(n,t=>t.createMediaStreamDestination());return Object(s.a)(o,i),1===o.numberOfOutputs&&Object.defineProperty(o,"numberOfOutputs",{get:()=>0}),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,{mediaStream:n})=>{const s=n.getAudioTracks(),i=t(e,t=>{const e=s.sort((t,e)=>t.ide.id?1:0).slice(0,1);return t.createMediaStreamSource(new MediaStream(e))});return Object.defineProperty(i,"mediaStream",{value:n}),i}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>(s,{mediaStreamTrack:i})=>"function"==typeof s.createMediaStreamTrackSource?e(s,t=>t.createMediaStreamTrackSource(i)):e(s,e=>{const s=new MediaStream([i]),o=e.createMediaStreamSource(s);if("audio"!==i.kind)throw t();if(n(e))throw new TypeError;return o})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("OfflineAudioContext")?t.OfflineAudioContext:t.hasOwnProperty("webkitOfflineAudioContext")?t.webkitOfflineAudioContext:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return c}));var s=n(5),i=n(4),o=n(1),r=n(30),a=n(31);const c=(t,e,n,c,u,h,l)=>(d,p)=>{const f=n(d,t=>t.createOscillator());return Object(o.a)(f,p),Object(s.a)(f,p,"detune"),Object(s.a)(f,p,"frequency"),void 0!==p.periodicWave?f.setPeriodicWave(p.periodicWave):Object(i.a)(f,p,"type"),e(c,()=>c(d))||Object(r.a)(f),e(u,()=>u(d))||l(f,d),e(h,()=>h(d))||Object(a.a)(f),t(d,f),f}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(5),i=n(4),o=n(1);const r=(t,e)=>(n,r)=>{const a=t(n,t=>t.createPanner());return void 0===a.orientationX?e(n,r):(Object(o.a)(a,r),Object(s.a)(a,r,"orientationX"),Object(s.a)(a,r,"orientationY"),Object(s.a)(a,r,"orientationZ"),Object(s.a)(a,r,"positionX"),Object(s.a)(a,r,"positionY"),Object(s.a)(a,r,"positionZ"),Object(i.a)(a,r,"coneInnerAngle"),Object(i.a)(a,r,"coneOuterAngle"),Object(i.a)(a,r,"coneOuterGain"),Object(i.a)(a,r,"distanceModel"),Object(i.a)(a,r,"maxDistance"),Object(i.a)(a,r,"panningModel"),Object(i.a)(a,r,"refDistance"),Object(i.a)(a,r,"rolloffFactor"),a)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n,o,r,a,c,u,h,l)=>(d,{coneInnerAngle:p,coneOuterAngle:f,coneOuterGain:_,distanceModel:m,maxDistance:g,orientationX:v,orientationY:y,orientationZ:b,panningModel:x,positionX:w,positionY:T,positionZ:O,refDistance:S,rolloffFactor:C,...k})=>{const A=n(d,t=>t.createPanner());if(k.channelCount>2)throw u();if("max"===k.channelCountMode)throw u();Object(s.a)(A,k);const D={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},M=o(d,{...D,channelInterpretation:"speakers",numberOfInputs:6}),j=r(d,{...k,gain:1}),E=r(d,{...D,gain:1}),R=r(d,{...D,gain:0}),q=r(d,{...D,gain:0}),I=r(d,{...D,gain:0}),F=r(d,{...D,gain:0}),V=r(d,{...D,gain:0}),N=a(d,256,6,1),P=c(d,{...D,curve:new Float32Array([1,1]),oversample:"none"});let L=[v,y,b],z=[w,T,O];N.onaudioprocess=({inputBuffer:t})=>{const e=[t.getChannelData(0)[0],t.getChannelData(1)[0],t.getChannelData(2)[0]];e.some((t,e)=>t!==L[e])&&(A.setOrientation(...e),L=e);const n=[t.getChannelData(3)[0],t.getChannelData(4)[0],t.getChannelData(5)[0]];n.some((t,e)=>t!==z[e])&&(A.setPosition(...n),z=n)},Object.defineProperty(R.gain,"defaultValue",{get:()=>0}),Object.defineProperty(q.gain,"defaultValue",{get:()=>0}),Object.defineProperty(I.gain,"defaultValue",{get:()=>0}),Object.defineProperty(F.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0});const B={get bufferSize(){},get channelCount(){return A.channelCount},set channelCount(t){if(t>2)throw u();j.channelCount=t,A.channelCount=t},get channelCountMode(){return A.channelCountMode},set channelCountMode(t){if("max"===t)throw u();j.channelCountMode=t,A.channelCountMode=t},get channelInterpretation(){return A.channelInterpretation},set channelInterpretation(t){j.channelInterpretation=t,A.channelInterpretation=t},get coneInnerAngle(){return A.coneInnerAngle},set coneInnerAngle(t){A.coneInnerAngle=t},get coneOuterAngle(){return A.coneOuterAngle},set coneOuterAngle(t){A.coneOuterAngle=t},get coneOuterGain(){return A.coneOuterGain},set coneOuterGain(t){if(t<0||t>1)throw e();A.coneOuterGain=t},get context(){return A.context},get distanceModel(){return A.distanceModel},set distanceModel(t){A.distanceModel=t},get inputs(){return[j]},get maxDistance(){return A.maxDistance},set maxDistance(t){if(t<0)throw new RangeError;A.maxDistance=t},get numberOfInputs(){return A.numberOfInputs},get numberOfOutputs(){return A.numberOfOutputs},get orientationX(){return E.gain},get orientationY(){return R.gain},get orientationZ(){return q.gain},get panningModel(){return A.panningModel},set panningModel(t){if(A.panningModel=t,A.panningModel!==t&&"HRTF"===t)throw u()},get positionX(){return I.gain},get positionY(){return F.gain},get positionZ(){return V.gain},get refDistance(){return A.refDistance},set refDistance(t){if(t<0)throw new RangeError;A.refDistance=t},get rolloffFactor(){return A.rolloffFactor},set rolloffFactor(t){if(t<0)throw new RangeError;A.rolloffFactor=t},addEventListener:(...t)=>j.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>j.dispatchEvent(t[0]),removeEventListener:(...t)=>j.removeEventListener(t[0],t[1],t[2])};p!==B.coneInnerAngle&&(B.coneInnerAngle=p),f!==B.coneOuterAngle&&(B.coneOuterAngle=f),_!==B.coneOuterGain&&(B.coneOuterGain=_),m!==B.distanceModel&&(B.distanceModel=m),g!==B.maxDistance&&(B.maxDistance=g),v!==B.orientationX.value&&(B.orientationX.value=v),y!==B.orientationY.value&&(B.orientationY.value=y),b!==B.orientationZ.value&&(B.orientationZ.value=b),x!==B.panningModel&&(B.panningModel=x),w!==B.positionX.value&&(B.positionX.value=w),T!==B.positionY.value&&(B.positionY.value=T),O!==B.positionZ.value&&(B.positionZ.value=O),S!==B.refDistance&&(B.refDistance=S),C!==B.rolloffFactor&&(B.rolloffFactor=C),1===L[0]&&0===L[1]&&0===L[2]||A.setOrientation(...L),0===z[0]&&0===z[1]&&0===z[2]||A.setPosition(...z);return l(Object(i.a)(B,A),()=>{j.connect(A),t(j,P,0,0),P.connect(E).connect(M,0,0),P.connect(R).connect(M,0,1),P.connect(q).connect(M,0,2),P.connect(I).connect(M,0,3),P.connect(F).connect(M,0,4),P.connect(V).connect(M,0,5),M.connect(N).connect(d.destination)},()=>{j.disconnect(A),h(j,P,0,0),P.disconnect(E),E.disconnect(M),P.disconnect(R),R.disconnect(M),P.disconnect(q),q.disconnect(M),P.disconnect(I),I.disconnect(M),P.disconnect(F),F.disconnect(M),P.disconnect(V),V.disconnect(M),M.disconnect(N),N.disconnect(d.destination)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,{disableNormalization:n,imag:s,real:i})=>{const o=t(e),r=new Float32Array(s),a=new Float32Array(i);return null!==o?o.createPeriodicWave(a,r,{disableNormalization:n}):e.createPeriodicWave(a,r,{disableNormalization:n})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s,i)=>t(e,t=>t.createScriptProcessor(n,s,i))},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=(t,e,n)=>(o,r)=>t(o,t=>{const a=r.channelCountMode;if("clamped-max"===a)throw n();if(void 0===o.createStereoPanner)return e(o,r);const c=t.createStereoPanner();return Object(i.a)(c,r),Object(s.a)(c,r,"pan"),Object.defineProperty(c,"channelCountMode",{get:()=>a,set:t=>{if(t!==a)throw n()}}),c})},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=(t,e,n,i,o,r)=>{const a=new Float32Array([1,1]),c=Math.PI/2,u={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},h={...u,oversample:"none"},l=(t,s,r,l,d)=>{if(1===s)return((t,e,s,o)=>{const r=new Float32Array(16385),l=new Float32Array(16385);for(let t=0;t<16385;t+=1){const e=t/16384*c;r[t]=Math.cos(e),l[t]=Math.sin(e)}const d=n(t,{...u,gain:0}),p=i(t,{...h,curve:r}),f=i(t,{...h,curve:a}),_=n(t,{...u,gain:0}),m=i(t,{...h,curve:l});return{connectGraph(){e.connect(d),e.connect(f.inputs[0]),e.connect(_),f.connect(s),s.connect(p.inputs[0]),s.connect(m.inputs[0]),p.connect(d.gain),m.connect(_.gain),d.connect(o,0,0),_.connect(o,0,1)},disconnectGraph(){e.disconnect(d),e.disconnect(f.inputs[0]),e.disconnect(_),f.disconnect(s),s.disconnect(p.inputs[0]),s.disconnect(m.inputs[0]),p.disconnect(d.gain),m.disconnect(_.gain),d.disconnect(o,0,0),_.disconnect(o,0,1)}}})(t,r,l,d);if(2===s)return((t,s,o,r)=>{const l=new Float32Array(16385),d=new Float32Array(16385),p=new Float32Array(16385),f=new Float32Array(16385),_=Math.floor(8192.5);for(let t=0;t<16385;t+=1)if(t>_){const e=(t-_)/(16384-_)*c;l[t]=Math.cos(e),d[t]=Math.sin(e),p[t]=0,f[t]=1}else{const e=t/(16384-_)*c;l[t]=1,d[t]=0,p[t]=Math.cos(e),f[t]=Math.sin(e)}const m=e(t,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),g=n(t,{...u,gain:0}),v=i(t,{...h,curve:l}),y=n(t,{...u,gain:0}),b=i(t,{...h,curve:d}),x=i(t,{...h,curve:a}),w=n(t,{...u,gain:0}),T=i(t,{...h,curve:p}),O=n(t,{...u,gain:0}),S=i(t,{...h,curve:f});return{connectGraph(){s.connect(m),s.connect(x.inputs[0]),m.connect(g,1),m.connect(y,1),m.connect(w,1),m.connect(O,1),x.connect(o),o.connect(v.inputs[0]),o.connect(b.inputs[0]),o.connect(T.inputs[0]),o.connect(S.inputs[0]),v.connect(g.gain),b.connect(y.gain),T.connect(w.gain),S.connect(O.gain),g.connect(r,0,0),w.connect(r,0,0),y.connect(r,0,1),O.connect(r,0,1)},disconnectGraph(){s.disconnect(m),s.disconnect(x.inputs[0]),m.disconnect(g,1),m.disconnect(y,1),m.disconnect(w,1),m.disconnect(O,1),x.disconnect(o),o.disconnect(v.inputs[0]),o.disconnect(b.inputs[0]),o.disconnect(T.inputs[0]),o.disconnect(S.inputs[0]),v.disconnect(g.gain),b.disconnect(y.gain),T.disconnect(w.gain),S.disconnect(O.gain),g.disconnect(r,0,0),w.disconnect(r,0,0),y.disconnect(r,0,1),O.disconnect(r,0,1)}}})(t,r,l,d);throw o()};return(e,{channelCount:i,channelCountMode:a,pan:c,...u})=>{if("max"===a)throw o();const h=t(e,{...u,channelCount:1,channelCountMode:a,numberOfInputs:2}),d=n(e,{...u,channelCount:i,channelCountMode:a,gain:1}),p=n(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:c});let{connectGraph:f,disconnectGraph:_}=l(e,i,d,p,h);Object.defineProperty(p.gain,"defaultValue",{get:()=>0});const m={get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){d.channelCount!==t&&(g&&_(),({connectGraph:f,disconnectGraph:_}=l(e,t,d,p,h)),g&&f()),d.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){if("clamped-max"===t||"max"===t)throw o();d.channelCountMode=t},get channelInterpretation(){return d.channelInterpretation},set channelInterpretation(t){d.channelInterpretation=t},get context(){return d.context},get inputs(){return[d]},get numberOfInputs(){return d.numberOfInputs},get numberOfOutputs(){return d.numberOfOutputs},get pan(){return p.gain},addEventListener:(...t)=>d.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>d.dispatchEvent(t[0]),removeEventListener:(...t)=>d.removeEventListener(t[0],t[1],t[2])};let g=!1;return r(Object(s.a)(m,h),()=>{f(),g=!0},()=>{_(),g=!1})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(4),i=n(1);const o=(t,e,n,o,r,a,c)=>(u,h)=>{const l=n(u,t=>t.createWaveShaper());try{return l.curve=new Float32Array([1]),o(u,h)}catch{}Object(i.a)(l,h);const d=h.curve;if(null!==d&&d.length<2)throw e();Object(s.a)(l,h,"curve"),Object(s.a)(l,h,"oversample");let p=null,f=!1;c(l,"curve",t=>()=>t.call(l),e=>n=>(e.call(l,n),f&&(r(n)&&null===p?p=t(u,l):r(n)||null===p||(p(),p=null)),n));return a(l,()=>{f=!0,r(l.curve)&&(p=t(u,l))},()=>{f=!1,null!==p&&(p(),p=null)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n,o,r,a)=>(c,{curve:u,oversample:h,...l})=>{const d=n(c,t=>t.createWaveShaper()),p=n(c,t=>t.createWaveShaper());Object(s.a)(d,l),Object(s.a)(p,l);const f=o(c,{...l,gain:1}),_=o(c,{...l,gain:-1}),m=o(c,{...l,gain:1}),g=o(c,{...l,gain:-1});let v=null,y=!1,b=null;const x={get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){f.channelCount=t,_.channelCount=t,d.channelCount=t,m.channelCount=t,p.channelCount=t,g.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){f.channelCountMode=t,_.channelCountMode=t,d.channelCountMode=t,m.channelCountMode=t,p.channelCountMode=t,g.channelCountMode=t},get channelInterpretation(){return d.channelInterpretation},set channelInterpretation(t){f.channelInterpretation=t,_.channelInterpretation=t,d.channelInterpretation=t,m.channelInterpretation=t,p.channelInterpretation=t,g.channelInterpretation=t},get context(){return d.context},get curve(){return b},set curve(n){if(null!==u&&u.length<2)throw e();if(null===n)d.curve=n,p.curve=n;else{const t=n.length,e=new Float32Array(t+2-t%2),s=new Float32Array(t+2-t%2);e[0]=n[0],s[0]=-n[t-1];const i=Math.ceil((t+1)/2),o=(t+1)/2-1;for(let r=1;rf.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>f.dispatchEvent(t[0]),removeEventListener:(...t)=>f.removeEventListener(t[0],t[1],t[2])};u!==x.curve&&(x.curve=u),h!==x.oversample&&(x.oversample=h);return a(Object(i.a)(x,m),()=>{f.connect(d).connect(m),f.connect(_).connect(p).connect(g).connect(m),y=!0,r(b)&&(v=t(c,f))},()=>{f.disconnect(d),d.disconnect(m),f.disconnect(_),_.disconnect(p),p.disconnect(g),g.disconnect(m),y=!1,null!==v&&(v(),v=null)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(14);const i={numberOfChannels:1},o=(t,e,n,o,r)=>class extends t{constructor(t,n,r){let a;if("number"==typeof t&&void 0!==n&&void 0!==r)a={length:n,numberOfChannels:t,sampleRate:r};else{if("object"!=typeof t)throw new Error("The given parameters are not valid.");a=t}const{length:c,numberOfChannels:u,sampleRate:h}={...i,...a},l=o(u,c,h);e(s.a,()=>Object(s.a)(l))||l.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(l.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(l,u),this._length=c,this._nativeOfflineAudioContext=l,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(n()):(this._state="running",r(this.destination,this._nativeOfflineAudioContext).then(t=>(this._state=null,t)).catch(t=>{throw this._state=null,t}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(17),i=n(21);const o={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,type:"sine"},r=(t,e,n,r,a,c,u,h)=>class extends t{constructor(t,n=o){const s=c(t),i={...o,...n},h=r(s,i),l=u(s),d=l?a():null,p=t.sampleRate/2;super(t,!1,h,d),this._detune=e(this,l,h.detune,153600,-153600),this._frequency=e(this,l,h.frequency,p,-p),this._nativeOscillatorNode=h,this._onended=null,this._oscillatorNodeRenderer=d,null!==this._oscillatorNodeRenderer&&void 0!==i.periodicWave&&(this._oscillatorNodeRenderer.periodicWave=i.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(t){const e="function"==typeof t?h(this,t):null;this._nativeOscillatorNode.onended=e;const n=this._nativeOscillatorNode.onended;this._onended=null!==n&&n===e?t:n}get type(){return this._nativeOscillatorNode.type}set type(t){if(this._nativeOscillatorNode.type=t,"custom"===t)throw n();null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(t){this._nativeOscillatorNode.setPeriodicWave(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=t)}start(t=0){if(this._nativeOscillatorNode.start(t),null!==this._oscillatorNodeRenderer)this._oscillatorNodeRenderer.start=t;else{Object(s.a)(this);const t=()=>{this._nativeOscillatorNode.removeEventListener("ended",t),setTimeout(()=>Object(i.a)(this),1e3)};this._nativeOscillatorNode.addEventListener("ended",t)}}stop(t=0){this._nativeOscillatorNode.stop(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null,u=null;return{set periodicWave(t){a=t},set start(t){c=t},set stop(t){u=t},render(h,l,d){const p=r.get(l);return void 0!==p?Promise.resolve(p):(async(h,l,d)=>{let p=n(h);const f=Object(s.a)(p,l);if(!f){const t={channelCount:p.channelCount,channelCountMode:p.channelCountMode,channelInterpretation:p.channelInterpretation,detune:p.detune.value,frequency:p.frequency.value,periodicWave:null===a?void 0:a,type:p.type};p=e(l,t),null!==c&&p.start(c),null!==u&&p.stop(u)}return r.set(l,p),f?(await t(l,h.detune,p.detune,d),await t(l,h.frequency,p.frequency,d)):(await i(l,h.detune,p.detune,d),await i(l,h.frequency,p.frequency,d)),await o(h,l,p,d),p})(h,l,d)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},o=(t,e,n,o,r,a)=>class extends t{constructor(t,c=i){const u=r(t),h={...i,...c},l=n(u,h),d=a(u);super(t,!1,l,d?o():null),this._nativePannerNode=l,this._orientationX=e(this,d,l.orientationX,s.b,s.a),this._orientationY=e(this,d,l.orientationY,s.b,s.a),this._orientationZ=e(this,d,l.orientationZ,s.b,s.a),this._positionX=e(this,d,l.positionX,s.b,s.a),this._positionY=e(this,d,l.positionY,s.b,s.a),this._positionZ=e(this,d,l.positionZ,s.b,s.a)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(t){this._nativePannerNode.coneInnerAngle=t}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(t){this._nativePannerNode.coneOuterAngle=t}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(t){this._nativePannerNode.coneOuterGain=t}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(t){this._nativePannerNode.distanceModel=t}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(t){this._nativePannerNode.maxDistance=t}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(t){this._nativePannerNode.panningModel=t}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(t){this._nativePannerNode.refDistance=t}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(t){this._nativePannerNode.rolloffFactor=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n,o,r,a,c,u,h,l)=>()=>{const d=new WeakMap;let p=null;return{render(f,_,m){const g=d.get(_);return void 0!==g?Promise.resolve(g):(async(f,_,m)=>{let g=null,v=a(f);const y={channelCount:v.channelCount,channelCountMode:v.channelCountMode,channelInterpretation:v.channelInterpretation},b={...y,coneInnerAngle:v.coneInnerAngle,coneOuterAngle:v.coneOuterAngle,coneOuterGain:v.coneOuterGain,distanceModel:v.distanceModel,maxDistance:v.maxDistance,panningModel:v.panningModel,refDistance:v.refDistance,rolloffFactor:v.rolloffFactor},x=Object(i.a)(v,_);if("bufferSize"in v)g=o(_,{...y,gain:1});else if(!x){const t={...b,orientationX:v.orientationX.value,orientationY:v.orientationY.value,orientationZ:v.orientationZ.value,positionX:v.positionX.value,positionY:v.positionY.value,positionZ:v.positionZ.value};v=r(_,t)}if(d.set(_,null===g?v:g),null!==g){if(null===p){if(null===c)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new c(6,f.context.length,_.sampleRate),s=e(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});s.connect(t.destination),p=(async()=>{const e=await Promise.all([f.orientationX,f.orientationY,f.orientationZ,f.positionX,f.positionY,f.positionZ].map(async(e,s)=>{const i=n(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:0===s?1:0});return await u(t,e,i.offset,m),i}));for(let t=0;t<6;t+=1)e[t].connect(s,0,t),e[t].start(0);return l(t)})()}const t=await p,s=o(_,{...y,gain:1});await h(f,_,s,m);const i=[];for(let e=0;et!==a[e])||n.some((t,e)=>t!==d[e])){a=t,d=n;const i=e/_.sampleRate;v.gain.setValueAtTime(0,i),v=o(_,{...y,gain:0}),x=r(_,{...b,orientationX:a[0],orientationY:a[1],orientationZ:a[2],positionX:d[0],positionY:d[1],positionZ:d[2]}),v.gain.setValueAtTime(1,i),s.connect(v).connect(x.inputs[0]),x.connect(g)}}return g}return x?(await t(_,f.orientationX,v.orientationX,m),await t(_,f.orientationY,v.orientationY,m),await t(_,f.orientationZ,v.orientationZ,m),await t(_,f.positionX,v.positionX,m),await t(_,f.positionY,v.positionY,m),await t(_,f.positionZ,v.positionZ,m)):(await u(_,f.orientationX,v.orientationX,m),await u(_,f.orientationY,v.orientationY,m),await u(_,f.orientationZ,v.orientationZ,m),await u(_,f.positionX,v.positionX,m),await u(_,f.positionY,v.positionY,m),await u(_,f.positionZ,v.positionZ,m)),Object(s.a)(v)?await h(f,_,v.inputs[0],m):await h(f,_,v,m),v})(f,_,m)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={disableNormalization:!1},i=(t,e,n)=>class i{constructor(i,o){const r=e(i),a={...s,...o},c=t(r,a);return n.add(c),c}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===i.prototype||n.has(t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i,o)=>(t(s).replay(i),e(s,n,i,o))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>async(s,i,o,r)=>{const a=t(s),c=[...r,s];await Promise.all(a.activeInputs.map((t,r)=>Array.from(t).filter(([t])=>!c.includes(t)).map(async([t,a])=>{const u=e(t),h=await u.render(t,i,c),l=s.context.destination;n(t)||s===l&&n(s)||h.connect(o,a,r)})).reduce((t,e)=>[...t,...e],[]))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>async(s,i,o,r)=>{const a=e(s);await Promise.all(Array.from(a.activeInputs).map(async([e,s])=>{const a=t(e),c=await a.render(e,i,r);n(e)||c.connect(o,s)}))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(14);const i=(t,e,n,i)=>o=>t(s.a,()=>Object(s.a)(o))?Promise.resolve(t(i,i)).then(t=>{if(!t){const t=n(o,512,0,1);o.oncomplete=()=>{t.onaudioprocess=null,t.disconnect()},t.onaudioprocess=()=>o.currentTime,t.connect(o.destination)}return o.startRendering()}):new Promise(t=>{const n=e(o,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});o.oncomplete=e=>{n.disconnect(),t(e.renderedBuffer)},n.connect(o.destination),o.startRendering()})},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(29);const i=(t,e,n,i,o,r,a,c)=>{const u=[];return(h,l)=>n(h).render(h,l,u).then(()=>Promise.all(Array.from(i(l)).map(t=>n(t).render(t,l,u)))).then(()=>o(l)).then(n=>("function"!=typeof n.copyFromChannel?(a(n),Object(s.a)(n)):e(r,()=>r(n))||c(n),t.add(n),n))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},i=(t,e,n,i,o,r)=>class extends t{constructor(t,a=s){const c=o(t),u={...s,...a},h=n(c,u),l=r(c);super(t,!1,h,l?i():null),this._pan=e(this,l,h.pan,1,-1)}get pan(){return this._pan}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n,o,r)=>()=>{const a=new WeakMap;return{render(c,u,h){const l=a.get(u);return void 0!==l?Promise.resolve(l):(async(c,u,h)=>{let l=n(c);const d=Object(i.a)(l,u);if(!d){const t={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,pan:l.pan.value};l=e(u,t)}return a.set(u,l),d?await t(u,c.pan,l.pan,h):await o(u,c.pan,l.pan,h),Object(s.a)(l)?await r(c,u,l.inputs[0],h):await r(c,u,l,h),l})(c,u,h)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;try{new t({length:1,sampleRate:44100})}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100).createBuffer(1,1,44100);if(void 0===e.copyToChannel)return!0;const n=new Float32Array(2);try{e.copyFromChannel(n,0,0)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource());n.start();try{n.start()}catch{return!0}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100),n=e.createBuffer(1,1,e.sampleRate),s=e.createBufferSource();return n.getChannelData(0)[0]=1,s.buffer=n,s.start(0,0,0),s.connect(e.destination),new Promise(t=>{e.oncomplete=({renderedBuffer:e})=>{t(0===e.getChannelData(0)[0])},e.startRendering()})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource()),s=e.createBuffer(1,1,44100);n.buffer=s;try{n.start(0,1)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource());n.start();try{n.stop()}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;if(void 0!==t.prototype&&void 0!==t.prototype.close)return!0;const e=new t,n=void 0!==e.close;try{e.close()}catch{}return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100);return new Promise(t=>{let n=!0;const s=s=>{n&&(n=!1,e.startRendering(),t(s instanceof TypeError))};let i;try{i=e.decodeAudioData(null,()=>{},s)}catch(t){s(t)}void 0!==i&&i.catch(s)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;let e;try{e=new t({latencyHint:"balanced"})}catch{return!1}return e.close(),!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100).createGain(),n=e.connect(e)===e;return e.disconnect(e),n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createOscillator());try{n.start(-1)}catch(t){return t instanceof RangeError}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=e.createBuffer(1,1,44100),s=t(e,t=>t.createBufferSource());s.buffer=n,s.start(),s.stop();try{return s.stop(),!0}catch{return!1}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createOscillator());try{n.stop(-1)}catch(t){return t instanceof RangeError}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>async()=>{if(null===t)return!0;if(null===e)return!1;const n=new Blob(['class A extends AudioWorkletProcessor{process(){this.port.postMessage(0)}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),s=new e(1,128,3200),i=URL.createObjectURL(n);let o=!1;try{await s.audioWorklet.addModule(i);const e=s.createGain(),n=new t(s,"a",{numberOfOutputs:0});n.port.onmessage=()=>o=!0,e.connect(n),await s.startRendering()}catch{}finally{URL.revokeObjectURL(i)}return o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return!1;const n=new e(1,1,44100),s=t(n,t=>t.createChannelMerger());try{s.channelCount=2}catch{return!0}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return!1;const n=new e(1,1,44100);return void 0===n.createConstantSource||t(n,t=>t.createConstantSource()).offset.maxValue!==Number.POSITIVE_INFINITY}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100),n=e.createConvolver();n.buffer=e.createBuffer(1,1,e.sampleRate);try{n.buffer=e.createBuffer(1,1,e.sampleRate)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>null!==t&&t.hasOwnProperty("isSecureContext")},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t;try{return e.createMediaStreamSource(new MediaStream),!1}catch(t){return!0}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return Promise.resolve(!1);const n=new e(1,1,44100),s=t(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(t=>{n.oncomplete=()=>{s.disconnect(),t(0!==n.currentTime)},n.startRendering()})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100);if(void 0===e.createStereoPanner)return Promise.resolve(!0);if(void 0===e.createConstantSource)return Promise.resolve(!0);const n=e.createConstantSource(),s=e.createStereoPanner();return n.channelCount=1,n.offset.value=1,s.channelCount=1,n.start(),n.connect(s).connect(e.destination),e.startRendering().then(t=>1!==t.getChannelData(0)[0])}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},i=(t,e,n,i,o,r)=>class extends t{constructor(t,e=s){const a=o(t),c={...s,...e},u=n(a,c);super(t,!0,u,r(a)?i():null),this._isCurveNullified=!1,this._nativeWaveShaperNode=u}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(t){if(null===t)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(t.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=t}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(t){this._nativeWaveShaperNode.oversample=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n)=>()=>{const o=new WeakMap;return{render(r,a,c){const u=o.get(a);return void 0!==u?Promise.resolve(u):(async(r,a,c)=>{let u=e(r);if(!Object(i.a)(u,a)){const e={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,curve:u.curve,oversample:u.oversample};u=t(a,e)}return o.set(a,u),Object(s.a)(u)?await n(r,a,u.inputs[0],c):await n(r,a,u,c),u})(r,a,c)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>"undefined"==typeof window?null:window},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{n.copyFromChannel=(s,i,o=0)=>{const r=t(o),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),h=s.length;for(let t=r<0?-r:0;t+r{const r=t(o),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),h=s.length;for(let t=r<0?-r:0;t+re=>{var n,s;e.copyFromChannel=(n=e.copyFromChannel,(s,i,o=0)=>{const r=t(o),a=t(i);if(r{const r=t(o),a=t(i);if(r(e,n)=>{const s=n.createBuffer(1,1,n.sampleRate);null===e.buffer&&(e.buffer=s),t(e,"buffer",t=>()=>{const n=t.call(e);return n===s?null:n},t=>n=>t.call(e,null===n?s:n))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=t=>(e,n)=>{const i=t(n,t=>t.createGain());e.connect(i);const o=(r=e.disconnect,()=>{r.call(e,i),e.removeEventListener("ended",o)});var r;e.addEventListener("ended",o),Object(s.a)(e,i),e.stop=(t=>{let n=!1;return(s=0)=>{if(n)try{t.call(e,s)}catch{i.gain.setValueAtTime(0,s)}else t.call(e,s),n=!0}})(e.stop)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>(s,i)=>{i.channelCount=1,i.channelCountMode="explicit",Object.defineProperty(i,"channelCount",{get:()=>1,set:()=>{throw t()}}),Object.defineProperty(i,"channelCountMode",{get:()=>"explicit",set:()=>{throw t()}});const o=e(s,t=>t.createBufferSource());n(i,()=>{const t=i.numberOfInputs;for(let e=0;eo.disconnect(i))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>new Promise(t=>{const e=new ArrayBuffer(0),{port1:n,port2:s}=new MessageChannel;n.onmessage=({data:e})=>t(null!==e),s.postMessage(e,[e])})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.start=(e=t.start,(n=0,s=0,i)=>{const o=t.buffer,r=null===o?s:Math.min(o.duration,s);null!==o&&r>o.duration-.5/t.context.sampleRate?e.call(t,n,0,0):e.call(t,n,r,i)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return N}));var s=n(0),i=n(24),o=n(22);const r=t=>"port"in t;var a=n(33),c=n(20);const u=(t,e)=>{if(!Object(c.a)(t).delete(e))throw new Error("Missing the expected event listener.")};var h=n(34),l=n(8),d=n(26),p=n(6),f=n(27),_=n(9),m=n(16),g=n(23),v=n(19);const y=t=>!s.a.has(t),b=(t,e)=>{const n=Array.from(t).filter(e);if(n.length>1)throw Error("More than one element was found.");if(0===n.length)throw Error("No element was found.");const[s]=n;return t.delete(s),s};var x=n(17),w=n(21);const T=(t,e)=>{!r(t)&&e.every(t=>0===t.size)&&Object(w.a)(t)},O=t=>new Promise(e=>{const n=t.createScriptProcessor(256,1,1),s=t.createGain(),i=t.createBuffer(1,2,44100),o=i.getChannelData(0);o[0]=1,o[1]=1;const r=t.createBufferSource();r.buffer=i,r.loop=!0,r.connect(n).connect(t.destination),r.connect(s),r.disconnect(s),n.onaudioprocess=s=>{const i=s.inputBuffer.getChannelData(0);Array.prototype.some.call(i,t=>1===t)?e(!0):e(!1),r.stop(),n.onaudioprocess=null,r.disconnect(n),n.disconnect(t.destination)},r.start()}),S=(t,e)=>{const n=new Map;for(const e of t)for(const t of e){const e=n.get(t);n.set(t,void 0===e?1:e+1)}n.forEach((t,n)=>e(n,t))};var C=n(25);const k=(t,e,[n,s,i],o)=>{Object(m.a)(t[s],[e,n,i],t=>t[0]===e&&t[1]===n,o)},A=(t,e,[n,s],i)=>{Object(m.a)(t,[e,n,s],t=>t[0]===e&&t[1]===n,i)},D=(t,e,[n,s,i],o)=>{const r=t.get(n);void 0===r?t.set(n,new Set([[s,e,i]])):Object(m.a)(r,[s,e,i],t=>t[0]===s&&t[1]===e,o)},M=(t,[e,n,s],i)=>{const o=t.get(e);void 0===o?t.set(e,new Set([[n,s]])):Object(m.a)(o,[n,s],t=>t[0]===n,i)},j=(t,e,n,s)=>{const i=Object(_.a)(t,e),o=b(i,t=>t[0]===n&&t[1]===s);return 0===i.size&&t.delete(e),o},E=(t,e,n)=>{const s=Object(_.a)(t,e),i=b(s,t=>t[0]===n);return 0===s.size&&t.delete(e),i},R=(t,e,n,s)=>{const{activeInputs:i,passiveInputs:o}=Object(l.a)(e),{outputs:r}=Object(l.a)(t),u=Object(c.a)(t),d=r=>{const c=Object(p.a)(e),u=Object(p.a)(t);if(r){const r=j(o,t,n,s);k(i,t,r,!1),Object(v.a)(t)||Object(a.a)(u,c,n,s),y(e)&&Object(x.a)(e)}else{const r=((t,e,n,s)=>b(t[s],t=>t[0]===e&&t[1]===n))(i,t,n,s);D(o,s,r,!1),Object(v.a)(t)||Object(h.a)(u,c,n,s),Object(g.a)(e)&&T(e,i)}};return!!Object(m.a)(r,[e,n,s],t=>t[0]===e&&t[1]===n&&t[2]===s,!0)&&(u.add(d),Object(g.a)(t)?k(i,t,[n,s,d],!0):D(o,s,[t,n,d],!0),!0)},q=(t,e,n)=>{const{activeInputs:s,passiveInputs:i}=Object(d.a)(e),{outputs:o}=Object(l.a)(t),r=Object(c.a)(t),a=o=>{const r=Object(p.a)(t),a=Object(f.a)(e);if(o){const e=E(i,t,n);A(s,t,e,!1),Object(v.a)(t)||r.connect(a,n)}else{const e=((t,e,n)=>b(t,t=>t[0]===e&&t[1]===n))(s,t,n);M(i,e,!1),Object(v.a)(t)||r.disconnect(a,n)}};return!!Object(m.a)(o,[e,n],t=>t[0]===e&&t[1]===n,!0)&&(r.add(a),Object(g.a)(t)?A(s,t,[n,a],!0):M(i,[t,n,a],!0),!0)},I=(t,e,n)=>{for(const s of t)if(s[0]===e&&s[1]===n)return t.delete(s),s;return null},F=(t,e,n,s)=>{const[i,o]=((t,e,n,s)=>{const{activeInputs:i,passiveInputs:o}=Object(l.a)(e),r=I(i[s],t,n);if(null===r){return[j(o,t,n,s)[2],!1]}return[r[2],!0]})(t,e,n,s);if(null!==i&&(u(t,i),o&&!Object(v.a)(t)&&Object(h.a)(Object(p.a)(t),Object(p.a)(e),n,s)),Object(g.a)(e)){const{activeInputs:t}=Object(l.a)(e);T(e,t)}},V=(t,e,n)=>{const[s,i]=((t,e,n)=>{const{activeInputs:s,passiveInputs:i}=Object(d.a)(e),o=I(s,t,n);if(null===o){return[E(i,t,n)[1],!1]}return[o[2],!0]})(t,e,n);null!==s&&(u(t,s),i&&!Object(v.a)(t)&&Object(p.a)(t).disconnect(Object(f.a)(e),n))},N=(t,e,n,c,u,h,_,g,v,b,w,T,D,M,j)=>class extends b{constructor(e,i,o,r){super(o),this._context=e,this._nativeAudioNode=o;const a=w(e);T(a)&&!0!==n(O,()=>O(a))&&(t=>{const e=new Map;var n,s;t.connect=(n=t.connect.bind(t),(t,s=0,i=0)=>{const o=Object(C.a)(t)?n(t,s,i):n(t,s),r=e.get(t);return void 0===r?e.set(t,[{input:i,output:s}]):r.every(t=>t.input!==i||t.output!==s)&&r.push({input:i,output:s}),o}),t.disconnect=(s=t.disconnect,(n,i,o)=>{if(s.apply(t),void 0===n)e.clear();else if("number"==typeof n)for(const[t,s]of e){const i=s.filter(t=>t.output!==n);0===i.length?e.delete(t):e.set(t,i)}else if(e.has(n))if(void 0===i)e.delete(n);else{const t=e.get(n);if(void 0!==t){const s=t.filter(t=>t.output!==i&&(t.input!==o||void 0===o));0===s.length?e.delete(n):e.set(n,s)}}for(const[n,s]of e)s.forEach(e=>{Object(C.a)(n)?t.connect(n,e.output,e.input):t.connect(n,e.output)})})})(o),s.c.set(this,o),s.i.set(this,new Set),i&&Object(x.a)(this),t(this,r,o)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(t){this._nativeAudioNode.channelCount=t}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(t){this._nativeAudioNode.channelCountMode=t}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(t){this._nativeAudioNode.channelInterpretation=t}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(t,n=0,s=0){if(n<0||n>=this._nativeAudioNode.numberOfOutputs)throw u();const o=w(this._context),g=j(o);if(D(t)||M(t))throw h();if(Object(i.a)(t)){const i=Object(p.a)(t);try{const c=Object(a.a)(this._nativeAudioNode,i,n,s);if(g||y(this)?this._nativeAudioNode.disconnect(...c):y(t)&&Object(x.a)(t),r(t)){const t=e.get(i);if(void 0===t){const t=o.createGain();t.connect(c[0],0,c[2]),e.set(i,new Map([[s,t]]))}else if(void 0===t.get(s)){const e=o.createGain();e.connect(c[0],0,c[2]),t.set(s,e)}}}catch(t){if(12===t.code)throw h();throw t}if(g?((t,e,n,s)=>{const{outputs:i}=Object(l.a)(t);if(Object(m.a)(i,[e,n,s],t=>t[0]===e&&t[1]===n&&t[2]===s,!0)){const{activeInputs:i}=Object(l.a)(e);return k(i,t,[n,s,null],!0),!0}return!1})(this,t,n,s):R(this,t,n,s)){const e=v([this],t);S(e,c(g))}return t}const b=Object(f.a)(t);if("playbackRate"===b.name)throw _();try{this._nativeAudioNode.connect(b,n),(g||y(this))&&this._nativeAudioNode.disconnect(b,n)}catch(t){if(12===t.code)throw h();throw t}if(g?((t,e,n)=>{const{outputs:s}=Object(l.a)(t);if(Object(m.a)(s,[e,n],t=>t[0]===e&&t[1]===n,!0)){const{activeInputs:s}=Object(d.a)(e);return A(s,t,[n,null],!0),!0}return!1})(this,t,n):q(this,t,n)){const e=v([this],t);S(e,c(g))}}disconnect(t,e,n){let s;if(void 0===t)s=(t=>{const e=Object(l.a)(t),n=[];for(const s of e.outputs)Object(o.a)(s)?F(t,...s):V(t,...s),n.push(s[0]);return e.outputs.clear(),n})(this);else if("number"==typeof t){if(t<0||t>=this.numberOfOutputs)throw u();s=((t,e)=>{const n=Object(l.a)(t),s=[];for(const i of n.outputs)i[1]===e&&(Object(o.a)(i)?F(t,...i):V(t,...i),s.push(i[0]),n.outputs.delete(i));return s})(this,t)}else{if(void 0!==e&&(e<0||e>=this.numberOfOutputs))throw u();if(Object(i.a)(t)&&void 0!==n&&(n<0||n>=t.numberOfInputs))throw u();if(s=((t,e,n,s)=>{const i=Object(l.a)(t);return Array.from(i.outputs).filter(t=>!(t[0]!==e||void 0!==n&&t[1]!==n||void 0!==s&&t[2]!==s)).map(e=>(Object(o.a)(e)?F(t,...e):V(t,...e),i.outputs.delete(e),e[0]))})(this,t,e,n),0===s.length)throw h()}for(const t of s){const e=v([this],t);S(e,g)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return l}));var s=n(2),i=n(43),o=n(35),r=n(41),a=n(0);const c=async(t,e)=>new t(await(t=>new Promise((e,n)=>{const{port1:s,port2:i}=new MessageChannel;s.onmessage=({data:t})=>{s.close(),i.close(),e(t)},s.onmessageerror=({data:t})=>{s.close(),i.close(),n(t)},i.postMessage(t)}))(e));var u=n(36),h=n(40);const l=(t,e,n,l,d,p,f,_,m,g,v,y,b)=>(x,w,T,O)=>{if(0===O.numberOfInputs&&0===O.numberOfOutputs)throw g();if(void 0!==O.outputChannelCount){if(O.outputChannelCount.some(t=>t<1))throw g();if(O.outputChannelCount.length!==O.numberOfOutputs)throw n()}if("explicit"!==O.channelCountMode)throw g();const S=O.channelCount*O.numberOfInputs,C=O.outputChannelCount.reduce((t,e)=>t+e,0),k=void 0===T.parameterDescriptors?0:T.parameterDescriptors.length;if(S+k>6||C>6)throw g();const A=new MessageChannel,D=[],M=[];for(let t=0;tvoid 0===t?0:t},maxValue:{get:()=>void 0===e?s.b:e},minValue:{get:()=>void 0===n?s.a:n}}),j.push(o)}const E=d(x,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+k)}),R=Object(i.a)(w,x.sampleRate),q=m(x,R,S+k,Math.max(1,C)),I=p(x,{channelCount:Math.max(1,C),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,C)}),F=[];for(let t=0;t{const n=j[e];return n.connect(E,0,S+e),n.start(0),[t,n.offset]}));E.connect(q);let N=O.channelInterpretation,P=null;const L=0===O.numberOfOutputs?[q]:F,z={get bufferSize(){return R},get channelCount(){return O.channelCount},set channelCount(t){throw l()},get channelCountMode(){return O.channelCountMode},set channelCountMode(t){throw l()},get channelInterpretation(){return N},set channelInterpretation(t){for(const e of D)e.channelInterpretation=t;N=t},get context(){return q.context},get inputs(){return D},get numberOfInputs(){return O.numberOfInputs},get numberOfOutputs(){return O.numberOfOutputs},get onprocessorerror(){return P},set onprocessorerror(t){"function"==typeof P&&z.removeEventListener("processorerror",P),P="function"==typeof t?t:null,"function"==typeof P&&z.addEventListener("processorerror",P)},get parameters(){return V},get port(){return A.port2},addEventListener:(...t)=>q.addEventListener(t[0],t[1],t[2]),connect:e.bind(null,L),disconnect:v.bind(null,L),dispatchEvent:(...t)=>q.dispatchEvent(t[0]),removeEventListener:(...t)=>q.removeEventListener(t[0],t[1],t[2])},B=new Map;var W,U;A.port1.addEventListener=(W=A.port1.addEventListener,(...t)=>{if("message"===t[0]){const e="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;if(null!==e){const n=B.get(t[1]);void 0!==n?t[1]=n:(t[1]=t=>{y(x.currentTime,x.sampleRate,()=>e(t))},B.set(e,t[1]))}}return W.call(A.port1,t[0],t[1],t[2])}),A.port1.removeEventListener=(U=A.port1.removeEventListener,(...t)=>{if("message"===t[0]){const e=B.get(t[1]);void 0!==e&&(B.delete(t[1]),t[1]=e)}return U.call(A.port1,t[0],t[1],t[2])});let G=null;Object.defineProperty(A.port1,"onmessage",{get:()=>G,set:t=>{"function"==typeof G&&A.port1.removeEventListener("message",G),G="function"==typeof t?t:null,"function"==typeof G&&(A.port1.addEventListener("message",G),A.port1.start())}}),T.prototype.port=A.port1;let Y=null;((t,e,n,s)=>{let i=a.k.get(t);void 0===i&&(i=new WeakMap,a.k.set(t,i));const o=c(n,s);return i.set(e,o),o})(x,z,T,O).then(t=>Y=t);const Q=Object(u.a)(O.numberOfInputs,O.channelCount),Z=Object(u.a)(O.numberOfOutputs,O.outputChannelCount),X=void 0===T.parameterDescriptors?[]:T.parameterDescriptors.reduce((t,{name:e})=>({...t,[e]:new Float32Array(128)}),{});let H=!0;const $=()=>{O.numberOfOutputs>0&&q.disconnect(I);for(let t=0,e=0;t{if(null!==Y)for(let s=0;s{Object(o.a)(e,X,t,S+n,s)});for(let t=0;t{const s=t.get(z);return void 0===s||void 0===s.get(n)?[]:e}),i=y(x.currentTime+s/x.sampleRate,x.sampleRate,()=>Y.process(e,Z,X));H=i;for(let t=0,e=0;tq.connect(K).connect(K.context.destination),et=()=>{q.disconnect(K),K.disconnect()};return tt(),b(z,()=>{if(H){et(),O.numberOfOutputs>0&&q.connect(I);for(let t=0,e=0;t{H&&(tt(),$()),J=!1})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return u}));var s=n(0);const i={construct:()=>i},o=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,r=(t,e)=>{const n=[];let s=t.replace(/^[\s]+/,""),i=s.match(o);for(;null!==i;){const t=i[1].slice(1,-1),r=i[0].replace(/([\s]+)?;?$/,"").replace(t,new URL(t,e).toString());n.push(r),s=s.slice(i[0].length).replace(/^[\s]+/,""),i=s.match(o)}return[n.join(";"),s]},a=t=>{if(void 0!==t&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},c=t=>{if(!(t=>{try{new new Proxy(t,i)}catch{return!1}return!0})(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(null===t.prototype||"object"!=typeof t.prototype)throw new TypeError("The given value for processorCtor should have a prototype.")},u=(t,e,n,i,o,u,h,l,d)=>(p,f,_={credentials:"omit"})=>{const m=u(p),g=new URL(f,d.location.href).toString();if(void 0!==m.audioWorklet)return i(f).then(t=>{const[e,n]=r(t,g),s=new Blob([`${e};(registerProcessor=>{${n}\n})((n,p)=>registerProcessor(n,class extends p{process(i,o,p){return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}))`],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(s),a=o(m);return(null!==a?a:m).audioWorklet.addModule(i,_).then(()=>URL.revokeObjectURL(i)).catch(t=>{throw URL.revokeObjectURL(i),void 0!==t.code&&"SyntaxError"!==t.name||(t.code=12),t})});const v=l.get(p);if(void 0!==v&&v.has(f))return Promise.resolve();const y=h.get(p);if(void 0!==y){const t=y.get(f);if(void 0!==t)return t}const b=i(f).then(t=>{const[n,s]=r(t,g);return e(`${n};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${s}\n})})(window,'_AWGS')`)}).then(()=>{const e=d._AWGS.pop();if(void 0===e)throw new SyntaxError;n(m.currentTime,m.sampleRate,()=>e(class{},void 0,(e,n)=>{if(""===e.trim())throw t();const i=s.j.get(m);if(void 0!==i){if(i.has(e))throw t();c(n),a(n.parameterDescriptors),i.set(e,n)}else c(n),a(n.parameterDescriptors),s.j.set(m,new Map([[e,n]]))},m.sampleRate,void 0,void 0))}).catch(t=>{throw void 0!==t.code&&"SyntaxError"!==t.name||(t.code=12),t});return void 0===y?h.set(p,new Map([[f,b]])):y.set(f,b),b.then(()=>{const t=l.get(p);void 0===t?l.set(p,new Set([f])):t.add(f)}).catch(()=>{}).then(()=>{const t=h.get(p);void 0!==t&&t.delete(f)}),b}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(4),i=n(1);const o=t=>"function"==typeof t.getFloatTimeDomainData,r=(t,e,n)=>(r,a)=>{const c=n(r,t=>t.createAnalyser());if(Object(i.a)(c,a),!(a.maxDecibels>a.minDecibels))throw e();return Object(s.a)(c,a,"fftSize"),Object(s.a)(c,a,"maxDecibels"),Object(s.a)(c,a,"minDecibels"),Object(s.a)(c,a,"smoothingTimeConstant"),t(o,()=>o(c))||(t=>{t.getFloatTimeDomainData=e=>{const n=new Uint8Array(e.length);t.getByteTimeDomainData(n);const s=Math.max(n.length,t.fftSize);for(let t=0;t(y,b={})=>{const x=n(y,t=>t.createBufferSource());return Object(o.a)(x,b),Object(s.a)(x,b,"playbackRate"),Object(i.a)(x,b,"buffer"),Object(i.a)(x,b,"loop"),Object(i.a)(x,b,"loopEnd"),Object(i.a)(x,b,"loopStart"),e(u,()=>u(y))||(t=>{t.start=(e=>{let n=!1;return(s=0,i=0,o)=>{if(n)throw Object(r.a)();e.call(t,s,i,o),n=!0}})(t.start)})(x),e(h,h)||((t,e)=>{let n=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;var i,o;t.start=(i=t.start,o=t.stop,(r=0,a=0,c=Number.POSITIVE_INFINITY)=>{if(i.call(t,r,a),c>=0&&c(o=0)=>{s=Math.max(o,e.currentTime),i.call(t,Math.min(n,s))})(t.stop)})(x,y),e(l,()=>l(y))||m(x),e(d,()=>d(y))||g(x,y),e(p,()=>p(y))||Object(a.a)(x),e(f,()=>f(y))||v(x,y),e(_,()=>_(y))||Object(c.a)(x),t(y,x),x}},function(t,e,n){"use strict";n.d(e,"a",(function(){return d}));var s=n(35),i=n(41),o=n(36),r=n(8),a=n(0),c=n(6),u=n(9);var h=n(3);const l=async(t,e,n,h,l,d)=>{const p=null===e?128*Math.ceil(t.context.length/128):e.length,f=h.channelCount*h.numberOfInputs,_=h.outputChannelCount.reduce((t,e)=>t+e,0),m=0===_?null:n.createBuffer(_,p,n.sampleRate);if(void 0===l)throw new Error("Missing the processor constructor.");const g=Object(r.a)(t),v=await((t,e)=>{const n=Object(u.a)(a.k,t),s=Object(c.a)(e);return Object(u.a)(n,s)})(n,t),y=Object(o.a)(h.numberOfInputs,h.channelCount),b=Object(o.a)(h.numberOfOutputs,h.outputChannelCount),x=Array.from(t.parameters.keys()).reduce((t,e)=>({...t,[e]:new Float32Array(128)}),{});for(let o=0;o0&&null!==e)for(let t=0;t{Object(s.a)(e,x,t,f+n,o)});for(let t=0;t0===g.activeInputs[e].size?[]:t),e=d(o/n.sampleRate,n.sampleRate,()=>v.process(t,b,x));if(null!==m)for(let t=0,e=0;t(v,y,b)=>{const x=new WeakMap;let w=null;return{render(T,O,S){a(O,T);const C=x.get(O);return void 0!==C?Promise.resolve(C):(async(a,T,O)=>{let S=d(a),C=null;const k=Object(h.a)(S,T);if(null===p){const t=y.outputChannelCount.reduce((t,e)=>t+e,0),n=i(T,{channelCount:Math.max(1,t),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,t)}),o=[];for(let t=0;t{const c=new f(n,128*Math.ceil(a.context.length/128),T.sampleRate),u=[],h=[];for(let t=0;t{const e=o(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:t.value});return await _(c,t,e.offset,O),e})),d=s(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,t+e)});for(let t=0;tm(a,c,t,O))),g(c)};w=l(a,0===n?null:await c(),T,y,b,u)}const t=await w,e=n(T),[c,h,d]=C;null!==t&&(e.buffer=t,e.start(0)),e.connect(c);for(let t=0,e=0;t(f,_)=>{const m=a(f)?f:r(f);if(o.has(_)){const t=n();return Promise.reject(t)}try{o.add(_)}catch{}if(e(l,()=>l(m))){return("closed"===m.state&&null!==u&&c(m)?new u(1,1,m.sampleRate):m).decodeAudioData(_).catch(t=>{if(t instanceof DOMException&&"NotSupportedError"===t.name)throw new TypeError;throw t}).then(n=>(e(h,()=>h(n))||p(n),t.add(n),n))}return new Promise((e,n)=>{const o=()=>{try{(t=>{const{port1:e}=new MessageChannel;e.postMessage(t,[t])})(_)}catch{}},r=t=>{n(t),o()};try{m.decodeAudioData(_,n=>{"function"!=typeof n.copyFromChannel&&(d(n),Object(s.a)(n)),t.add(n),o(),e(n)},t=>{r(null===t?i():t)})}catch(t){r(t)}})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(24);const i=(t,e,n)=>function i(o,r){const a=Object(s.a)(r)?r:n(t,r);if((t=>"delayTime"in t)(a))return[];if(o[0]===a)return[o];if(o.includes(a))return[];const{outputs:c}=e(a);return Array.from(c).map(t=>i([...o,a],t[0])).reduce((t,e)=>t.concat(e),[])}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(37);const i={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},o=(t,e,n,o,r)=>class extends t{constructor(t,a){const c=o(t),u=r(c),h={...i,...a},l=e(c,u?null:t.baseLatency,h);super(t,!1,l,u?n(h.feedback,h.feedforward):null),(t=>{var e;t.getFrequencyResponse=(e=t.getFrequencyResponse,(n,i,o)=>{if(n.length!==i.length||i.length!==o.length)throw Object(s.a)();return e.call(t,n,i,o)})})(l),this._nativeIIRFilterNode=l}getFrequencyResponse(t,e,n){return this._nativeIIRFilterNode.getFrequencyResponse(t,e,n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o)=>(r,a,c,u,h,l)=>{if(null!==c)try{const n=e(r,t=>new c(t,u,l)),i=new Map;let a=null;if(Object.defineProperties(n,{channelCount:{get:()=>l.channelCount,set:()=>{throw t()}},channelCountMode:{get:()=>"explicit",set:()=>{throw t()}},onprocessorerror:{get:()=>a,set:t=>{"function"==typeof a&&n.removeEventListener("processorerror",a),a="function"==typeof t?t:null,"function"==typeof a&&n.addEventListener("processorerror",a)}}}),n.addEventListener=(p=n.addEventListener,(...t)=>{if("processorerror"===t[0]){const e="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;if(null!==e){const n=i.get(t[1]);void 0!==n?t[1]=n:(t[1]=n=>{e(new ErrorEvent(t[0],{...n,error:new Error}))},i.set(e,t[1]))}}return p.call(n,t[0],t[1],t[2])}),n.removeEventListener=(d=n.removeEventListener,(...t)=>{if("processorerror"===t[0]){const e=i.get(t[1]);void 0!==e&&(i.delete(t[1]),t[1]=e)}return d.call(n,t[0],t[1],t[2])}),0!==l.numberOfOutputs){const t=s(r,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return n.connect(t).connect(t.context.destination),o(n,()=>t.disconnect(),()=>t.connect(t.context.destination))}return n}catch(t){if(11===t.code)throw i();throw t}var d,p;if(void 0===h)throw i();return(t=>{const{port1:e}=new MessageChannel;try{e.postMessage(t)}finally{e.close()}})(l),n(r,a,h,l)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(7);const o=t=>(e,n)=>{const o=t(e,t=>t.createChannelSplitter(n.numberOfOutputs));return Object(s.a)(o,n),(t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw Object(i.a)()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:t=>{if("explicit"!==t)throw Object(i.a)()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:t=>{if("discrete"!==t)throw Object(i.a)()}})})(o),o}},function(t,e,n){var s=n(677),i=n(678),o=n(679),r=n(681);t.exports=function(t,e){return s(t)||i(t,e)||o(t,e)||r()}},function(t,e){t.exports=function(t){if(Array.isArray(t))return t}},function(t,e){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var n=[],s=!0,i=!1,o=void 0;try{for(var r,a=t[Symbol.iterator]();!(s=(r=a.next()).done)&&(n.push(r.value),!e||n.length!==e);s=!0);}catch(t){i=!0,o=t}finally{try{s||null==a.return||a.return()}finally{if(i)throw o}}return n}}},function(t,e,n){var s=n(680);t.exports=function(t,e){if(t){if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(t,e):void 0}}},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,s=new Array(e);n=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}function S(t,e,n,s){return new(n||(n=Promise))((function(i,o){function r(t){try{c(s.next(t))}catch(t){o(t)}}function a(t){try{c(s.throw(t))}catch(t){o(t)}}function c(t){t.done?i(t.value):new n((function(e){e(t.value)})).then(r,a)}c((s=s.apply(t,e||[])).next())}))}class C{constructor(t,e,n){this._callback=t,this._type=e,this._updateInterval=n,this._createClock()}_createWorker(){const t=new Blob([`\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime =  ${(1e3*this._updateInterval).toFixed(1)};\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t`],{type:"text/javascript"}),e=URL.createObjectURL(t),n=new Worker(e);n.onmessage=this._callback.bind(this),this._worker=n}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},1e3*this._updateInterval)}_createClock(){if("worker"===this._type)try{this._createWorker()}catch(t){this._type="timeout",this._createClock()}else"timeout"===this._type&&this._createTimeout()}_disposeClock(){this._timeout&&(clearTimeout(this._timeout),this._timeout=0),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(t){this._updateInterval=Math.max(t,128/44100),"worker"===this._type&&this._worker.postMessage(Math.max(1e3*t,1))}get type(){return this._type}set type(t){this._disposeClock(),this._type=t,this._createClock()}dispose(){this._disposeClock()}}function k(t){return Object(o.isAnyAudioParam)(t)}function A(t){return Object(o.isAnyAudioNode)(t)}function D(t){return Object(o.isAnyOfflineAudioContext)(t)}function M(t){return Object(o.isAnyAudioContext)(t)}function j(t){return t instanceof AudioBuffer}function E(t,e){return"value"===t||k(e)||A(e)||j(e)}function R(t,...e){if(!e.length)return t;const n=e.shift();if(g(t)&&g(n))for(const e in n)E(e,n[e])?t[e]=n[e]:g(n[e])?(t[e]||Object.assign(t,{[e]:{}}),R(t[e],n[e])):Object.assign(t,{[e]:n[e]});return R(t,...e)}function q(t,e,n=[],s){const i={},o=Array.from(e);if(g(o[0])&&s&&!Reflect.has(o[0],s)){Object.keys(o[0]).some(e=>Reflect.has(t,e))||(R(i,{[s]:o[0]}),n.splice(n.indexOf(s),1),o.shift())}if(1===o.length&&g(o[0]))R(i,o[0]);else for(let t=0;t{Reflect.has(t,e)&&delete t[e]}),t}
 /**
- *  Tone.js
- *  @author Yotam Mann
- *  @license http://opensource.org/licenses/MIT MIT License
- *  @copyright 2014-2019 Yotam Mann
- */n.prototype.toString=function(){for(var t in n){var e=t[0].match(/^[A-Z]$/),i=n[t]===this.constructor;if(n.isFunction(n[t])&&e&&i)return t}return"Tone"},n.prototype.dispose=function(){return this},n.prototype.set=function(t,e){if(n.isString(t)){var i={};i[t]=e,t=i}t:for(var s in t){e=t[s];var o=this;if(-1!==s.indexOf(".")){for(var a=s.split("."),r=0;r1&&(this.input=new Array(t)),1===e?this.output=this.context.createGain():e>1&&(this.output=new Array(e))},Object.defineProperty(s.default.AudioNode.prototype,"channelCount",{get:function(){return this.output.channelCount},set:function(t){return this.output.channelCount=t}}),Object.defineProperty(s.default.AudioNode.prototype,"channelCountMode",{get:function(){return this.output.channelCountMode},set:function(t){return this.output.channelCountMode=t}}),Object.defineProperty(s.default.AudioNode.prototype,"channelInterpretation",{get:function(){return this.output.channelInterpretation},set:function(t){return this.output.channelInterpretation=t}}),Object.defineProperty(s.default.AudioNode.prototype,"numberOfInputs",{get:function(){return this.input?s.default.isArray(this.input)?this.input.length:1:0}}),Object.defineProperty(s.default.AudioNode.prototype,"numberOfOutputs",{get:function(){return this.output?s.default.isArray(this.output)?this.output.length:1:0}}),s.default.AudioNode.prototype.connect=function(t,e,i){return s.default.isArray(this.output)?(e=s.default.defaultArg(e,0),this.output[e].connect(t,0,i)):s.default.connect(this.output,t,e,i),this},s.default.AudioNode.prototype.disconnect=function(t,e,i){return s.default.isArray(this.output)?(e=s.default.defaultArg(e,0),this.output[e].disconnect(t,0,i)):s.default.disconnect(this.output,t,e,i),this},s.default.AudioNode.prototype.chain=function(){var t=Array.from(arguments);return t.unshift(this),s.default.connectSeries.apply(void 0,t),this},s.default.AudioNode.prototype.fan=function(){for(var t=0;t0){var i=this._state.get(e);if(i&&i.state===s.default.State.Started&&i.time!==e){var n,o=e-this.toSeconds(i.time);i.duration&&(n=this.toSeconds(i.duration)-o),this._start(t,this.toSeconds(i.offset)+o,n)}}}.bind(this),this._syncedStop=function(t){var e=s.default.Transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));this._state.getValueAtTime(e)===s.default.State.Started&&this._stop(t)}.bind(this),s.default.Transport.on("start loopStart",this._syncedStart),s.default.Transport.on("stop pause loopEnd",this._syncedStop),this},s.default.Source.prototype.unsync=function(){this._synced&&(s.default.Transport.off("stop pause loopEnd",this._syncedStop),s.default.Transport.off("start loopStart",this._syncedStart)),this._synced=!1;for(var t=0;t0}}),Object.defineProperty(s.default.Buffer.prototype,"duration",{get:function(){return this._buffer?this._buffer.duration:0}}),Object.defineProperty(s.default.Buffer.prototype,"length",{get:function(){return this._buffer?this._buffer.length:0}}),Object.defineProperty(s.default.Buffer.prototype,"numberOfChannels",{get:function(){return this._buffer?this._buffer.numberOfChannels:0}}),s.default.Buffer.prototype.fromArray=function(t){var e=t[0].length>0,i=e?t.length:1,s=e?t[0].length:t.length,n=this.context.createBuffer(i,s,this.context.sampleRate);e||1!==i||(t=[t]);for(var o=0;o0&&e%this._ppq!=0&&e%(2*this._swingTicks)!=0){var i=e%(2*this._swingTicks)/(2*this._swingTicks),n=Math.sin(i*Math.PI)*this._swingAmount;t+=s.default.Ticks(2*this._swingTicks/3).toSeconds()*n}this.loop&&e>=this._loopEnd&&(this.emit("loopEnd",t),this._clock.setTicksAtTime(this._loopStart,t),e=this._loopStart,this.emit("loopStart",t,this._clock.getSecondsAtTime(t)),this.emit("loop",t)),this._timeline.forEachAtTime(e,function(e){e.invoke(t)})},s.default.Transport.prototype.schedule=function(t,e){var i=new s.default.TransportEvent(this,{time:s.default.TransportTime(e),callback:t});return this._addEvent(i,this._timeline)},s.default.Transport.prototype.scheduleRepeat=function(t,e,i,n){var o=new s.default.TransportRepeatEvent(this,{callback:t,interval:s.default.Time(e),time:s.default.TransportTime(i),duration:s.default.Time(s.default.defaultArg(n,1/0))});return this._addEvent(o,this._repeatedEvents)},s.default.Transport.prototype.scheduleOnce=function(t,e){var i=new s.default.TransportEvent(this,{time:s.default.TransportTime(e),callback:t,once:!0});return this._addEvent(i,this._timeline)},s.default.Transport.prototype.clear=function(t){if(this._scheduledEvents.hasOwnProperty(t)){var e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this},s.default.Transport.prototype._addEvent=function(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id},s.default.Transport.prototype.cancel=function(t){return t=s.default.defaultArg(t,0),t=this.toTicks(t),this._timeline.forEachFrom(t,function(t){this.clear(t.id)}.bind(this)),this._repeatedEvents.forEachFrom(t,function(t){this.clear(t.id)}.bind(this)),this},s.default.Transport.prototype._bindClockEvents=function(){this._clock.on("start",function(t,e){e=s.default.Ticks(e).toSeconds(),this.emit("start",t,e)}.bind(this)),this._clock.on("stop",function(t){this.emit("stop",t)}.bind(this)),this._clock.on("pause",function(t){this.emit("pause",t)}.bind(this))},Object.defineProperty(s.default.Transport.prototype,"state",{get:function(){return this._clock.getStateAtTime(this.now())}}),s.default.Transport.prototype.start=function(t,e){return s.default.isDefined(e)&&(e=this.toTicks(e)),this._clock.start(t,e),this},s.default.Transport.prototype.stop=function(t){return this._clock.stop(t),this},s.default.Transport.prototype.pause=function(t){return this._clock.pause(t),this},s.default.Transport.prototype.toggle=function(t){return t=this.toSeconds(t),this._clock.getStateAtTime(t)!==s.default.State.Started?this.start(t):this.stop(t),this},Object.defineProperty(s.default.Transport.prototype,"timeSignature",{get:function(){return this._timeSignature},set:function(t){s.default.isArray(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}}),Object.defineProperty(s.default.Transport.prototype,"loopStart",{get:function(){return s.default.Ticks(this._loopStart).toSeconds()},set:function(t){this._loopStart=this.toTicks(t)}}),Object.defineProperty(s.default.Transport.prototype,"loopEnd",{get:function(){return s.default.Ticks(this._loopEnd).toSeconds()},set:function(t){this._loopEnd=this.toTicks(t)}}),s.default.Transport.prototype.setLoopPoints=function(t,e){return this.loopStart=t,this.loopEnd=e,this},Object.defineProperty(s.default.Transport.prototype,"swing",{get:function(){return this._swingAmount},set:function(t){this._swingAmount=t}}),Object.defineProperty(s.default.Transport.prototype,"swingSubdivision",{get:function(){return s.default.Ticks(this._swingTicks).toNotation()},set:function(t){this._swingTicks=this.toTicks(t)}}),Object.defineProperty(s.default.Transport.prototype,"position",{get:function(){var t=this.now(),e=this._clock.getTicksAtTime(t);return s.default.Ticks(e).toBarsBeatsSixteenths()},set:function(t){var e=this.toTicks(t);this.ticks=e}}),Object.defineProperty(s.default.Transport.prototype,"seconds",{get:function(){return this._clock.seconds},set:function(t){var e=this.now(),i=this.bpm.timeToTicks(t,e);this.ticks=i}}),Object.defineProperty(s.default.Transport.prototype,"progress",{get:function(){if(this.loop){var t=this.now();return(this._clock.getTicksAtTime(t)-this._loopStart)/(this._loopEnd-this._loopStart)}return 0}}),Object.defineProperty(s.default.Transport.prototype,"ticks",{get:function(){return this._clock.ticks},set:function(t){if(this._clock.ticks!==t){var e=this.now();this.state===s.default.State.Started?(this.emit("stop",e),this._clock.setTicksAtTime(t,e),this.emit("start",e,this.seconds)):this._clock.setTicksAtTime(t,e)}}}),s.default.Transport.prototype.getTicksAtTime=function(t){return Math.round(this._clock.getTicksAtTime(t))},s.default.Transport.prototype.getSecondsAtTime=function(t){return this._clock.getSecondsAtTime(t)},Object.defineProperty(s.default.Transport.prototype,"PPQ",{get:function(){return this._ppq},set:function(t){var e=this.bpm.value;this._ppq=t,this.bpm.value=e}}),s.default.Transport.prototype._fromUnits=function(t){return 1/(60/t/this.PPQ)},s.default.Transport.prototype._toUnits=function(t){return t/this.PPQ*60},s.default.Transport.prototype.nextSubdivision=function(t){if(t=this.toTicks(t),this.state!==s.default.State.Started)return 0;var e=this.now(),i=t-this.getTicksAtTime(e)%t;return this._clock.nextTickTime(i,e)},s.default.Transport.prototype.syncSignal=function(t,e){if(!e){var i=this.now();e=0!==t.getValueAtTime(i)?t.getValueAtTime(i)/this.bpm.getValueAtTime(i):0}var n=new s.default.Gain(e);return this.bpm.chain(n,t._param),this._syncedSignals.push({ratio:n,signal:t,initial:t.value}),t.value=0,this},s.default.Transport.prototype.unsyncSignal=function(t){for(var e=this._syncedSignals.length-1;e>=0;e--){var i=this._syncedSignals[e];i.signal===t&&(i.ratio.dispose(),i.signal.value=i.initial,this._syncedSignals.splice(e,1))}return this},s.default.Transport.prototype.dispose=function(){return s.default.Emitter.prototype.dispose.call(this),this._clock.dispose(),this._clock=null,this._writable("bpm"),this.bpm=null,this._timeline.dispose(),this._timeline=null,this._repeatedEvents.dispose(),this._repeatedEvents=null,this};var n=s.default.Transport;s.default.Transport=new n,s.default.Context.on("init",function(t){t.transport&&t.transport.isTransport?s.default.Transport=t.transport:s.default.Transport=new n}),s.default.Context.on("close",function(t){t.transport&&t.transport.isTransport&&t.transport.dispose()}),e.default=s.default.Transport},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2),i(6),i(16),i(64);s.default.Oscillator=function(){var t=s.default.defaults(arguments,["frequency","type"],s.default.Oscillator);s.default.Source.call(this,t),this._oscillator=null,this.frequency=new s.default.Signal(t.frequency,s.default.Type.Frequency),this.detune=new s.default.Signal(t.detune,s.default.Type.Cents),this._wave=null,this._partials=t.partials,this._partialCount=t.partialCount,this._phase=t.phase,this._type=t.type,t.partialCount&&t.type!==s.default.Oscillator.Type.Custom&&(this._type=this.baseType+t.partialCount.toString()),this.phase=this._phase,this._readOnly(["frequency","detune"])},s.default.extend(s.default.Oscillator,s.default.Source),s.default.Oscillator.defaults={type:"sine",frequency:440,detune:0,phase:0,partials:[],partialCount:0},s.default.Oscillator.Type={Sine:"sine",Triangle:"triangle",Sawtooth:"sawtooth",Square:"square",Custom:"custom"},s.default.Oscillator.prototype._start=function(t){this.log("start",t);var e=new s.default.OscillatorNode;this._oscillator=e,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),t=this.toSeconds(t),this._oscillator.start(t)},s.default.Oscillator.prototype._stop=function(t){return this.log("stop",t),this._oscillator&&(t=this.toSeconds(t),this._oscillator.stop(t)),this},s.default.Oscillator.prototype.restart=function(t){return this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(this.toSeconds(t)),this},s.default.Oscillator.prototype.syncFrequency=function(){return s.default.Transport.syncSignal(this.frequency),this},s.default.Oscillator.prototype.unsyncFrequency=function(){return s.default.Transport.unsyncSignal(this.frequency),this},Object.defineProperty(s.default.Oscillator.prototype,"type",{get:function(){return this._type},set:function(t){var e=[s.default.Oscillator.Type.Sine,s.default.Oscillator.Type.Square,s.default.Oscillator.Type.Triangle,s.default.Oscillator.Type.Sawtooth].includes(t);if(0===this._phase&&e)this._wave=null,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{var i=this._getRealImaginary(t,this._phase),n=this.context.createPeriodicWave(i[0],i[1]);this._wave=n,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}this._type=t}}),Object.defineProperty(s.default.Oscillator.prototype,"baseType",{get:function(){return this._type.replace(this.partialCount,"")},set:function(t){this.partialCount&&this._type!==s.default.Oscillator.Type.Custom&&t!==s.default.Oscillator.Type.Custom?this.type=t+this.partialCount:this.type=t}}),Object.defineProperty(s.default.Oscillator.prototype,"partialCount",{get:function(){return this._partialCount},set:function(t){var e=this._type,i=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);i&&(e=i[1]),this._type!==s.default.Oscillator.Type.Custom&&(this.type=0===t?e:e+t.toString())}}),s.default.Oscillator.prototype.get=function(){var t=s.default.prototype.get.apply(this,arguments);return t.type!==s.default.Oscillator.Type.Custom&&delete t.partials,t},s.default.Oscillator.prototype._getRealImaginary=function(t,e){var i=2048,n=new Float32Array(i),o=new Float32Array(i),a=1;if(t===s.default.Oscillator.Type.Custom)a=this._partials.length+1,this._partialCount=this._partials.length,i=a;else{var r=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(t);r?(a=parseInt(r[2])+1,this._partialCount=parseInt(r[2]),t=r[1],i=a=Math.max(a,2)):this._partialCount=0,this._partials=[]}for(var l=1;l>1&1?-1:1):0,this._partials[l-1]=u;break;case s.default.Oscillator.Type.Custom:u=this._partials[l-1];break;default:throw new TypeError("Tone.Oscillator: invalid type: "+t)}0!==u?(n[l]=-u*Math.sin(e*l),o[l]=u*Math.cos(e*l)):(n[l]=0,o[l]=0)}return[n,o]},s.default.Oscillator.prototype._inverseFFT=function(t,e,i){for(var s=0,n=t.length,o=0;othis.memory){var i=this.length-this.memory;this._timeline.splice(0,i)}return this},s.default.Timeline.prototype.remove=function(t){var e=this._timeline.indexOf(t);return-1!==e&&this._timeline.splice(e,1),this},s.default.Timeline.prototype.get=function(t,e){e=s.default.defaultArg(e,"time");var i=this._search(t,e);return-1!==i?this._timeline[i]:null},s.default.Timeline.prototype.peek=function(){return this._timeline[0]},s.default.Timeline.prototype.shift=function(){return this._timeline.shift()},s.default.Timeline.prototype.getAfter=function(t,e){e=s.default.defaultArg(e,"time");var i=this._search(t,e);return i+10&&this._timeline[i-1][e]=0?this._timeline[n-1]:null},s.default.Timeline.prototype.cancel=function(t){if(this._timeline.length>1){var e=this._search(t);if(e>=0)if(this._timeline[e].time===t){for(var i=e;i>=0&&this._timeline[i].time===t;i--)e=i;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&this._timeline[0].time>=t&&(this._timeline=[]);return this},s.default.Timeline.prototype.cancelBefore=function(t){var e=this._search(t);return e>=0&&(this._timeline=this._timeline.slice(e+1)),this},s.default.Timeline.prototype.previousEvent=function(t){var e=this._timeline.indexOf(t);return e>0?this._timeline[e-1]:null},s.default.Timeline.prototype._search=function(t,e){if(0===this._timeline.length)return-1;e=s.default.defaultArg(e,"time");var i=0,n=this._timeline.length,o=n;if(n>0&&this._timeline[n-1][e]<=t)return n-1;for(;it)return a;r[e]>t?o=a:i=a+1}return-1},s.default.Timeline.prototype._iterate=function(t,e,i){e=s.default.defaultArg(e,0),i=s.default.defaultArg(i,this._timeline.length-1),this._timeline.slice(e,i+1).forEach(function(e){t.call(this,e)}.bind(this))},s.default.Timeline.prototype.forEach=function(t){return this._iterate(t),this},s.default.Timeline.prototype.forEachBefore=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(e,0,i),this},s.default.Timeline.prototype.forEachAfter=function(t,e){var i=this._search(t);return this._iterate(e,i+1),this},s.default.Timeline.prototype.forEachBetween=function(t,e,i){var s=this._search(t),n=this._search(e);return-1!==s&&-1!==n?(this._timeline[s].time!==t&&(s+=1),this._timeline[n].time===e&&(n-=1),this._iterate(i,s,n)):-1===s&&this._iterate(i,0,n),this},s.default.Timeline.prototype.forEachFrom=function(t,e){for(var i=this._search(t);i>=0&&this._timeline[i].time>=t;)i--;return this._iterate(e,i+1),this},s.default.Timeline.prototype.forEachAtTime=function(t,e){var i=this._search(t);return-1!==i&&this._iterate(function(i){i.time===t&&e.call(this,i)},0,i),this},s.default.Timeline.prototype.dispose=function(){return s.default.prototype.dispose.call(this),this._timeline=null,this},e.default=s.default.Timeline},function(t,e,i){"use strict";i.r(e);var s=i(0);i(21),i(2);s.default.Monophonic=function(t){t=s.default.defaultArg(t,s.default.Monophonic.defaults),s.default.Instrument.call(this,t),this.portamento=t.portamento},s.default.extend(s.default.Monophonic,s.default.Instrument),s.default.Monophonic.defaults={portamento:0},s.default.Monophonic.prototype.triggerAttack=function(t,e,i){return this.log("triggerAttack",t,e,i),e=this.toSeconds(e),this._triggerEnvelopeAttack(e,i),this.setNote(t,e),this},s.default.Monophonic.prototype.triggerRelease=function(t){return this.log("triggerRelease",t),t=this.toSeconds(t),this._triggerEnvelopeRelease(t),this},s.default.Monophonic.prototype._triggerEnvelopeAttack=function(){},s.default.Monophonic.prototype._triggerEnvelopeRelease=function(){},s.default.Monophonic.prototype.getLevelAtTime=function(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)},s.default.Monophonic.prototype.setNote=function(t,e){if(e=this.toSeconds(e),this.portamento>0&&this.getLevelAtTime(e)>.05){var i=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(t,i,e)}else this.frequency.setValueAtTime(t,e);return this},e.default=s.default.Monophonic},function(t,e,i){"use strict";i.r(e);var s=i(0);i(29),i(5),i(2);s.default.Scale=function(t,e){s.default.SignalBase.call(this),this._outputMin=s.default.defaultArg(t,0),this._outputMax=s.default.defaultArg(e,1),this._scale=this.input=new s.default.Multiply(1),this._add=this.output=new s.default.Add(0),this._scale.connect(this._add),this._setRange()},s.default.extend(s.default.Scale,s.default.SignalBase),Object.defineProperty(s.default.Scale.prototype,"min",{get:function(){return this._outputMin},set:function(t){this._outputMin=t,this._setRange()}}),Object.defineProperty(s.default.Scale.prototype,"max",{get:function(){return this._outputMax},set:function(t){this._outputMax=t,this._setRange()}}),s.default.Scale.prototype._setRange=function(){this._add.value=this._outputMin,this._scale.value=this._outputMax-this._outputMin},s.default.Scale.prototype.dispose=function(){return s.default.SignalBase.prototype.dispose.call(this),this._add.dispose(),this._add=null,this._scale.dispose(),this._scale=null,this},e.default=s.default.Scale},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2),i(3),i(1);s.default.Volume=function(){var t=s.default.defaults(arguments,["volume"],s.default.Volume);s.default.AudioNode.call(this,t),this.output=this.input=new s.default.Gain(t.volume,s.default.Type.Decibels),this._unmutedVolume=t.volume,this.volume=this.output.gain,this._readOnly("volume"),this.mute=t.mute},s.default.extend(s.default.Volume,s.default.AudioNode),s.default.Volume.defaults={volume:0,mute:!1},Object.defineProperty(s.default.Volume.prototype,"mute",{get:function(){return this.volume.value===-1/0},set:function(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}}),s.default.Volume.prototype.dispose=function(){return this.input.dispose(),s.default.AudioNode.prototype.dispose.call(this),this._writable("volume"),this.volume.dispose(),this.volume=null,this},e.default=s.default.Volume},function(t,e,i){"use strict";i.r(e);var s=i(0);i(3),i(30);s.default.Zero=function(){s.default.SignalBase.call(this),this._gain=this.input=this.output=new s.default.Gain,s.default.connect(this.context.getConstant(0),this._gain)},s.default.extend(s.default.Zero,s.default.SignalBase),s.default.Zero.prototype.dispose=function(){return s.default.SignalBase.prototype.dispose.call(this),this._gain.dispose(),this._gain=null,this},e.default=s.default.Zero},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2),i(3);s.default.Add=function(t){s.default.Signal.call(this),this.createInsOuts(2,0),this._sum=this.input[0]=this.input[1]=this.output=new s.default.Gain,this._param=this.input[1]=new s.default.Signal(t),this._param.connect(this._sum)},s.default.extend(s.default.Add,s.default.Signal),s.default.Add.prototype.dispose=function(){return s.default.Signal.prototype.dispose.call(this),this._sum.dispose(),this._sum=null,this},e.default=s.default.Add},function(t,e,i){"use strict";i.r(e);var s=i(0);i(1);s.default.SignalBase=function(){s.default.AudioNode.call(this)},s.default.extend(s.default.SignalBase,s.default.AudioNode),s.default.SignalBase.prototype.connect=function(t,e,i){return s.default.Signal&&s.default.Signal===t.constructor||s.default.Param&&s.default.Param===t.constructor?(t._param.cancelScheduledValues(0),t._param.setValueAtTime(0,0),t.overridden=!0):t instanceof AudioParam&&(t.cancelScheduledValues(0),t.setValueAtTime(0,0)),s.default.AudioNode.prototype.connect.call(this,t,e,i),this},e.default=s.default.SignalBase},function(t,e,i){"use strict";i.r(e);var s=i(0);i(47),i(3);s.default.AmplitudeEnvelope=function(){s.default.Envelope.apply(this,arguments),this.input=this.output=new s.default.Gain,this._sig.connect(this.output.gain)},s.default.extend(s.default.AmplitudeEnvelope,s.default.Envelope),s.default.AmplitudeEnvelope.prototype.dispose=function(){return s.default.Envelope.prototype.dispose.call(this),this},e.default=s.default.AmplitudeEnvelope},function(t,e,i){"use strict";i.r(e);var s=i(0);i(11),i(6),i(3),i(1);s.default.BufferSource=function(){var t=s.default.defaults(arguments,["buffer","onload"],s.default.BufferSource);s.default.AudioNode.call(this,t),this.onended=t.onended,this._startTime=-1,this._sourceStarted=!1,this._sourceStopped=!1,this._stopTime=-1,this._gainNode=this.output=new s.default.Gain(0),this._source=this.context.createBufferSource(),s.default.connect(this._source,this._gainNode),this._source.onended=this._onended.bind(this),this._buffer=new s.default.Buffer(t.buffer,t.onload),this.playbackRate=new s.default.Param({param:this._source.playbackRate,units:s.default.Type.Positive,value:t.playbackRate}),this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut,this.curve=t.curve,this._onendedTimeout=-1,this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd},s.default.extend(s.default.BufferSource,s.default.AudioNode),s.default.BufferSource.defaults={onended:s.default.noOp,onload:s.default.noOp,loop:!1,loopStart:0,loopEnd:0,fadeIn:0,fadeOut:0,curve:"linear",playbackRate:1},Object.defineProperty(s.default.BufferSource.prototype,"state",{get:function(){return this.getStateAtTime(this.now())}}),s.default.BufferSource.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),-1!==this._startTime&&this._startTime<=t&&(-1===this._stopTime||t0?(this._gainNode.gain.setValueAtTime(0,t),"linear"===this.curve?this._gainNode.gain.linearRampToValueAtTime(n,t+o):this._gainNode.gain.exponentialApproachValueAtTime(n,t,o)):this._gainNode.gain.setValueAtTime(n,t),this._startTime=t,s.default.isDefined(i)){var a=this.toSeconds(i);a=Math.max(a,0),this.stop(t+a)}if(this.loop){var r=this.loopEnd||this.buffer.duration,l=this.loopStart;e>=r&&(e=(e-l)%(r-l)+l)}return this._source.buffer=this.buffer.get(),this._source.loopEnd=this.loopEnd||this.buffer.duration,e0?"linear"===this.curve?this._gainNode.gain.linearRampTo(0,e,t):this._gainNode.gain.targetRampTo(0,e,t):(this._gainNode.gain.cancelAndHoldAtTime(t),this._gainNode.gain.setValueAtTime(0,t)),s.default.context.clearTimeout(this._onendedTimeout),this._onendedTimeout=s.default.context.setTimeout(this._onended.bind(this),this._stopTime-this.now()),this},s.default.BufferSource.prototype.cancelStop=function(){if(-1!==this._startTime&&!this._sourceStopped){var t=this.toSeconds(this.fadeIn);this._gainNode.gain.cancelScheduledValues(this._startTime+t+this.sampleTime),this.context.clearTimeout(this._onendedTimeout),this._stopTime=-1}return this},s.default.BufferSource.prototype._onended=function(){if(!this._sourceStopped){this._sourceStopped=!0;var t="exponential"===this.curve?2*this.fadeOut:0;this._sourceStarted&&-1!==this._stopTime&&this._source.stop(this._stopTime+t),this.onended(this),setTimeout(function(){this._source&&(this._source.disconnect(),this._gainNode.disconnect())}.bind(this),1e3*t+100)}},Object.defineProperty(s.default.BufferSource.prototype,"loopStart",{get:function(){return this._source.loopStart},set:function(t){this._source.loopStart=this.toSeconds(t)}}),Object.defineProperty(s.default.BufferSource.prototype,"loopEnd",{get:function(){return this._source.loopEnd},set:function(t){this._source.loopEnd=this.toSeconds(t)}}),Object.defineProperty(s.default.BufferSource.prototype,"buffer",{get:function(){return this._buffer},set:function(t){this._buffer.set(t)}}),Object.defineProperty(s.default.BufferSource.prototype,"loop",{get:function(){return this._source.loop},set:function(t){this._source.loop=t,this.cancelStop()}}),s.default.BufferSource.prototype.dispose=function(){return this._wasDisposed||(this._wasDisposed=!0,s.default.AudioNode.prototype.dispose.call(this),this.onended=null,this._source.onended=null,this._source.disconnect(),this._source=null,this._gainNode.dispose(),this._gainNode=null,this._buffer.dispose(),this._buffer=null,this._startTime=-1,this.playbackRate=null,s.default.context.clearTimeout(this._onendedTimeout)),this},e.default=s.default.BufferSource},function(t,e,i){"use strict";i.r(e);var s=i(0);i(8),i(2),i(5),i(3);s.default.FeedbackEffect=function(){var t=s.default.defaults(arguments,["feedback"],s.default.FeedbackEffect);s.default.Effect.call(this,t),this._feedbackGain=new s.default.Gain(t.feedback,s.default.Type.NormalRange),this.feedback=this._feedbackGain.gain,this.effectReturn.chain(this._feedbackGain,this.effectSend),this._readOnly(["feedback"])},s.default.extend(s.default.FeedbackEffect,s.default.Effect),s.default.FeedbackEffect.defaults={feedback:.125},s.default.FeedbackEffect.prototype.dispose=function(){return s.default.Effect.prototype.dispose.call(this),this._writable(["feedback"]),this._feedbackGain.dispose(),this._feedbackGain=null,this.feedback=null,this},e.default=s.default.FeedbackEffect},function(t,e,i){"use strict";i.r(e);var s=i(0);i(24),i(4);s.default.TimelineState=function(t){s.default.Timeline.call(this),this._initial=t},s.default.extend(s.default.TimelineState,s.default.Timeline),s.default.TimelineState.prototype.getValueAtTime=function(t){var e=this.get(t);return null!==e?e.state:this._initial},s.default.TimelineState.prototype.setStateAtTime=function(t,e){return this.add({state:t,time:e}),this},s.default.TimelineState.prototype.getLastState=function(t,e){e=this.toSeconds(e);for(var i=this._search(e);i>=0;i--){var s=this._timeline[i];if(s.state===t)return s}},s.default.TimelineState.prototype.getNextState=function(t,e){e=this.toSeconds(e);var i=this._search(e);if(-1!==i)for(var s=i;s0&&(i=(1-o)/(1/i));if(0===i)this._sig.setValueAtTime(e,t);else if("linear"===this._attackCurve)this._sig.linearRampTo(e,i,t);else if("exponential"===this._attackCurve)this._sig.targetRampTo(e,i,t);else if(i>0){this._sig.cancelAndHoldAtTime(t);for(var a=this._attackCurve,r=1;r0){var i=this.toSeconds(this.release);if("linear"===this._releaseCurve)this._sig.linearRampTo(0,i,t);else if("exponential"===this._releaseCurve)this._sig.targetRampTo(0,i,t);else{var n=this._releaseCurve;s.default.isArray(n)&&(this._sig.cancelAndHoldAtTime(t),this._sig.setValueCurveAtTime(n,t,i,e))}}return this},s.default.Envelope.prototype.getValueAtTime=function(t){return this._sig.getValueAtTime(t)},s.default.Envelope.prototype.triggerAttackRelease=function(t,e,i){return e=this.toSeconds(e),this.triggerAttack(e,i),this.triggerRelease(e+this.toSeconds(t)),this},s.default.Envelope.prototype.cancel=function(t){return this._sig.cancelScheduledValues(t),this},s.default.Envelope.prototype.connect=s.default.SignalBase.prototype.connect,function(){var t,e,i=[];for(t=0;t<128;t++)i[t]=Math.sin(t/127*(Math.PI/2));var n=[];for(t=0;t<127;t++){e=t/127;var o=Math.sin(e*(2*Math.PI)*6.4-Math.PI/2)+1;n[t]=o/10+.83*e}n[127]=1;var a=[];for(t=0;t<128;t++)a[t]=Math.ceil(t/127*5)/5;var r=[];for(t=0;t<128;t++)e=t/127,r[t]=.5*(1-Math.cos(Math.PI*e));var l,u=[];for(t=0;t<128;t++){e=t/127;var d=4*Math.pow(e,3)+.2,f=Math.cos(d*Math.PI*2*e);u[t]=Math.abs(f*(1-e))}function h(t){for(var e=new Array(t.length),i=0;i1){e=1/0,s.default.isNumber(this._loop)&&(e=this._loop*this._getLoopDuration());var n=this._state.getAfter(i);null!==n&&(e=Math.min(e,n.time-i)),e!==1/0&&(this._state.setStateAtTime(s.default.State.Stopped,i+e+1),e=s.default.Ticks(e));var o=s.default.Ticks(this._getLoopDuration());t.id=s.default.Transport.scheduleRepeat(this._tick.bind(this),o,s.default.Ticks(i),e)}else t.id=s.default.Transport.schedule(this._tick.bind(this),s.default.Ticks(i))}}.bind(this)),this},Object.defineProperty(s.default.Event.prototype,"state",{get:function(){return this._state.getValueAtTime(s.default.Transport.ticks)}}),Object.defineProperty(s.default.Event.prototype,"startOffset",{get:function(){return this._startOffset},set:function(t){this._startOffset=t}}),Object.defineProperty(s.default.Event.prototype,"probability",{get:function(){return this._probability},set:function(t){this._probability=t}}),Object.defineProperty(s.default.Event.prototype,"humanize",{get:function(){return this._humanize},set:function(t){this._humanize=t}}),s.default.Event.prototype.start=function(t){return t=this.toTicks(t),this._state.getValueAtTime(t)===s.default.State.Stopped&&(this._state.add({state:s.default.State.Started,time:t,id:void 0}),this._rescheduleEvents(t)),this},s.default.Event.prototype.stop=function(t){if(this.cancel(t),t=this.toTicks(t),this._state.getValueAtTime(t)===s.default.State.Started){this._state.setStateAtTime(s.default.State.Stopped,t);var e=this._state.getBefore(t),i=t;null!==e&&(i=e.time),this._rescheduleEvents(i)}return this},s.default.Event.prototype.cancel=function(t){return t=s.default.defaultArg(t,-1/0),t=this.toTicks(t),this._state.forEachFrom(t,function(t){s.default.Transport.clear(t.id)}),this._state.cancel(t),this},s.default.Event.prototype._tick=function(t){var e=s.default.Transport.getTicksAtTime(t);if(!this.mute&&this._state.getValueAtTime(e)===s.default.State.Started){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){var i=.02;s.default.isBoolean(this.humanize)||(i=this.toSeconds(this.humanize)),t+=(2*Math.random()-1)*i}this.callback(t,this.value)}},s.default.Event.prototype._getLoopDuration=function(){return Math.round((this._loopEnd-this._loopStart)/this._playbackRate)},Object.defineProperty(s.default.Event.prototype,"loop",{get:function(){return this._loop},set:function(t){this._loop=t,this._rescheduleEvents()}}),Object.defineProperty(s.default.Event.prototype,"playbackRate",{get:function(){return this._playbackRate},set:function(t){this._playbackRate=t,this._rescheduleEvents()}}),Object.defineProperty(s.default.Event.prototype,"loopEnd",{get:function(){return s.default.Ticks(this._loopEnd).toSeconds()},set:function(t){this._loopEnd=this.toTicks(t),this._loop&&this._rescheduleEvents()}}),Object.defineProperty(s.default.Event.prototype,"loopStart",{get:function(){return s.default.Ticks(this._loopStart).toSeconds()},set:function(t){this._loopStart=this.toTicks(t),this._loop&&this._rescheduleEvents()}}),Object.defineProperty(s.default.Event.prototype,"progress",{get:function(){if(this._loop){var t=s.default.Transport.ticks,e=this._state.get(t);if(null!==e&&e.state===s.default.State.Started){var i=this._getLoopDuration();return(t-e.time)%i/i}return 0}return 0}}),s.default.Event.prototype.dispose=function(){this.cancel(),this._state.dispose(),this._state=null,this.callback=null,this.value=null},e.default=s.default.Event},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2),i(13),i(29),i(10),i(3),i(1);s.default.MidSideMerge=function(){s.default.AudioNode.call(this),this.createInsOuts(2,0),this.mid=this.input[0]=new s.default.Gain,this._left=new s.default.Add,this._timesTwoLeft=new s.default.Multiply(Math.SQRT1_2),this.side=this.input[1]=new s.default.Gain,this._right=new s.default.Subtract,this._timesTwoRight=new s.default.Multiply(Math.SQRT1_2),this._merge=this.output=new s.default.Merge,this.mid.connect(this._left,0,0),this.side.connect(this._left,0,1),this.mid.connect(this._right,0,0),this.side.connect(this._right,0,1),this._left.connect(this._timesTwoLeft),this._right.connect(this._timesTwoRight),this._timesTwoLeft.connect(this._merge,0,0),this._timesTwoRight.connect(this._merge,0,1)},s.default.extend(s.default.MidSideMerge,s.default.AudioNode),s.default.MidSideMerge.prototype.dispose=function(){return s.default.AudioNode.prototype.dispose.call(this),this.mid.dispose(),this.mid=null,this.side.dispose(),this.side=null,this._left.dispose(),this._left=null,this._timesTwoLeft.dispose(),this._timesTwoLeft=null,this._right.dispose(),this._right=null,this._timesTwoRight.dispose(),this._timesTwoRight=null,this._merge.dispose(),this._merge=null,this},e.default=s.default.MidSideMerge},function(t,e,i){"use strict";i.r(e);var s=i(0);i(29),i(13),i(2),i(19),i(1);s.default.MidSideSplit=function(){s.default.AudioNode.call(this),this.createInsOuts(0,2),this._split=this.input=new s.default.Split,this._midAdd=new s.default.Add,this.mid=this.output[0]=new s.default.Multiply(Math.SQRT1_2),this._sideSubtract=new s.default.Subtract,this.side=this.output[1]=new s.default.Multiply(Math.SQRT1_2),this._split.connect(this._midAdd,0,0),this._split.connect(this._midAdd,1,1),this._split.connect(this._sideSubtract,0,0),this._split.connect(this._sideSubtract,1,1),this._midAdd.connect(this.mid),this._sideSubtract.connect(this.side)},s.default.extend(s.default.MidSideSplit,s.default.AudioNode),s.default.MidSideSplit.prototype.dispose=function(){return s.default.AudioNode.prototype.dispose.call(this),this.mid.dispose(),this.mid=null,this.side.dispose(),this.side=null,this._midAdd.dispose(),this._midAdd=null,this._sideSubtract.dispose(),this._sideSubtract=null,this._split.dispose(),this._split=null,this},e.default=s.default.MidSideSplit},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2),i(9),i(1),i(59);s.default.LowpassCombFilter=function(){var t=s.default.defaults(arguments,["delayTime","resonance","dampening"],s.default.LowpassCombFilter);s.default.AudioNode.call(this),this._combFilter=this.output=new s.default.FeedbackCombFilter(t.delayTime,t.resonance),this.delayTime=this._combFilter.delayTime,this._lowpass=this.input=new s.default.Filter({frequency:t.dampening,type:"lowpass",Q:0,rolloff:-12}),this.dampening=this._lowpass.frequency,this.resonance=this._combFilter.resonance,this._lowpass.connect(this._combFilter),this._readOnly(["dampening","resonance","delayTime"])},s.default.extend(s.default.LowpassCombFilter,s.default.AudioNode),s.default.LowpassCombFilter.defaults={delayTime:.1,resonance:.5,dampening:3e3},s.default.LowpassCombFilter.prototype.dispose=function(){return s.default.AudioNode.prototype.dispose.call(this),this._writable(["dampening","resonance","delayTime"]),this._combFilter.dispose(),this._combFilter=null,this.resonance=null,this.delayTime=null,this._lowpass.dispose(),this._lowpass=null,this.dampening=null,this},e.default=s.default.LowpassCombFilter},function(t,e,i){"use strict";i.r(e);var s=i(0);i(45);s.default.Ticks=function(t,e){if(!(this instanceof s.default.Ticks))return new s.default.Ticks(t,e);s.default.TransportTime.call(this,t,e)},s.default.extend(s.default.Ticks,s.default.TransportTime),s.default.Ticks.prototype._defaultUnits="i",s.default.Ticks.prototype._now=function(){return s.default.Transport.ticks},s.default.Ticks.prototype._beatsToUnits=function(t){return this._getPPQ()*t},s.default.Ticks.prototype._secondsToUnits=function(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())},s.default.Ticks.prototype._ticksToUnits=function(t){return t},s.default.Ticks.prototype.toTicks=function(){return this.valueOf()},s.default.Ticks.prototype.toSeconds=function(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())},e.default=s.default.Ticks},function(t,e,i){"use strict";i.r(e);var s=i(0);i(55);s.default.TransportEvent=function(t,e){e=s.default.defaultArg(e,s.default.TransportEvent.defaults),s.default.call(this),this.Transport=t,this.id=s.default.TransportEvent._eventId++,this.time=s.default.Ticks(e.time),this.callback=e.callback,this._once=e.once},s.default.extend(s.default.TransportEvent),s.default.TransportEvent.defaults={once:!1,callback:s.default.noOp},s.default.TransportEvent._eventId=0,s.default.TransportEvent.prototype.invoke=function(t){this.callback&&(this.callback(t),this._once&&this.Transport&&this.Transport.clear(this.id))},s.default.TransportEvent.prototype.dispose=function(){return s.default.prototype.dispose.call(this),this.Transport=null,this.callback=null,this.time=null,this},e.default=s.default.TransportEvent},function(t,e,i){"use strict";i.r(e);var s=i(0);i(82),i(34),i(24),i(14);s.default.TickSource=function(){var t=s.default.defaults(arguments,["frequency"],s.default.TickSource);this.frequency=new s.default.TickSignal(t.frequency),this._readOnly("frequency"),this._state=new s.default.TimelineState(s.default.State.Stopped),this._state.setStateAtTime(s.default.State.Stopped,0),this._tickOffset=new s.default.Timeline,this.setTicksAtTime(0,0)},s.default.extend(s.default.TickSource),s.default.TickSource.defaults={frequency:1},Object.defineProperty(s.default.TickSource.prototype,"state",{get:function(){return this._state.getValueAtTime(this.now())}}),s.default.TickSource.prototype.start=function(t,e){return t=this.toSeconds(t),this._state.getValueAtTime(t)!==s.default.State.Started&&(this._state.setStateAtTime(s.default.State.Started,t),s.default.isDefined(e)&&this.setTicksAtTime(e,t)),this},s.default.TickSource.prototype.stop=function(t){if(t=this.toSeconds(t),this._state.getValueAtTime(t)===s.default.State.Stopped){var e=this._state.get(t);e.time>0&&(this._tickOffset.cancel(e.time),this._state.cancel(e.time))}return this._state.cancel(t),this._state.setStateAtTime(s.default.State.Stopped,t),this.setTicksAtTime(0,t),this},s.default.TickSource.prototype.pause=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)===s.default.State.Started&&this._state.setStateAtTime(s.default.State.Paused,t),this},s.default.TickSource.prototype.cancel=function(t){return t=this.toSeconds(t),this._state.cancel(t),this._tickOffset.cancel(t),this},s.default.TickSource.prototype.getTicksAtTime=function(t){t=this.toSeconds(t);var e=this._state.getLastState(s.default.State.Stopped,t),i={state:s.default.State.Paused,time:t};this._state.add(i);var n=e,o=0;return this._state.forEachBetween(e.time,t+this.sampleTime,function(t){var e=n.time,i=this._tickOffset.get(t.time);i.time>=n.time&&(o=i.ticks,e=i.time),n.state===s.default.State.Started&&t.state!==s.default.State.Started&&(o+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e)),n=t}.bind(this)),this._state.remove(i),o},Object.defineProperty(s.default.TickSource.prototype,"ticks",{get:function(){return this.getTicksAtTime(this.now())},set:function(t){this.setTicksAtTime(t,this.now())}}),Object.defineProperty(s.default.TickSource.prototype,"seconds",{get:function(){return this.getSecondsAtTime(this.now())},set:function(t){var e=this.now(),i=this.frequency.timeToTicks(t,e);this.setTicksAtTime(i,e)}}),s.default.TickSource.prototype.getSecondsAtTime=function(t){t=this.toSeconds(t);var e=this._state.getLastState(s.default.State.Stopped,t),i={state:s.default.State.Paused,time:t};this._state.add(i);var n=e,o=0;return this._state.forEachBetween(e.time,t+this.sampleTime,function(t){var e=n.time,i=this._tickOffset.get(t.time);i.time>=n.time&&(o=i.seconds,e=i.time),n.state===s.default.State.Started&&t.state!==s.default.State.Started&&(o+=t.time-e),n=t}.bind(this)),this._state.remove(i),o},s.default.TickSource.prototype.setTicksAtTime=function(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({time:e,ticks:t,seconds:this.frequency.getDurationOfTicks(t,e)}),this},s.default.TickSource.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)},s.default.TickSource.prototype.getTimeOfTick=function(t,e){e=s.default.defaultArg(e,this.now());var i=this._tickOffset.get(e),n=this._state.get(e),o=Math.max(i.time,n.time),a=this.frequency.getTicksAtTime(o)+t-i.ticks;return this.frequency.getTimeOfTick(a)},s.default.TickSource.prototype.forEachTickBetween=function(t,e,i){var n=this._state.get(t);if(this._state.forEachBetween(t,e,function(e){n.state===s.default.State.Started&&e.state!==s.default.State.Started&&this.forEachTickBetween(Math.max(n.time,t),e.time-this.sampleTime,i),n=e}.bind(this)),t=Math.max(n.time,t),n.state===s.default.State.Started&&this._state){var o=this.frequency.getTicksAtTime(t),a=(o-this.frequency.getTicksAtTime(n.time))%1;0!==a&&(a=1-a);for(var r=this.frequency.getTimeOfTick(o+a),l=null;r3&&(s=parseFloat(parseFloat(s).toFixed(3))),[i,e,s].join(":")},s.default.Time.prototype.toTicks=function(){var t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.round(e*this._getPPQ())},s.default.Time.prototype.toSeconds=function(){return this.valueOf()},s.default.Time.prototype.toMidi=function(){return s.default.Frequency.ftom(this.toFrequency())},e.default=s.default.Time},function(t,e,i){"use strict";i.r(e);var s=i(0);i(11),i(6),i(3),i(1);s.default.supported&&(OscillatorNode.prototype.setPeriodicWave||(OscillatorNode.prototype.setPeriodicWave=OscillatorNode.prototype.setWaveTable),AudioContext.prototype.createPeriodicWave||(AudioContext.prototype.createPeriodicWave=AudioContext.prototype.createWaveTable)),s.default.OscillatorNode=function(){var t=s.default.defaults(arguments,["frequency","type"],s.default.OscillatorNode);s.default.AudioNode.call(this,t),this.onended=t.onended,this._startTime=-1,this._stopTime=-1,this._gainNode=this.output=new s.default.Gain(0),this._oscillator=this.context.createOscillator(),s.default.connect(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new s.default.Param({param:this._oscillator.frequency,units:s.default.Type.Frequency,value:t.frequency}),this.detune=new s.default.Param({param:this._oscillator.detune,units:s.default.Type.Cents,value:t.detune}),this._gain=1},s.default.extend(s.default.OscillatorNode,s.default.AudioNode),s.default.OscillatorNode.defaults={frequency:440,detune:0,type:"sine",onended:s.default.noOp},Object.defineProperty(s.default.OscillatorNode.prototype,"state",{get:function(){return this.getStateAtTime(this.now())}}),s.default.OscillatorNode.prototype.getStateAtTime=function(t){return t=this.toSeconds(t),-1!==this._startTime&&t>=this._startTime&&(-1===this._stopTime||t<=this._stopTime)?s.default.State.Started:s.default.State.Stopped},s.default.OscillatorNode.prototype.start=function(t){if(this.log("start",t),-1!==this._startTime)throw new Error("cannot call OscillatorNode.start more than once");return this._startTime=this.toSeconds(t),this._startTime=Math.max(this._startTime,this.context.currentTime),this._oscillator.start(this._startTime),this._gainNode.gain.setValueAtTime(1,this._startTime),this},s.default.OscillatorNode.prototype.setPeriodicWave=function(t){return this._oscillator.setPeriodicWave(t),this},s.default.OscillatorNode.prototype.stop=function(t){return this.log("stop",t),this.assert(-1!==this._startTime,"'start' must be called before 'stop'"),this.cancelStop(),this._stopTime=this.toSeconds(t),this._stopTime=Math.max(this._stopTime,this.context.currentTime),this._stopTime>this._startTime?(this._gainNode.gain.setValueAtTime(0,this._stopTime),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(function(){this._oscillator.stop(this.now()),this.onended(),setTimeout(function(){this._oscillator&&(this._oscillator.disconnect(),this._gainNode.disconnect())}.bind(this),100)}.bind(this),this._stopTime-this.context.currentTime)):this._gainNode.gain.cancelScheduledValues(this._startTime),this},s.default.OscillatorNode.prototype.cancelStop=function(){return-1!==this._startTime&&(this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1),this},Object.defineProperty(s.default.OscillatorNode.prototype,"type",{get:function(){return this._oscillator.type},set:function(t){this._oscillator.type=t}}),s.default.OscillatorNode.prototype.dispose=function(){return this._wasDisposed||(this._wasDisposed=!0,this.context.clearTimeout(this._timeout),s.default.AudioNode.prototype.dispose.call(this),this.onended=null,this._oscillator.disconnect(),this._oscillator=null,this._gainNode.dispose(),this._gainNode=null,this.frequency.dispose(),this.frequency=null,this.detune.dispose(),this.detune=null),this};e.default=s.default.OscillatorNode},function(t,e,i){"use strict";i.r(e);var s=i(0);i(11),i(6),i(57),i(32);s.default.Player=function(t){var e;t instanceof s.default.Buffer&&t.loaded?(t=t.get(),e=s.default.Player.defaults):e=s.default.defaults(arguments,["url","onload"],s.default.Player),s.default.Source.call(this,e),this.autostart=e.autostart,this._buffer=new s.default.Buffer({url:e.url,onload:this._onload.bind(this,e.onload),reverse:e.reverse}),t instanceof AudioBuffer&&this._buffer.set(t),this._loop=e.loop,this._loopStart=e.loopStart,this._loopEnd=e.loopEnd,this._playbackRate=e.playbackRate,this._activeSources=[],this.fadeIn=e.fadeIn,this.fadeOut=e.fadeOut},s.default.extend(s.default.Player,s.default.Source),s.default.Player.defaults={onload:s.default.noOp,playbackRate:1,loop:!1,autostart:!1,loopStart:0,loopEnd:0,reverse:!1,fadeIn:0,fadeOut:0},s.default.Player.prototype.load=function(t,e){return this._buffer.load(t,this._onload.bind(this,e))},s.default.Player.prototype._onload=function(t){(t=s.default.defaultArg(t,s.default.noOp))(this),this.autostart&&this.start()},s.default.Player.prototype._onSourceEnd=function(t){var e=this._activeSources.indexOf(t);this._activeSources.splice(e,1),0!==this._activeSources.length||this._synced||this._state.setStateAtTime(s.default.State.Stopped,s.default.now())},s.default.Player.prototype._start=function(t,e,i){e=this._loop?s.default.defaultArg(e,this._loopStart):s.default.defaultArg(e,0),e=this.toSeconds(e),this._synced&&(e*=this._playbackRate);var n=s.default.defaultArg(i,Math.max(this._buffer.duration-e,0));n=this.toSeconds(n),n/=this._playbackRate,t=this.toSeconds(t);var o=new s.default.BufferSource({buffer:this._buffer,loop:this._loop,loopStart:this._loopStart,loopEnd:this._loopEnd,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate,fadeIn:this.fadeIn,fadeOut:this.fadeOut}).connect(this.output);return this._loop||this._synced||this._state.setStateAtTime(s.default.State.Stopped,t+n),this._activeSources.push(o),this._loop&&s.default.isUndef(i)?o.start(t,e):o.start(t,e,n-this.toSeconds(this.fadeOut)),this},s.default.Player.prototype._stop=function(t){return t=this.toSeconds(t),this._activeSources.forEach(function(e){e.stop(t)}),this},s.default.Player.prototype.restart=function(t,e,i){return this._stop(t),this._start(t,e,i),this},s.default.Player.prototype.seek=function(t,e){return e=this.toSeconds(e),this._state.getValueAtTime(e)===s.default.State.Started&&(t=this.toSeconds(t),this._stop(e),this._start(e,t)),this},s.default.Player.prototype.setLoopPoints=function(t,e){return this.loopStart=t,this.loopEnd=e,this},Object.defineProperty(s.default.Player.prototype,"loopStart",{get:function(){return this._loopStart},set:function(t){this._loopStart=t,this._activeSources.forEach(function(e){e.loopStart=t})}}),Object.defineProperty(s.default.Player.prototype,"loopEnd",{get:function(){return this._loopEnd},set:function(t){this._loopEnd=t,this._activeSources.forEach(function(e){e.loopEnd=t})}}),Object.defineProperty(s.default.Player.prototype,"buffer",{get:function(){return this._buffer},set:function(t){this._buffer.set(t)}}),Object.defineProperty(s.default.Player.prototype,"loop",{get:function(){return this._loop},set:function(t){if(this._loop!==t&&(this._loop=t,this._activeSources.forEach(function(e){e.loop=t}),t)){var e=this._state.getNextState(s.default.State.Stopped,this.now());e&&this._state.cancel(e.time)}}}),Object.defineProperty(s.default.Player.prototype,"playbackRate",{get:function(){return this._playbackRate},set:function(t){this._playbackRate=t;var e=this.now(),i=this._state.getNextState(s.default.State.Stopped,e);i&&this._state.cancel(i.time),this._activeSources.forEach(function(i){i.cancelStop(),i.playbackRate.setValueAtTime(t,e)})}}),Object.defineProperty(s.default.Player.prototype,"reverse",{get:function(){return this._buffer.reverse},set:function(t){this._buffer.reverse=t}}),Object.defineProperty(s.default.Player.prototype,"loaded",{get:function(){return this._buffer.loaded}}),s.default.Player.prototype.dispose=function(){return this._activeSources.forEach(function(t){t.dispose()}),this._activeSources=null,s.default.Source.prototype.dispose.call(this),this._buffer.dispose(),this._buffer=null,this},e.default=s.default.Player},function(t,e,i){"use strict";i.r(e);var s=i(0);i(31),i(41),i(37),i(2),i(9),i(25);s.default.MonoSynth=function(t){t=s.default.defaultArg(t,s.default.MonoSynth.defaults),s.default.Monophonic.call(this,t),this.oscillator=new s.default.OmniOscillator(t.oscillator),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.filter=new s.default.Filter(t.filter),this.filter.frequency.value=5e3,this.filterEnvelope=new s.default.FrequencyEnvelope(t.filterEnvelope),this.envelope=new s.default.AmplitudeEnvelope(t.envelope),this.oscillator.chain(this.filter,this.envelope,this.output),this.filterEnvelope.connect(this.filter.frequency),this._readOnly(["oscillator","frequency","detune","filter","filterEnvelope","envelope"])},s.default.extend(s.default.MonoSynth,s.default.Monophonic),s.default.MonoSynth.defaults={frequency:"C4",detune:0,oscillator:{type:"square"},filter:{Q:6,type:"lowpass",rolloff:-24},envelope:{attack:.005,decay:.1,sustain:.9,release:1},filterEnvelope:{attack:.06,decay:.2,sustain:.5,release:2,baseFrequency:200,octaves:7,exponent:2}},s.default.MonoSynth.prototype._triggerEnvelopeAttack=function(t,e){return t=this.toSeconds(t),this.envelope.triggerAttack(t,e),this.filterEnvelope.triggerAttack(t),this.oscillator.start(t),0===this.envelope.sustain&&this.oscillator.stop(t+this.envelope.attack+this.envelope.decay),this},s.default.MonoSynth.prototype._triggerEnvelopeRelease=function(t){return this.envelope.triggerRelease(t),this.filterEnvelope.triggerRelease(t),this.oscillator.stop(t+this.envelope.release),this},s.default.MonoSynth.prototype.dispose=function(){return s.default.Monophonic.prototype.dispose.call(this),this._writable(["oscillator","frequency","detune","filter","filterEnvelope","envelope"]),this.oscillator.dispose(),this.oscillator=null,this.envelope.dispose(),this.envelope=null,this.filterEnvelope.dispose(),this.filterEnvelope=null,this.filter.dispose(),this.filter=null,this.frequency=null,this.detune=null,this},e.default=s.default.MonoSynth},function(t,e,i){"use strict";i.r(e);var s=i(0);i(6),i(17),i(5),i(3);s.default.FatOscillator=function(){var t=s.default.defaults(arguments,["frequency","type","spread"],s.default.FatOscillator);s.default.Source.call(this,t),this.frequency=new s.default.Signal(t.frequency,s.default.Type.Frequency),this.detune=new s.default.Signal(t.detune,s.default.Type.Cents),this._oscillators=[],this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,this._readOnly(["frequency","detune"])},s.default.extend(s.default.FatOscillator,s.default.Source),s.default.FatOscillator.defaults={frequency:440,detune:0,phase:0,spread:20,count:3,type:"sawtooth",partials:[],partialCount:0},s.default.FatOscillator.prototype._start=function(t){t=this.toSeconds(t),this._forEach(function(e){e.start(t)})},s.default.FatOscillator.prototype._stop=function(t){t=this.toSeconds(t),this._forEach(function(e){e.stop(t)})},s.default.FatOscillator.prototype.restart=function(t){t=this.toSeconds(t),this._forEach(function(e){e.restart(t)})},s.default.FatOscillator.prototype._forEach=function(t){for(var e=0;e1){var e=-t/2,i=t/(this._oscillators.length-1);this._forEach(function(t,s){t.detune.value=e+i*s})}}}),Object.defineProperty(s.default.FatOscillator.prototype,"count",{get:function(){return this._oscillators.length},set:function(t){if(t=Math.max(t,1),this._oscillators.length!==t){this._forEach(function(t){t.dispose()}),this._oscillators=[];for(var e=0;e=this._loopStart&&t.startOffset=i&&(t.loop=!1,t.start(s.default.Ticks(e))):t.startOffset>=i&&t.start(s.default.Ticks(e))},Object.defineProperty(s.default.Part.prototype,"startOffset",{get:function(){return this._startOffset},set:function(t){this._startOffset=t,this._forEach(function(t){t.startOffset+=this._startOffset})}}),s.default.Part.prototype.stop=function(t){var e=this.toTicks(t);return this._state.cancel(e),this._state.setStateAtTime(s.default.State.Stopped,e),this._forEach(function(e){e.stop(t)}),this},s.default.Part.prototype.at=function(t,e){t=s.default.TransportTime(t);for(var i=s.default.Ticks(1).toSeconds(),n=0;n=0;i--){var n=this._events[i];n.startOffset===t&&(s.default.isUndef(e)||s.default.isDefined(e)&&n.value===e)&&(this._events.splice(i,1),n.dispose())}return this},s.default.Part.prototype.removeAll=function(){return this._forEach(function(t){t.dispose()}),this._events=[],this},s.default.Part.prototype.cancel=function(t){return this._forEach(function(e){e.cancel(t)}),this._state.cancel(this.toTicks(t)),this},s.default.Part.prototype._forEach=function(t,e){if(this._events){e=s.default.defaultArg(e,this);for(var i=this._events.length-1;i>=0;i--){var n=this._events[i];n instanceof s.default.Part?n._forEach(t,e):t.call(e,n)}}return this},s.default.Part.prototype._setAll=function(t,e){this._forEach(function(i){i[t]=e})},s.default.Part.prototype._tick=function(t,e){this.mute||this.callback(t,e)},s.default.Part.prototype._testLoopBoundries=function(t){this._loop&&(t.startOffset=this._loopEnd)?t.cancel(0):t.state===s.default.State.Stopped&&this._restartEvent(t)},Object.defineProperty(s.default.Part.prototype,"probability",{get:function(){return this._probability},set:function(t){this._probability=t,this._setAll("probability",t)}}),Object.defineProperty(s.default.Part.prototype,"humanize",{get:function(){return this._humanize},set:function(t){this._humanize=t,this._setAll("humanize",t)}}),Object.defineProperty(s.default.Part.prototype,"loop",{get:function(){return this._loop},set:function(t){this._loop=t,this._forEach(function(e){e._loopStart=this._loopStart,e._loopEnd=this._loopEnd,e.loop=t,this._testLoopBoundries(e)})}}),Object.defineProperty(s.default.Part.prototype,"loopEnd",{get:function(){return s.default.Ticks(this._loopEnd).toSeconds()},set:function(t){this._loopEnd=this.toTicks(t),this._loop&&this._forEach(function(e){e.loopEnd=t,this._testLoopBoundries(e)})}}),Object.defineProperty(s.default.Part.prototype,"loopStart",{get:function(){return s.default.Ticks(this._loopStart).toSeconds()},set:function(t){this._loopStart=this.toTicks(t),this._loop&&this._forEach(function(t){t.loopStart=this.loopStart,this._testLoopBoundries(t)})}}),Object.defineProperty(s.default.Part.prototype,"playbackRate",{get:function(){return this._playbackRate},set:function(t){this._playbackRate=t,this._setAll("playbackRate",t)}}),Object.defineProperty(s.default.Part.prototype,"length",{get:function(){return this._events.length}}),s.default.Part.prototype.dispose=function(){return s.default.Event.prototype.dispose.call(this),this.removeAll(),this.callback=null,this._events=null,this},e.default=s.default.Part},function(t,e,i){"use strict";i.r(e);var s=i(0);i(51);s.default.Loop=function(){var t=s.default.defaults(arguments,["callback","interval"],s.default.Loop);s.default.call(this),this._event=new s.default.Event({callback:this._tick.bind(this),loop:!0,loopEnd:t.interval,playbackRate:t.playbackRate,probability:t.probability}),this.callback=t.callback,this.iterations=t.iterations},s.default.extend(s.default.Loop),s.default.Loop.defaults={interval:"4n",callback:s.default.noOp,playbackRate:1,iterations:1/0,probability:!0,mute:!1},s.default.Loop.prototype.start=function(t){return this._event.start(t),this},s.default.Loop.prototype.stop=function(t){return this._event.stop(t),this},s.default.Loop.prototype.cancel=function(t){return this._event.cancel(t),this},s.default.Loop.prototype._tick=function(t){this.callback(t)},Object.defineProperty(s.default.Loop.prototype,"state",{get:function(){return this._event.state}}),Object.defineProperty(s.default.Loop.prototype,"progress",{get:function(){return this._event.progress}}),Object.defineProperty(s.default.Loop.prototype,"interval",{get:function(){return this._event.loopEnd},set:function(t){this._event.loopEnd=t}}),Object.defineProperty(s.default.Loop.prototype,"playbackRate",{get:function(){return this._event.playbackRate},set:function(t){this._event.playbackRate=t}}),Object.defineProperty(s.default.Loop.prototype,"humanize",{get:function(){return this._event.humanize},set:function(t){this._event.humanize=t}}),Object.defineProperty(s.default.Loop.prototype,"probability",{get:function(){return this._event.probability},set:function(t){this._event.probability=t}}),Object.defineProperty(s.default.Loop.prototype,"mute",{get:function(){return this._event.mute},set:function(t){this._event.mute=t}}),Object.defineProperty(s.default.Loop.prototype,"iterations",{get:function(){return!0===this._event.loop?1/0:this._event.loop},set:function(t){this._event.loop=t===1/0||t}}),s.default.Loop.prototype.dispose=function(){this._event.dispose(),this._event=null,this.callback=null},e.default=s.default.Loop},function(t,e,i){"use strict";i.r(e);var s=i(0);i(15),i(33);s.default.StereoXFeedbackEffect=function(){var t=s.default.defaults(arguments,["feedback"],s.default.FeedbackEffect);s.default.StereoEffect.call(this,t),this.feedback=new s.default.Signal(t.feedback,s.default.Type.NormalRange),this._feedbackLR=new s.default.Gain,this._feedbackRL=new s.default.Gain,this.effectReturnL.chain(this._feedbackLR,this.effectSendR),this.effectReturnR.chain(this._feedbackRL,this.effectSendL),this.feedback.fan(this._feedbackLR.gain,this._feedbackRL.gain),this._readOnly(["feedback"])},s.default.extend(s.default.StereoXFeedbackEffect,s.default.StereoEffect),s.default.StereoXFeedbackEffect.prototype.dispose=function(){return s.default.StereoEffect.prototype.dispose.call(this),this._writable(["feedback"]),this.feedback.dispose(),this.feedback=null,this._feedbackLR.dispose(),this._feedbackLR=null,this._feedbackRL.dispose(),this._feedbackRL=null,this},e.default=s.default.StereoXFeedbackEffect},function(t,e,i){"use strict";i.r(e);var s=i(0);i(8),i(53),i(52);s.default.MidSideEffect=function(){s.default.Effect.apply(this,arguments),this._midSideSplit=new s.default.MidSideSplit,this._midSideMerge=new s.default.MidSideMerge,this.midSend=this._midSideSplit.mid,this.sideSend=this._midSideSplit.side,this.midReturn=this._midSideMerge.mid,this.sideReturn=this._midSideMerge.side,this.effectSend.connect(this._midSideSplit),this._midSideMerge.connect(this.effectReturn)},s.default.extend(s.default.MidSideEffect,s.default.Effect),s.default.MidSideEffect.prototype.dispose=function(){return s.default.Effect.prototype.dispose.call(this),this._midSideSplit.dispose(),this._midSideSplit=null,this._midSideMerge.dispose(),this._midSideMerge=null,this.midSend=null,this.sideSend=null,this.midReturn=null,this.sideReturn=null,this},e.default=s.default.MidSideEffect},function(t,e,i){"use strict";i.r(e);var s=i(0);i(11),i(8);s.default.Convolver=function(){var t=s.default.defaults(arguments,["url","onload"],s.default.Convolver);s.default.Effect.call(this,t),this._convolver=this.context.createConvolver(),this._buffer=new s.default.Buffer(t.url,function(e){this.buffer=e.get(),t.onload()}.bind(this)),this._buffer.loaded&&(this.buffer=this._buffer),this.normalize=t.normalize,this.connectEffect(this._convolver)},s.default.extend(s.default.Convolver,s.default.Effect),s.default.Convolver.defaults={onload:s.default.noOp,normalize:!0},Object.defineProperty(s.default.Convolver.prototype,"buffer",{get:function(){return this._buffer.length?this._buffer:null},set:function(t){this._buffer.set(t),this._convolver.buffer&&(this.effectSend.disconnect(),this._convolver.disconnect(),this._convolver=this.context.createConvolver(),this.connectEffect(this._convolver)),this._convolver.buffer=this._buffer.get()}}),Object.defineProperty(s.default.Convolver.prototype,"normalize",{get:function(){return this._convolver.normalize},set:function(t){this._convolver.normalize=t}}),s.default.Convolver.prototype.load=function(t,e){return this._buffer.load(t,function(t){this.buffer=t,e&&e()}.bind(this))},s.default.Convolver.prototype.dispose=function(){return s.default.Effect.prototype.dispose.call(this),this._buffer.dispose(),this._buffer=null,this._convolver.disconnect(),this._convolver=null,this},e.default=s.default.Convolver},function(t,e,i){"use strict";i.r(e);var s=i(0);i(7),i(5),i(13);s.default.Modulo=function(t){s.default.SignalBase.call(this),this.createInsOuts(1,0),this._shaper=new s.default.WaveShaper(Math.pow(2,16)),this._multiply=new s.default.Multiply,this._subtract=this.output=new s.default.Subtract,this._modSignal=new s.default.Signal(t),s.default.connect(this.input,this._shaper),s.default.connect(this.input,this._subtract),this._modSignal.connect(this._multiply,0,0),this._shaper.connect(this._multiply,0,1),this._multiply.connect(this._subtract,0,1),this._setWaveShaper(t)},s.default.extend(s.default.Modulo,s.default.SignalBase),s.default.Modulo.prototype._setWaveShaper=function(t){this._shaper.setMap(function(e){return Math.floor((e+1e-4)/t)})},Object.defineProperty(s.default.Modulo.prototype,"value",{get:function(){return this._modSignal.value},set:function(t){this._modSignal.value=t,this._setWaveShaper(t)}}),s.default.Modulo.prototype.dispose=function(){return s.default.SignalBase.prototype.dispose.call(this),this._shaper.dispose(),this._shaper=null,this._multiply.dispose(),this._multiply=null,this._subtract.dispose(),this._subtract=null,this._modSignal.dispose(),this._modSignal=null,this},e.default=s.default.Modulo},function(t,e,i){"use strict";i.r(e);var s=i(0);i(20),i(92);s.default.OfflineContext=function(t,e,i){var n=new OfflineAudioContext(t,e*i,i);s.default.Context.call(this,{context:n,clockSource:"offline",lookAhead:0,updateInterval:128/i}),this._duration=e,this._currentTime=0},s.default.extend(s.default.OfflineContext,s.default.Context),s.default.OfflineContext.prototype.now=function(){return this._currentTime},s.default.OfflineContext.prototype.resume=function(){return Promise.resolve()},s.default.OfflineContext.prototype.render=function(){for(;this._duration-this._currentTime>=0;)this.emit("tick"),this._currentTime+=.005;return this._context.startRendering()},s.default.OfflineContext.prototype.close=function(){return this._context=null,Promise.resolve()},e.default=s.default.OfflineContext},function(t,e,i){"use strict";i.r(e);var s=i(0);i(16),i(11),i(76),i(40);s.default.Offline=function(t,e){var i=s.default.context.sampleRate,n=s.default.context,o=new s.default.OfflineContext(2,e,i);s.default.context=o;var a=t(s.default.Transport),r=null;return r=a&&s.default.isFunction(a.then)?a.then(function(){return o.render()}):o.render(),s.default.context=n,r.then(function(t){return new s.default.Buffer(t)})},e.default=s.default.Offline},function(t,e,i){"use strict";i.r(e);var s=i(0);i(11);s.default.Buffers=function(t){var e=Array.prototype.slice.call(arguments);e.shift();var i=s.default.defaults(e,["onload","baseUrl"],s.default.Buffers);for(var n in s.default.call(this),this._buffers={},this.baseUrl=i.baseUrl,this._loadingCount=0,t)this._loadingCount++,this.add(n,t[n],this._bufferLoaded.bind(this,i.onload))},s.default.extend(s.default.Buffers),s.default.Buffers.defaults={onload:s.default.noOp,baseUrl:""},s.default.Buffers.prototype.has=function(t){return this._buffers.hasOwnProperty(t)},s.default.Buffers.prototype.get=function(t){if(this.has(t))return this._buffers[t];throw new Error("Tone.Buffers: no buffer named "+t)},s.default.Buffers.prototype._bufferLoaded=function(t){this._loadingCount--,0===this._loadingCount&&t&&t(this)},Object.defineProperty(s.default.Buffers.prototype,"loaded",{get:function(){var t=!0;for(var e in this._buffers){var i=this.get(e);t=t&&i.loaded}return t}}),s.default.Buffers.prototype.add=function(t,e,i){return i=s.default.defaultArg(i,s.default.noOp),e instanceof s.default.Buffer?(this._buffers[t]=e,i(this)):e instanceof AudioBuffer?(this._buffers[t]=new s.default.Buffer(e),i(this)):s.default.isString(e)&&(this._buffers[t]=new s.default.Buffer(this.baseUrl+e,i)),this},s.default.Buffers.prototype.dispose=function(){for(var t in s.default.prototype.dispose.call(this),this._buffers)this._buffers[t].dispose();return this._buffers=null,this},e.default=s.default.Buffers},function(t,e,i){"use strict";i.r(e);var s=i(0);s.default.CtrlPattern=function(){var t=s.default.defaults(arguments,["values","type"],s.default.CtrlPattern);s.default.call(this),this.values=t.values,this.index=0,this._type=null,this._shuffled=null,this._direction=null,this.type=t.type},s.default.extend(s.default.CtrlPattern),s.default.CtrlPattern.Type={Up:"up",Down:"down",UpDown:"upDown",DownUp:"downUp",AlternateUp:"alternateUp",AlternateDown:"alternateDown",Random:"random",RandomWalk:"randomWalk",RandomOnce:"randomOnce"},s.default.CtrlPattern.defaults={type:s.default.CtrlPattern.Type.Up,values:[]},Object.defineProperty(s.default.CtrlPattern.prototype,"value",{get:function(){if(0!==this.values.length){if(1===this.values.length)return this.values[0];this.index=Math.min(this.index,this.values.length-1);var t=this.values[this.index];return this.type===s.default.CtrlPattern.Type.RandomOnce&&(this.values.length!==this._shuffled.length&&this._shuffleValues(),t=this.values[this._shuffled[this.index]]),t}}}),Object.defineProperty(s.default.CtrlPattern.prototype,"type",{get:function(){return this._type},set:function(t){this._type=t,this._shuffled=null,this._type===s.default.CtrlPattern.Type.Up||this._type===s.default.CtrlPattern.Type.UpDown||this._type===s.default.CtrlPattern.Type.RandomOnce||this._type===s.default.CtrlPattern.Type.AlternateUp?this.index=0:this._type!==s.default.CtrlPattern.Type.Down&&this._type!==s.default.CtrlPattern.Type.DownUp&&this._type!==s.default.CtrlPattern.Type.AlternateDown||(this.index=this.values.length-1),this._type===s.default.CtrlPattern.Type.UpDown||this._type===s.default.CtrlPattern.Type.AlternateUp?this._direction=s.default.CtrlPattern.Type.Up:this._type!==s.default.CtrlPattern.Type.DownUp&&this._type!==s.default.CtrlPattern.Type.AlternateDown||(this._direction=s.default.CtrlPattern.Type.Down),this._type===s.default.CtrlPattern.Type.RandomOnce?this._shuffleValues():this._type===s.default.CtrlPattern.Type.Random&&(this.index=Math.floor(Math.random()*this.values.length))}}),s.default.CtrlPattern.prototype.next=function(){var t=this.type;return t===s.default.CtrlPattern.Type.Up?(this.index++,this.index>=this.values.length&&(this.index=0)):t===s.default.CtrlPattern.Type.Down?(this.index--,this.index<0&&(this.index=this.values.length-1)):t===s.default.CtrlPattern.Type.UpDown||t===s.default.CtrlPattern.Type.DownUp?(this._direction===s.default.CtrlPattern.Type.Up?this.index++:this.index--,this.index<0?(this.index=1,this._direction=s.default.CtrlPattern.Type.Up):this.index>=this.values.length&&(this.index=this.values.length-2,this._direction=s.default.CtrlPattern.Type.Down)):t===s.default.CtrlPattern.Type.Random?this.index=Math.floor(Math.random()*this.values.length):t===s.default.CtrlPattern.Type.RandomWalk?Math.random()<.5?(this.index--,this.index=Math.max(this.index,0)):(this.index++,this.index=Math.min(this.index,this.values.length-1)):t===s.default.CtrlPattern.Type.RandomOnce?(this.index++,this.index>=this.values.length&&(this.index=0,this._shuffleValues())):t===s.default.CtrlPattern.Type.AlternateUp?(this._direction===s.default.CtrlPattern.Type.Up?(this.index+=2,this._direction=s.default.CtrlPattern.Type.Down):(this.index-=1,this._direction=s.default.CtrlPattern.Type.Up),this.index>=this.values.length&&(this.index=0,this._direction=s.default.CtrlPattern.Type.Up)):t===s.default.CtrlPattern.Type.AlternateDown&&(this._direction===s.default.CtrlPattern.Type.Up?(this.index+=1,this._direction=s.default.CtrlPattern.Type.Down):(this.index-=2,this._direction=s.default.CtrlPattern.Type.Up),this.index<0&&(this.index=this.values.length-1,this._direction=s.default.CtrlPattern.Type.Down)),this.value},s.default.CtrlPattern.prototype._shuffleValues=function(){var t=[];this._shuffled=[];for(var e=0;e0;){var i=t.splice(Math.floor(t.length*Math.random()),1);this._shuffled.push(i[0])}},s.default.CtrlPattern.prototype.dispose=function(){this._shuffled=null,this.values=null},e.default=s.default.CtrlPattern},function(t,e,i){"use strict";i.r(e);var s=i(0);i(56),i(55);s.default.TransportRepeatEvent=function(t,e){s.default.TransportEvent.call(this,t,e),e=s.default.defaultArg(e,s.default.TransportRepeatEvent.defaults),this.duration=s.default.Ticks(e.duration),this._interval=s.default.Ticks(e.interval),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this),this.Transport.on("start loopStart",this._boundRestart),this._restart()},s.default.extend(s.default.TransportRepeatEvent,s.default.TransportEvent),s.default.TransportRepeatEvent.defaults={duration:1/0,interval:1},s.default.TransportRepeatEvent.prototype.invoke=function(t){this._createEvents(t),s.default.TransportEvent.prototype.invoke.call(this,t)},s.default.TransportRepeatEvent.prototype._createEvents=function(t){var e=this.Transport.getTicksAtTime(t);e>=this.time&&e>=this._nextTick&&this._nextTick+this._intervalthis.time&&(this._nextTick=this.time+Math.ceil((e-this.time)/this._interval)*this._interval),this._currentId=this.Transport.scheduleOnce(this.invoke.bind(this),s.default.Ticks(this._nextTick)),this._nextTick+=this._interval,this._nextId=this.Transport.scheduleOnce(this.invoke.bind(this),s.default.Ticks(this._nextTick))},s.default.TransportRepeatEvent.prototype.dispose=function(){return this.Transport.clear(this._currentId),this.Transport.clear(this._nextId),this.Transport.off("start loopStart",this._boundRestart),this._boundCreateEvents=null,s.default.TransportEvent.prototype.dispose.call(this),this.duration=null,this._interval=null,this},e.default=s.default.TransportRepeatEvent},function(t,e,i){"use strict";i.r(e);var s=i(0);i(4);s.default.IntervalTimeline=function(){s.default.call(this),this._root=null,this._length=0},s.default.extend(s.default.IntervalTimeline),s.default.IntervalTimeline.prototype.add=function(t){if(s.default.isUndef(t.time)||s.default.isUndef(t.duration))throw new Error("Tone.IntervalTimeline: events must have time and duration parameters");t.time=t.time.valueOf();var e=new n(t.time,t.time+t.duration,t);for(null===this._root?this._root=e:this._root.insert(e),this._length++;null!==e;)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this},s.default.IntervalTimeline.prototype.remove=function(t){if(null!==this._root){var e=[];this._root.search(t.time,e);for(var i=0;i0)if(null===t.left.right)(e=t.left).right=t.right,i=e;else{for(e=t.left.right;null!==e.right;)e=e.right;e.parent.right=e.left,i=e.parent,e.left=t.left,e.right=t.right}else if(null===t.right.left)(e=t.right).left=t.left,i=e;else{for(e=t.right.left;null!==e.left;)e=e.left;e.parent.left=e.right,i=e.parent,e.left=t.left,e.right=t.right}null!==t.parent?t.isLeftChild()?t.parent.left=e:t.parent.right=e:this._setRoot(e),this._rebalance(i)}t.dispose()},s.default.IntervalTimeline.prototype._rotateLeft=function(t){var e=t.parent,i=t.isLeftChild(),s=t.right;t.right=s.left,s.left=t,null!==e?i?e.left=s:e.right=s:this._setRoot(s)},s.default.IntervalTimeline.prototype._rotateRight=function(t){var e=t.parent,i=t.isLeftChild(),s=t.left;t.left=s.right,s.right=t,null!==e?i?e.left=s:e.right=s:this._setRoot(s)},s.default.IntervalTimeline.prototype._rebalance=function(t){var e=t.getBalance();e>1?t.left.getBalance()<0?this._rotateLeft(t.left):this._rotateRight(t):e<-1&&(t.right.getBalance()>0?this._rotateRight(t.right):this._rotateLeft(t))},s.default.IntervalTimeline.prototype.get=function(t){if(null!==this._root){var e=[];if(this._root.search(t,e),e.length>0){for(var i=e[0],s=1;si.low&&(i=e[s]);return i.event}}return null},s.default.IntervalTimeline.prototype.forEach=function(t){if(null!==this._root){var e=[];this._root.traverse(function(t){e.push(t)});for(var i=0;i=0;s--){var n=i[s].event;n&&e(n)}}return this},s.default.IntervalTimeline.prototype.forEachFrom=function(t,e){if(null!==this._root){var i=[];this._root.searchAfter(t,i);for(var s=i.length-1;s>=0;s--){e(i[s].event)}}return this},s.default.IntervalTimeline.prototype.dispose=function(){var t=[];null!==this._root&&this._root.traverse(function(e){t.push(e)});for(var e=0;ethis.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))},n.prototype.searchAfter=function(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)},n.prototype.traverse=function(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)},n.prototype.updateHeight=function(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0},n.prototype.updateMax=function(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))},n.prototype.getBalance=function(){var t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t},n.prototype.isLeftChild=function(){return null!==this.parent&&this.parent.left===this},Object.defineProperty(n.prototype,"left",{get:function(){return this._left},set:function(t){this._left=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}}),Object.defineProperty(n.prototype,"right",{get:function(){return this._right},set:function(t){this._right=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}}),n.prototype.dispose=function(){this.parent=null,this._left=null,this._right=null,this.event=null},e.default=s.default.IntervalTimeline},function(t,e,i){"use strict";i.r(e);var s=i(0);i(2);function n(t){return function(e,i){i=this.toSeconds(i),t.apply(this,arguments);var s=this._events.get(i),n=this._events.previousEvent(s),o=this._getTicksUntilEvent(n,i);return s.ticks=Math.max(o,0),this}}s.default.TickSignal=function(t){t=s.default.defaultArg(t,1),s.default.Signal.call(this,{units:s.default.Type.Ticks,value:t}),this._events.memory=1/0,this.cancelScheduledValues(0),this._events.add({type:s.default.Param.AutomationType.SetValue,time:0,value:t})},s.default.extend(s.default.TickSignal,s.default.Signal),s.default.TickSignal.prototype.setValueAtTime=n(s.default.Signal.prototype.setValueAtTime),s.default.TickSignal.prototype.linearRampToValueAtTime=n(s.default.Signal.prototype.linearRampToValueAtTime),s.default.TickSignal.prototype.setTargetAtTime=function(t,e,i){e=this.toSeconds(e),this.setRampPoint(e),t=this._fromUnits(t);for(var s=this._events.get(e),n=Math.round(Math.max(1/i,1)),o=0;o<=n;o++){var a=i*o+e,r=this._exponentialApproach(s.time,s.value,t,i,a);this.linearRampToValueAtTime(this._toUnits(r),a)}return this},s.default.TickSignal.prototype.exponentialRampToValueAtTime=function(t,e){e=this.toSeconds(e),t=this._fromUnits(t);for(var i=this._events.get(e),s=Math.round(Math.max(10*(e-i.time),1)),n=(e-i.time)/s,o=0;o<=s;o++){var a=n*o+i.time,r=this._exponentialInterpolate(i.time,i.value,e,t,a);this.linearRampToValueAtTime(this._toUnits(r),a)}return this},s.default.TickSignal.prototype._getTicksUntilEvent=function(t,e){if(null===t)t={ticks:0,time:0};else if(s.default.isUndef(t.ticks)){var i=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(i,t.time)}var n=this.getValueAtTime(t.time),o=this.getValueAtTime(e);return this._events.get(e).time===e&&this._events.get(e).type===s.default.Param.AutomationType.SetValue&&(o=this.getValueAtTime(e-this.sampleTime)),.5*(e-t.time)*(n+o)+t.ticks},s.default.TickSignal.prototype.getTicksAtTime=function(t){t=this.toSeconds(t);var e=this._events.get(t);return Math.max(this._getTicksUntilEvent(e,t),0)},s.default.TickSignal.prototype.getDurationOfTicks=function(t,e){e=this.toSeconds(e);var i=this.getTicksAtTime(e);return this.getTimeOfTick(i+t)-e},s.default.TickSignal.prototype.getTimeOfTick=function(t){var e=this._events.get(t,"ticks"),i=this._events.getAfter(t,"ticks");if(e&&e.ticks===t)return e.time;if(e&&i&&i.type===s.default.Param.AutomationType.Linear&&e.value!==i.value){var n=this.getValueAtTime(e.time),o=(this.getValueAtTime(i.time)-n)/(i.time-e.time),a=Math.sqrt(Math.pow(n,2)-2*o*(e.ticks-t)),r=(-n+a)/o;return(r>0?r:(-n-a)/o)+e.time}return e?0===e.value?1/0:e.time+(t-e.ticks)/e.value:t/this._initialValue},s.default.TickSignal.prototype.ticksToTime=function(t,e){return e=this.toSeconds(e),new s.default.Time(this.getDurationOfTicks(t,e))},s.default.TickSignal.prototype.timeToTicks=function(t,e){e=this.toSeconds(e),t=this.toSeconds(t);var i=this.getTicksAtTime(e),n=this.getTicksAtTime(e+t);return new s.default.Ticks(n-i)},e.default=s.default.TickSignal},function(t,e,i){"use strict";i.r(e);var s=i(0);i(57),i(34),i(35),i(20);s.default.Clock=function(){var t=s.default.defaults(arguments,["callback","frequency"],s.default.Clock);s.default.Emitter.call(this),this.callback=t.callback,this._nextTick=0,this._tickSource=new s.default.TickSource(t.frequency),this._lastUpdate=0,this.frequency=this._tickSource.frequency,this._readOnly("frequency"),this._state=new s.default.TimelineState(s.default.State.Stopped),this._state.setStateAtTime(s.default.State.Stopped,0),this._boundLoop=this._loop.bind(this),this.context.on("tick",this._boundLoop)},s.default.extend(s.default.Clock,s.default.Emitter),s.default.Clock.defaults={callback:s.default.noOp,frequency:1},Object.defineProperty(s.default.Clock.prototype,"state",{get:function(){return this._state.getValueAtTime(this.now())}}),s.default.Clock.prototype.start=function(t,e){return this.context.resume(),t=this.toSeconds(t),this._state.getValueAtTime(t)!==s.default.State.Started&&(this._state.setStateAtTime(s.default.State.Started,t),this._tickSource.start(t,e),t0)i=e[0];else if(!i&&s.default.isDefined(t))throw new Error("Tone.UserMedia: no matching device: "+t);this._device=i;var n={audio:{echoCancellation:!1,sampleRate:this.context.sampleRate,noiseSuppression:!1,mozNoiseSuppression:!1}};return i&&(n.audio.deviceId=i.deviceId),navigator.mediaDevices.getUserMedia(n).then(function(t){return this._stream||(this._stream=t,this._mediaStream=this.context.createMediaStreamSource(t),s.default.connect(this._mediaStream,this.output)),this}.bind(this))}.bind(this))},s.default.UserMedia.prototype.close=function(){return this._stream&&(this._stream.getAudioTracks().forEach(function(t){t.stop()}),this._stream=null,this._mediaStream.disconnect(),this._mediaStream=null),this._device=null,this},s.default.UserMedia.enumerateDevices=function(){return navigator.mediaDevices.enumerateDevices().then(function(t){return t.filter(function(t){return"audioinput"===t.kind})})},Object.defineProperty(s.default.UserMedia.prototype,"state",{get:function(){return this._stream&&this._stream.active?s.default.State.Started:s.default.State.Stopped}}),Object.defineProperty(s.default.UserMedia.prototype,"deviceId",{get:function(){return this._device?this._device.deviceId:null}}),Object.defineProperty(s.default.UserMedia.prototype,"groupId",{get:function(){return this._device?this._device.groupId:null}}),Object.defineProperty(s.default.UserMedia.prototype,"label",{get:function(){return this._device?this._device.label:null}}),Object.defineProperty(s.default.UserMedia.prototype,"mute",{get:function(){return this._volume.mute},set:function(t){this._volume.mute=t}}),s.default.UserMedia.prototype.dispose=function(){return s.default.AudioNode.prototype.dispose.call(this),this.close(),this._writable("volume"),this._volume.dispose(),this._volume=null,this.volume=null,this},Object.defineProperty(s.default.UserMedia,"supported",{get:function(){return s.default.isDefined(navigator.mediaDevices)&&s.default.isFunction(navigator.mediaDevices.getUserMedia)}}),e.default=s.default.UserMedia},function(t,e,i){"use strict";i.r(e);var s=i(0);i(65),i(27),i(1);s.default.Players=function(t){var e=Array.prototype.slice.call(arguments);e.shift();var i=s.default.defaults(e,["onload"],s.default.Players);for(var n in s.default.AudioNode.call(this,i),this._volume=this.output=new s.default.Volume(i.volume),this.volume=this._volume.volume,this._readOnly("volume"),this._volume.output.output.channelCount=2,this._volume.output.output.channelCountMode="explicit",this.mute=i.mute,this._players={},this._loadingCount=0,this._fadeIn=i.fadeIn,this._fadeOut=i.fadeOut,t)this._loadingCount++,this.add(n,t[n],this._bufferLoaded.bind(this,i.onload))},s.default.extend(s.default.Players,s.default.AudioNode),s.default.Players.defaults={volume:0,mute:!1,onload:s.default.noOp,fadeIn:0,fadeOut:0},s.default.Players.prototype._bufferLoaded=function(t){this._loadingCount--,0===this._loadingCount&&t&&t(this)},Object.defineProperty(s.default.Players.prototype,"mute",{get:function(){return this._volume.mute},set:function(t){this._volume.mute=t}}),Object.defineProperty(s.default.Players.prototype,"fadeIn",{get:function(){return this._fadeIn},set:function(t){this._fadeIn=t,this._forEach(function(e){e.fadeIn=t})}}),Object.defineProperty(s.default.Players.prototype,"fadeOut",{get:function(){return this._fadeOut},set:function(t){this._fadeOut=t,this._forEach(function(e){e.fadeOut=t})}}),Object.defineProperty(s.default.Players.prototype,"state",{get:function(){var t=!1;return this._forEach(function(e){t=t||e.state===s.default.State.Started}),t?s.default.State.Started:s.default.State.Stopped}}),s.default.Players.prototype.has=function(t){return this._players.hasOwnProperty(t)},s.default.Players.prototype.get=function(t){if(this.has(t))return this._players[t];throw new Error("Tone.Players: no player named "+t)},s.default.Players.prototype._forEach=function(t){for(var e in this._players)t(this._players[e],e);return this},Object.defineProperty(s.default.Players.prototype,"loaded",{get:function(){var t=!0;return this._forEach(function(e){t=t&&e.loaded}),t}}),s.default.Players.prototype.add=function(t,e,i){return this._players[t]=new s.default.Player(e,i).connect(this.output),this._players[t].fadeIn=this._fadeIn,this._players[t].fadeOut=this._fadeOut,this},s.default.Players.prototype.stopAll=function(t){this._forEach(function(e){e.stop(t)})},s.default.Players.prototype.dispose=function(){return s.default.AudioNode.prototype.dispose.call(this),this._volume.dispose(),this._volume=null,this._writable("volume"),this.volume=null,this.output=null,this._forEach(function(t){t.dispose()}),this._players=null,this},e.default=s.default.Players},function(t,e,i){"use strict";i.r(e);var s=i(0);i(6),i(11),i(32);s.default.GrainPlayer=function(){var t=s.default.defaults(arguments,["url","onload"],s.default.GrainPlayer);s.default.Source.call(this,t),this.buffer=new s.default.Buffer(t.url,t.onload.bind(void 0,this)),this._clock=new s.default.Clock(this._tick.bind(this),t.grainSize),this._loopStart=0,this._loopEnd=0,this._activeSources=[],this._playbackRate=t.playbackRate,this._grainSize=t.grainSize,this._overlap=t.overlap,this.detune=t.detune,this.overlap=t.overlap,this.loop=t.loop,this.playbackRate=t.playbackRate,this.grainSize=t.grainSize,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.reverse=t.reverse,this._clock.on("stop",this._onstop.bind(this))},s.default.extend(s.default.GrainPlayer,s.default.Source),s.default.GrainPlayer.defaults={onload:s.default.noOp,overlap:.1,grainSize:.2,playbackRate:1,detune:0,loop:!1,loopStart:0,loopEnd:0,reverse:!1},s.default.GrainPlayer.prototype._start=function(t,e,i){e=s.default.defaultArg(e,0),e=this.toSeconds(e),t=this.toSeconds(t),this._offset=e,this._clock.start(t),i&&this.stop(t+this.toSeconds(i))},s.default.GrainPlayer.prototype._stop=function(t){this._clock.stop(t)},s.default.GrainPlayer.prototype._onstop=function(t){this._activeSources.forEach(function(e){e.fadeOut=0,e.stop(t)})},s.default.GrainPlayer.prototype._tick=function(t){if(!this.loop&&this._offset>this.buffer.duration)this.stop(t);else{var e=this._offset0,"polyphony must be greater than 0"),this.detune=new s.default.Signal(t.detune,s.default.Type.Cents),this._readOnly("detune");for(var e=0;e1e-5)return i});return i||this.voices.slice().sort(function(e,i){var s=e.getLevelAtTime(t+this.blockTime),n=i.getLevelAtTime(t+this.blockTime);return s<1e-5&&(s=0),n<1e-5&&(n=0),s-n}.bind(this))[0]},s.default.PolySynth.prototype.triggerAttack=function(t,e,i){return Array.isArray(t)||(t=[t]),e=this.toSeconds(e),t.forEach(function(t){var s=this._getClosestVoice(e,t);s.triggerAttack(t,e,i),this.log("triggerAttack",s.index,t)}.bind(this)),this},s.default.PolySynth.prototype.triggerRelease=function(t,e){return Array.isArray(t)||(t=[t]),e=this.toSeconds(e),t.forEach(function(t){var i=this._getClosestVoice(e,t);this.log("triggerRelease",i.index,t),i.triggerRelease(e)}.bind(this)),this},s.default.PolySynth.prototype.triggerAttackRelease=function(t,e,i,n){if(i=this.toSeconds(i),this.triggerAttack(t,i,n),s.default.isArray(e)&&s.default.isArray(t))for(var o=0;o0&&requestAnimationFrame(this._boundDrawLoop)},s.default.Draw=new s.default.Draw,e.default=s.default.Draw},function(t,e,i){"use strict";i.r(e);var s=i(0),n=(i(3),{});s.default.prototype.send=function(t,e){n.hasOwnProperty(t)||(n[t]=this.context.createGain()),e=s.default.defaultArg(e,0);var i=new s.default.Gain(e,s.default.Type.Decibels);return this.connect(i),i.connect(n[t]),i},s.default.prototype.receive=function(t,e){return n.hasOwnProperty(t)||(n[t]=this.context.createGain()),s.default.connect(n[t],this,0,e),this},s.default.Context.on("init",function(t){t.buses?n=t.buses:(n={},t.buses=n)}),e.default=s.default},function(t,e,i){"use strict";i.r(e);var s=i(0);i(4);s.default.CtrlRandom=function(){var t=s.default.defaults(arguments,["min","max"],s.default.CtrlRandom);s.default.call(this),this.min=t.min,this.max=t.max,this.integer=t.integer},s.default.extend(s.default.CtrlRandom),s.default.CtrlRandom.defaults={min:0,max:1,integer:!1},Object.defineProperty(s.default.CtrlRandom.prototype,"value",{get:function(){var t=this.toSeconds(this.min),e=this.toSeconds(this.max),i=Math.random(),s=i*t+(1-i)*e;return this.integer&&(s=Math.floor(s)),s}}),e.default=s.default.CtrlRandom},function(t,e,i){"use strict";i.r(e);var s=i(0);s.default.CtrlMarkov=function(t,e){s.default.call(this),this.values=s.default.defaultArg(t,{}),this.value=s.default.defaultArg(e,Object.keys(this.values)[0])},s.default.extend(s.default.CtrlMarkov),s.default.CtrlMarkov.prototype.next=function(){if(this.values.hasOwnProperty(this.value)){var t=this.values[this.value];if(s.default.isArray(t))for(var e=this._getProbDistribution(t),i=Math.random(),n=0,o=0;on&&ie+1e-6}function P(t,e){return N(t,e)||z(t,e)}function L(t,e){return t+1e-6this.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(t){const e=this._timeline.indexOf(t);return-1!==e&&this._timeline.splice(e,1),this}get(t,e="time"){const n=this._search(t,e);return-1!==n?this._timeline[n]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(t,e="time"){const n=this._search(t,e);return n+10&&this._timeline[e-1].time=0?this._timeline[n-1]:null}cancel(t){if(this._timeline.length>1){let e=this._search(t);if(e>=0)if(z(this._timeline[e].time,t)){for(let n=e;n>=0&&z(this._timeline[n].time,t);n--)e=n;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&P(this._timeline[0].time,t)&&(this._timeline=[]);return this}cancelBefore(t){const e=this._search(t);return e>=0&&(this._timeline=this._timeline.slice(e+1)),this}previousEvent(t){const e=this._timeline.indexOf(t);return e>0?this._timeline[e-1]:null}_search(t,e="time"){if(0===this._timeline.length)return-1;let n=0;const s=this._timeline.length;let i=s;if(s>0&&this._timeline[s-1][e]<=t)return s-1;for(;n=0&&this._timeline[n].time>=t;)n--;return this._iterate(e,n+1),this}forEachAtTime(t,e){const n=this._search(t);if(-1!==n&&z(this._timeline[n].time,t)){let s=n;for(let e=n;e>=0&&z(this._timeline[e].time,t);e--)s=e;this._iterate(t=>{e(t)},s,n)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const U=[];function G(t){U.push(t)}const Y=[];function Q(t){Y.push(t)}class Z extends V{constructor(){super(...arguments),this.name="Emitter"}on(t,e){return t.split(/\W+/).forEach(t=>{p(this._events)&&(this._events={}),this._events.hasOwnProperty(t)||(this._events[t]=[]),this._events[t].push(e)}),this}once(t,e){const n=(...s)=>{e(...s),this.off(t,n)};return this.on(t,n),this}off(t,e){return t.split(/\W+/).forEach(n=>{if(p(this._events)&&(this._events={}),this._events.hasOwnProperty(t))if(p(e))this._events[t]=[];else{const n=this._events[t];for(let t=0;t{const n=Object.getOwnPropertyDescriptor(Z.prototype,e);Object.defineProperty(t.prototype,e,n)})}dispose(){return super.dispose(),this._events=void 0,this}}class X extends Z{constructor(){super(...arguments),this.isOffline=!1}}class H extends X{constructor(){super(),this.name="Context",this._constants=new Map,this._timeouts=new W,this._timeoutIds=0,this._initialized=!1,this.isOffline=!1,this._workletModules=new Map;const t=q(H.getDefaults(),arguments,["context"]);t.context?this._context=t.context:this._context=function(t){return new o.AudioContext(t)}({latencyHint:t.latencyHint}),this._ticker=new C(this.emit.bind(this,"tick"),t.clockSource,t.updateInterval),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this._setLatencyHint(t.latencyHint),this.lookAhead=t.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){var t;return this._initialized||(t=this,U.forEach(e=>e(t)),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(t,e,n){return this._context.createBuffer(t,e,n)}createChannelMerger(t){return this._context.createChannelMerger(t)}createChannelSplitter(t){return this._context.createChannelSplitter(t)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(t){return this._context.createDelay(t)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(t,e){return this._context.createIIRFilter(t,e)}createPanner(){return this._context.createPanner()}createPeriodicWave(t,e,n){return this._context.createPeriodicWave(t,e,n)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(t){return r(M(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(t)}createMediaStreamDestination(){return r(M(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(t){return this._context.decodeAudioData(t)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(t){r(!this._initialized,"The listener cannot be set after initialization."),this._listener=t}get transport(){return this.initialize(),this._transport}set transport(t){r(!this._initialized,"The transport cannot be set after initialization."),this._transport=t}get draw(){return this.initialize(),this._draw}set draw(t){r(!this._initialized,"Draw cannot be set after initialization."),this._draw=t}get destination(){return this.initialize(),this._destination}set destination(t){r(!this._initialized,"The destination cannot be set after initialization."),this._destination=t}createAudioWorkletNode(t,e){return function(t,e,n){return r(f(o.AudioWorkletNode),"This node only works in a secure context (https or localhost)"),new o.AudioWorkletNode(t,e,n)}
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */(this.rawContext,t,e)}addAudioWorkletModule(t,e){return S(this,void 0,void 0,(function*(){r(f(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletModules.has(e)||this._workletModules.set(e,this.rawContext.audioWorklet.addModule(t)),yield this._workletModules.get(e)}))}workletsAreReady(){return S(this,void 0,void 0,(function*(){const t=[];this._workletModules.forEach(e=>t.push(e)),yield Promise.all(t)}))}get updateInterval(){return this._ticker.updateInterval}set updateInterval(t){this._ticker.updateInterval=t}get clockSource(){return this._ticker.type}set clockSource(t){this._ticker.type=t}get latencyHint(){return this._latencyHint}_setLatencyHint(t){let e=0;if(this._latencyHint=t,b(t))switch(t){case"interactive":e=.1;break;case"playback":e=.5;break;case"balanced":e=.25}this.lookAhead=e,this.updateInterval=e/2}get rawContext(){return this._context}now(){return this._context.currentTime+this.lookAhead}immediate(){return this._context.currentTime}resume(){return"suspended"===this._context.state&&M(this._context)?this._context.resume():Promise.resolve()}close(){return S(this,void 0,void 0,(function*(){var t;M(this._context)&&(yield this._context.close()),this._initialized&&(t=this,Y.forEach(e=>e(t)))}))}getConstant(t){if(this._constants.has(t))return this._constants.get(t);{const e=this._context.createBuffer(1,128,this._context.sampleRate),n=e.getChannelData(0);for(let e=0;ethis._constants[t].disconnect()),this}_timeoutLoop(){const t=this.now();let e=this._timeouts.peek();for(;this._timeouts.length&&e&&e.time<=t;)e.callback(),this._timeouts.shift(),e=this._timeouts.peek()}setTimeout(t,e){this._timeoutIds++;const n=this.now();return this._timeouts.add({callback:t,id:this._timeoutIds,time:n+e}),this._timeoutIds}clearTimeout(t){return this._timeouts.forEach(e=>{e.id===t&&this._timeouts.remove(e)}),this}clearInterval(t){return this.clearTimeout(t)}setInterval(t,e){const n=++this._timeoutIds,s=()=>{const i=this.now();this._timeouts.add({callback:()=>{t(),s()},id:n,time:i+e})};return s(),n}}function $(t,e){y(e)?e.forEach(e=>$(t,e)):Object.defineProperty(t,e,{enumerable:!0,writable:!1})}function J(t,e){y(e)?e.forEach(e=>J(t,e)):Object.defineProperty(t,e,{writable:!0})}const K=()=>{};class tt extends V{constructor(){super(),this.name="ToneAudioBuffer",this.onload=K;const t=q(tt.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=t.reverse,this.onload=t.onload,t.url&&j(t.url)||t.url instanceof tt?this.set(t.url):b(t.url)&&this.load(t.url).catch(t.onerror)}static getDefaults(){return{onerror:K,onload:K,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:it().sampleRate}set(t){return t instanceof tt?t.loaded?this._buffer=t.get():t.onload=()=>{this.set(t),this.onload(this)}:this._buffer=t,this._reversed&&this._reverse(),this}get(){return this._buffer}load(t){return S(this,void 0,void 0,(function*(){const e=tt.load(t).then(t=>{this.set(t),this.onload(this)});tt.downloads.push(e);try{yield e}finally{const t=tt.downloads.indexOf(e);tt.downloads.splice(t,1)}return this}))}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(t){const e=y(t)&&t[0].length>0,n=e?t.length:1,s=e?t[0].length:t.length,i=it(),o=i.createBuffer(n,s,i.sampleRate),r=e||1!==n?t:[t];for(let t=0;tt/e),this.fromArray(t)}return this}toArray(t){if(m(t))return this.getChannelData(t);if(1===this.numberOfChannels)return this.toArray(0);{const t=[];for(let e=0;e0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(t){this._reversed!==t&&(this._reversed=t,this._reverse())}static fromArray(t){return(new tt).fromArray(t)}static fromUrl(t){return S(this,void 0,void 0,(function*(){const e=new tt;return yield e.load(t)}))}static load(t){return S(this,void 0,void 0,(function*(){const e=t.match(/\[(.+\|?)+\]$/);if(e){const n=e[1].split("|");let s=n[0];for(const t of n)if(tt.supportsType(t)){s=t;break}t=t.replace(e[0],s)}const n=""===tt.baseUrl||tt.baseUrl.endsWith("/")?tt.baseUrl:tt.baseUrl+"/",s=yield fetch(n+t);if(!s.ok)throw new Error("could not load url: "+t);const i=yield s.arrayBuffer();return yield it().decodeAudioData(i)}))}static supportsType(t){const e=t.split("."),n=e[e.length-1];return""!==document.createElement("audio").canPlayType("audio/"+n)}static loaded(){return S(this,void 0,void 0,(function*(){for(yield Promise.resolve();tt.downloads.length;)yield tt.downloads[0]}))}}tt.baseUrl="",tt.downloads=[];class et extends H{constructor(){var t,e,n;super({clockSource:"offline",context:D(arguments[0])?arguments[0]:(t=arguments[0],e=arguments[1]*arguments[2],n=arguments[2],new o.OfflineAudioContext(t,e,n)),lookAhead:0,updateInterval:D(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=D(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(t){return S(this,void 0,void 0,(function*(){let e=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,e++;const n=Math.floor(this.sampleRate/128);t&&e%n==0&&(yield new Promise(t=>setTimeout(t,1)))}}))}render(t=!0){return S(this,void 0,void 0,(function*(){yield this.workletsAreReady(),yield this._renderClock(t);const e=yield this._context.startRendering();return new tt(e)}))}close(){return Promise.resolve()}}const nt=new class extends X{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(t,e,n){return{}}createChannelMerger(t){return{}}createChannelSplitter(t){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(t){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(t,e){return{}}createPanner(){return{}}createPeriodicWave(t,e,n){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(t){return{}}createMediaStreamDestination(){return{}}decodeAudioData(t){return Promise.resolve({})}createAudioWorkletNode(t,e){return{}}get rawContext(){return{}}addAudioWorkletModule(t,e){return S(this,void 0,void 0,(function*(){return Promise.resolve()}))}resume(){return Promise.resolve()}setTimeout(t,e){return 0}clearTimeout(t){return this}setInterval(t,e){return 0}clearInterval(t){return this}getConstant(t){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(t){}get destination(){return{}}set destination(t){}now(){return 0}immediate(){return 0}};let st=nt;function it(){return st===nt&&T&&ot(new H),st}function ot(t){st=M(t)?new H(t):D(t)?new et(t):t}function rt(){return st.resume()}if(w&&!w.TONE_SILENCE_LOGGING){let t="v";"dev"===i&&(t="");const e=` * Tone.js ${t}${i} * `;console.log("%c"+e,"background: #000; color: #fff")}function at(t){return Math.pow(10,t/20)}function ct(t){return Math.log(t)/Math.LN10*20}function ut(t){return Math.pow(2,t/12)}let ht=440;function lt(t){return Math.round(dt(t))}function dt(t){return 69+12*Math.log2(t/ht)}function pt(t){return ht*Math.pow(2,(t-69)/12)}class ft extends V{constructor(t,e,n){super(),this.defaultUnits="s",this._val=e,this._units=n,this.context=t,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:t=>this._frequencyToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:t=>this._ticksToUnits(parseInt(t,10)),regexp:/^(\d+)i$/i},m:{method:t=>this._beatsToUnits(parseInt(t,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(t,e)=>{const n=parseInt(t,10),s="."===e?1.5:1;return 1===n?this._beatsToUnits(this._getTimeSignature())*s:this._beatsToUnits(4/n)*s},regexp:/^(\d+)n(\.?)$/i},number:{method:t=>this._expressions[this.defaultUnits].method.call(this,t),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:t=>this._secondsToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:t=>parseInt(t,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:t=>{const e=parseInt(t,10);return this._beatsToUnits(8/(3*Math.floor(e)))},regexp:/^(\d+)t$/i},tr:{method:(t,e,n)=>{let s=0;return t&&"0"!==t&&(s+=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s+=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s+=this._beatsToUnits(parseFloat(n)/4)),s},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ft&&this.fromType(this._val),p(this._val))return this._noArg();if(b(this._val)&&p(this._units)){for(const t in this._expressions)if(this._expressions[t].regexp.test(this._val.trim())){this._units=t;break}}else if(g(this._val)){let t=0;for(const e in this._val)if(f(this._val[e])){const n=this._val[e];t+=new this.constructor(this.context,e).valueOf()*n}return t}if(f(this._units)){const t=this._expressions[this._units],e=this._val.toString().trim().match(t.regexp);return e?t.method.apply(this,e.slice(1)):t.method.call(this,this._val)}return b(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(t){return 1/t}_beatsToUnits(t){return 60/this._getBpm()*t}_secondsToUnits(t){return t}_ticksToUnits(t){return t*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(t){switch(this._units=void 0,this.defaultUnits){case"s":this._val=t.toSeconds();break;case"i":this._val=t.toTicks();break;case"hz":this._val=t.toFrequency();break;case"midi":this._val=t.toMidi()}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return 1e3*this.toSeconds()}}class _t extends ft{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:t=>this._now()+new this.constructor(this.context,t).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{const e=new _t(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(e))},regexp:/^@(.+)/}})}quantize(t,e=1){const n=new this.constructor(this.context,t).valueOf(),s=this.valueOf();return s+(Math.round(s/n)*n-s)*e}toNotation(){const t=this.toSeconds(),e=["1m"];for(let t=1;t<9;t++){const n=Math.pow(2,t);e.push(n+"n."),e.push(n+"n"),e.push(n+"t")}e.push("0");let n=e[0],s=new _t(this.context,e[0]).toSeconds();return e.forEach(e=>{const i=new _t(this.context,e).toSeconds();Math.abs(i-t)3&&(s=parseFloat(parseFloat(i).toFixed(3))),[n,e,s].join(":")}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.round(e*this._getPPQ())}toSeconds(){return this.valueOf()}toMidi(){return lt(this.toFrequency())}_now(){return this.context.now()}}function mt(t,e){return new _t(it(),t,e)}class gt extends _t{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return ht}static set A4(t){!function(t){ht=t}(t)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(t){return"midi"===this.defaultUnits?t:gt.mtof(t)}},note:{regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method(t,e){const n=vt[t.toLowerCase()]+12*(parseInt(e,10)+1);return"midi"===this.defaultUnits?n:gt.mtof(n)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(t,e,n){let s=1;return t&&"0"!==t&&(s*=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s*=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s*=this._beatsToUnits(parseFloat(n)/4)),s}}})}transpose(t){return new gt(this.context,this.valueOf()*ut(t))}harmonize(t){return t.map(t=>this.transpose(t))}toMidi(){return lt(this.valueOf())}toNote(){const t=this.toFrequency(),e=Math.log2(t/gt.A4);let n=Math.round(12*e)+57;const s=Math.floor(n/12);return s<0&&(n+=-12*s),yt[n%12]+s.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.floor(e*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(t){return t}_ticksToUnits(t){return 1/(60*t/(this._getBpm()*this._getPPQ()))}_beatsToUnits(t){return 1/super._beatsToUnits(t)}_secondsToUnits(t){return 1/t}static mtof(t){return pt(t)}static ftom(t){return lt(t)}}const vt={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},yt=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function bt(t,e){return new gt(it(),t,e)}class xt extends _t{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}function wt(t,e){return new xt(it(),t,e)}class Tt extends V{constructor(){super();const t=q(Tt.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:it()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(t){return new _t(this.context,t).toSeconds()}toFrequency(t){return new gt(this.context,t).toFrequency()}toTicks(t){return new xt(this.context,t).toTicks()}_getPartialProperties(t){const e=this.get();return Object.keys(e).forEach(n=>{p(t[n])&&delete e[n]}),e}get(){const t=this.constructor.getDefaults();return Object.keys(t).forEach(e=>{if(Reflect.has(this,e)){const n=this[e];f(n)&&f(n.value)&&f(n.setValueAtTime)?t[e]=n.value:n instanceof Tt?t[e]=n._getPartialProperties(t[e]):y(n)||m(n)||b(n)||v(n)?t[e]=n:delete t[e]}}),t}set(t){return Object.keys(t).forEach(e=>{Reflect.has(this,e)&&f(this[e])&&(this[e]&&f(this[e].value)&&f(this[e].setValueAtTime)?this[e].value!==t[e]&&(this[e].value=t[e]):this[e]instanceof Tt?this[e].set(t[e]):this[e]=t[e])}),this}}class Ot extends W{constructor(t="stopped"){super(),this.name="StateTimeline",this._initial=t,this.setStateAtTime(this._initial,0)}getValueAtTime(t){const e=this.get(t);return null!==e?e.state:this._initial}setStateAtTime(t,e,n){return a(e,0),this.add(Object.assign({},n,{state:t,time:e})),this}getLastState(t,e){for(let n=this._search(e);n>=0;n--){const e=this._timeline[n];if(e.state===t)return e}}getNextState(t,e){const n=this._search(e);if(-1!==n)for(let e=n;e0,"timeConstant must be a number greater than 0");const i=this.toSeconds(e);return this._assertRange(s),r(isFinite(s)&&isFinite(i),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(t)}, ${JSON.stringify(e)}`),this._events.add({constant:n,time:i,type:"setTargetAtTime",value:s}),this.log(this.units,"setTargetAtTime",t,i,n),this._param.setTargetAtTime(s,i,n),this}setValueCurveAtTime(t,e,n,s=1){n=this.toSeconds(n),e=this.toSeconds(e);const i=this._fromType(t[0])*s;this.setValueAtTime(this._toType(i),e);const o=n/(t.length-1);for(let n=1;n{"cancelScheduledValues"===e.type?t.cancelScheduledValues(e.time):"setTargetAtTime"===e.type?t.setTargetAtTime(e.value,e.time,e.constant):t[e.type](e.value,e.time)}),this}setParam(t){r(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const e=this.input;return e.disconnect(this._param),this.apply(t),this._param=t,e.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(t,e,n,s,i){return n+(e-n)*Math.exp(-(i-t)/s)}_linearInterpolate(t,e,n,s,i){return e+(i-t)/(n-t)*(s-e)}_exponentialInterpolate(t,e,n,s,i){return e*Math.pow(s/e,(i-t)/(n-t))}}class Ct extends Tt{constructor(){super(...arguments),this.name="ToneAudioNode",this._internalChannels=[]}get numberOfInputs(){return f(this.input)?k(this.input)||this.input instanceof St?1:this.input.numberOfInputs:0}get numberOfOutputs(){return f(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return f(t)&&(t instanceof Ct||A(t))}_getInternalNodes(){const t=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&t.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&t.push(this.output),t}_setChannelProperties(t){this._getInternalNodes().forEach(e=>{e.channelCount=t.channelCount,e.channelCountMode=t.channelCountMode,e.channelInterpretation=t.channelInterpretation})}_getChannelProperties(){const t=this._getInternalNodes();r(t.length>0,"ToneAudioNode does not have any internal nodes");const e=t[0];return{channelCount:e.channelCount,channelCountMode:e.channelCountMode,channelInterpretation:e.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCount:t}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCountMode:t}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelInterpretation:t}))}connect(t,e=0,n=0){return At(this,t,e,n),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return d("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(t,e=0,n=0){return Dt(this,t,e,n),this}chain(...t){return kt(this,...t),this}fan(...t){return t.forEach(t=>this.connect(t)),this}dispose(){return super.dispose(),f(this.input)&&(this.input instanceof Ct?this.input.dispose():A(this.input)&&this.input.disconnect()),f(this.output)&&(this.output instanceof Ct?this.output.dispose():A(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function kt(...t){const e=t.shift();t.reduce((t,e)=>(t instanceof Ct?t.connect(e):A(t)&&At(t,e),e),e)}function At(t,e,n=0,s=0){for(r(f(t),"Cannot connect from undefined node"),r(f(e),"Cannot connect to undefined node"),(e instanceof Ct||A(e))&&r(e.numberOfInputs>0,"Cannot connect to node with no inputs"),r(t.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof Ct||e instanceof St;)f(e.input)&&(e=e.input);for(;t instanceof Ct;)f(t.output)&&(t=t.output);k(e)?t.connect(e,n):t.connect(e,n,s)}function Dt(t,e,n=0,s=0){if(f(e))for(;e instanceof Ct;)e=e.input;for(;!A(t);)f(t.output)&&(t=t.output);k(e)?t.disconnect(e,n):A(e)?t.disconnect(e,n,s):t.disconnect()}class Mt extends Ct{constructor(){super(q(Mt.getDefaults(),arguments,["gain","units"])),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode;const t=q(Mt.getDefaults(),arguments,["gain","units"]);this.gain=new St({context:this.context,convert:t.convert,param:this._gainNode.gain,units:t.units,value:t.gain,minValue:t.minValue,maxValue:t.maxValue}),$(this,"gain")}static getDefaults(){return Object.assign(Ct.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class jt extends Ct{constructor(t){super(t),this.onended=K,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new Mt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(t){const e=this.toSeconds(t);return-1!==this._startTime&&e>=this._startTime&&(-1===this._stopTime||e<=this._stopTime)?"started":"stopped"},this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut,this._curve=t.curve,this.onended=t.onended}static getDefaults(){return Object.assign(Ct.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:K})}_startGain(t,e=1){r(-1===this._startTime,"Source cannot be started more than once");const n=this.toSeconds(this._fadeIn);return this._startTime=t+n,this._startTime=Math.max(this._startTime,this.context.currentTime),n>0?(this._gainNode.gain.setValueAtTime(0,t),"linear"===this._curve?this._gainNode.gain.linearRampToValueAtTime(e,t+n):this._gainNode.gain.exponentialApproachValueAtTime(e,t,n)):this._gainNode.gain.setValueAtTime(e,t),this}stop(t){return this.log("stop",t),this._stopGain(this.toSeconds(t)),this}_stopGain(t){r(-1!==this._startTime,"'start' must be called before 'stop'"),this.cancelStop();const e=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(t)+e,this._stopTime=Math.max(this._stopTime,this.context.currentTime),e>0?"linear"===this._curve?this._gainNode.gain.linearRampTo(0,e,t):this._gainNode.gain.targetRampTo(0,e,t):(this._gainNode.gain.cancelAndHoldAtTime(t),this._gainNode.gain.setValueAtTime(0,t)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const t="exponential"===this._curve?2*e:0;this._stopSource(this.now()+t),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==K&&(this.onended(this),this.onended=K,!this.context.isOffline)){const t=()=>this.dispose();void 0!==window.requestIdleCallback?window.requestIdleCallback(t):setTimeout(t,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),r(-1!==this._startTime,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.disconnect(),this}}class Et extends jt{constructor(){super(q(Et.getDefaults(),arguments,["offset"])),this.name="ToneConstantSource",this._source=this.context.createConstantSource();const t=q(Et.getDefaults(),arguments,["offset"]);At(this._source,this._gainNode),this.offset=new St({context:this.context,convert:t.convert,param:this._source.offset,units:t.units,value:t.offset,minValue:t.minValue,maxValue:t.maxValue})}static getDefaults(){return Object.assign(jt.getDefaults(),{convert:!0,offset:1,units:"number"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._source.start(e),this}_stopSource(t){this._source.stop(t)}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class Rt extends Ct{constructor(){super(q(Rt.getDefaults(),arguments,["value","units"])),this.name="Signal",this.override=!0;const t=q(Rt.getDefaults(),arguments,["value","units"]);this.output=this._constantSource=new Et({context:this.context,convert:t.convert,offset:t.value,units:t.units,minValue:t.minValue,maxValue:t.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(Ct.getDefaults(),{convert:!0,units:"number",value:0})}connect(t,e=0,n=0){return qt(this,t,e,n),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(t,e){return this._param.setValueAtTime(t,e),this}getValueAtTime(t){return this._param.getValueAtTime(t)}setRampPoint(t){return this._param.setRampPoint(t),this}linearRampToValueAtTime(t,e){return this._param.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){return this._param.exponentialRampToValueAtTime(t,e),this}exponentialRampTo(t,e,n){return this._param.exponentialRampTo(t,e,n),this}linearRampTo(t,e,n){return this._param.linearRampTo(t,e,n),this}targetRampTo(t,e,n){return this._param.targetRampTo(t,e,n),this}exponentialApproachValueAtTime(t,e,n){return this._param.exponentialApproachValueAtTime(t,e,n),this}setTargetAtTime(t,e,n){return this._param.setTargetAtTime(t,e,n),this}setValueCurveAtTime(t,e,n,s){return this._param.setValueCurveAtTime(t,e,n,s),this}cancelScheduledValues(t){return this._param.cancelScheduledValues(t),this}cancelAndHoldAtTime(t){return this._param.cancelAndHoldAtTime(t),this}rampTo(t,e,n){return this._param.rampTo(t,e,n),this}get value(){return this._param.value}set value(t){this._param.value=t}get convert(){return this._param.convert}set convert(t){this._param.convert=t}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(t){this._param.overridden=t}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(t){return this._param.apply(t),this}}function qt(t,e,n,s){(e instanceof St||k(e)||e instanceof Rt&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof Rt&&(e.overridden=!0)),At(t,e,n,s)}class It extends St{constructor(){super(q(It.getDefaults(),arguments,["value"])),this.name="TickParam",this._events=new W(1/0),this._multiplier=1;const t=q(It.getDefaults(),arguments,["value"]);this._multiplier=t.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(t.value)}),this.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(St.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(t,e,n){e=this.toSeconds(e),this.setRampPoint(e);const s=this._fromType(t),i=this._events.get(e),o=Math.round(Math.max(1/n,1));for(let t=0;t<=o;t++){const o=n*t+e,r=this._exponentialApproach(i.time,i.value,s,n,o);this.linearRampToValueAtTime(this._toType(r),o)}return this}setValueAtTime(t,e){const n=this.toSeconds(e);super.setValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),o=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(o,0),this}linearRampToValueAtTime(t,e){const n=this.toSeconds(e);super.linearRampToValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),o=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(t,e){e=this.toSeconds(e);const n=this._fromType(t),s=this._events.get(e),i=Math.round(Math.max(10*(e-s.time),1)),o=(e-s.time)/i;for(let t=0;t<=i;t++){const i=o*t+s.time,r=this._exponentialInterpolate(s.time,s.value,e,n,i);this.linearRampToValueAtTime(this._toType(r),i)}return this}_getTicksUntilEvent(t,e){if(null===t)t={ticks:0,time:0,type:"setValueAtTime",value:0};else if(p(t.ticks)){const e=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(e,t.time)}const n=this._fromType(this.getValueAtTime(t.time));let s=this._fromType(this.getValueAtTime(e));const i=this._events.get(e);return i&&i.time===e&&"setValueAtTime"===i.type&&(s=this._fromType(this.getValueAtTime(e-this.sampleTime))),.5*(e-t.time)*(n+s)+t.ticks}getTicksAtTime(t){const e=this.toSeconds(t),n=this._events.get(e);return Math.max(this._getTicksUntilEvent(n,e),0)}getDurationOfTicks(t,e){const n=this.toSeconds(e),s=this.getTicksAtTime(e);return this.getTimeOfTick(s+t)-n}getTimeOfTick(t){const e=this._events.get(t,"ticks"),n=this._events.getAfter(t,"ticks");if(e&&e.ticks===t)return e.time;if(e&&n&&"linearRampToValueAtTime"===n.type&&e.value!==n.value){const s=this._fromType(this.getValueAtTime(e.time)),i=(this._fromType(this.getValueAtTime(n.time))-s)/(n.time-e.time),o=Math.sqrt(Math.pow(s,2)-2*i*(e.ticks-t)),r=(-s+o)/i,a=(-s-o)/i;return(r>0?r:a)+e.time}return e?0===e.value?1/0:e.time+(t-e.ticks)/e.value:t/this._initialValue}ticksToTime(t,e){return this.getDurationOfTicks(t,e)}timeToTicks(t,e){const n=this.toSeconds(e),s=this.toSeconds(t),i=this.getTicksAtTime(n);return this.getTicksAtTime(n+s)-i}_fromType(t){return"bpm"===this.units&&this.multiplier?1/(60/t/this.multiplier):super._fromType(t)}_toType(t){return"bpm"===this.units&&this.multiplier?t/this.multiplier*60:super._toType(t)}get multiplier(){return this._multiplier}set multiplier(t){const e=this.value;this._multiplier=t,this.cancelScheduledValues(0),this.setValueAtTime(e,0)}}class Ft extends Rt{constructor(){super(q(Ft.getDefaults(),arguments,["value"])),this.name="TickSignal";const t=q(Ft.getDefaults(),arguments,["value"]);this.input=this._param=new It({context:this.context,convert:t.convert,multiplier:t.multiplier,param:this._constantSource.offset,units:t.units,value:t.value})}static getDefaults(){return Object.assign(Rt.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(t,e){return this._param.ticksToTime(t,e)}timeToTicks(t,e){return this._param.timeToTicks(t,e)}getTimeOfTick(t){return this._param.getTimeOfTick(t)}getDurationOfTicks(t,e){return this._param.getDurationOfTicks(t,e)}getTicksAtTime(t){return this._param.getTicksAtTime(t)}get multiplier(){return this._param.multiplier}set multiplier(t){this._param.multiplier=t}dispose(){return super.dispose(),this._param.dispose(),this}}class Vt extends Tt{constructor(){super(q(Vt.getDefaults(),arguments,["frequency"])),this.name="TickSource",this._state=new Ot,this._tickOffset=new W;const t=q(Vt.getDefaults(),arguments,["frequency"]);this.frequency=new Ft({context:this.context,units:t.units,value:t.frequency}),$(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},Tt.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(t,e){const n=this.toSeconds(t);return"started"!==this._state.getValueAtTime(n)&&(this._state.setStateAtTime("started",n),f(e)&&this.setTicksAtTime(e,n)),this}stop(t){const e=this.toSeconds(t);if("stopped"===this._state.getValueAtTime(e)){const t=this._state.get(e);t&&t.time>0&&(this._tickOffset.cancel(t.time),this._state.cancel(t.time))}return this._state.cancel(e),this._state.setStateAtTime("stopped",e),this.setTicksAtTime(0,e),this}pause(t){const e=this.toSeconds(t);return"started"===this._state.getValueAtTime(e)&&this._state.setStateAtTime("paused",e),this}cancel(t){return t=this.toSeconds(t),this._state.cancel(t),this._tickOffset.cancel(t),this}getTicksAtTime(t){const e=this.toSeconds(t),n=this._state.getLastState("stopped",e),s={state:"paused",time:e};this._state.add(s);let i=n,o=0;return this._state.forEachBetween(n.time,e+this.sampleTime,t=>{let e=i.time;const n=this._tickOffset.get(t.time);n&&n.time>=i.time&&(o=n.ticks,e=n.time),"started"===i.state&&"started"!==t.state&&(o+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e)),i=t}),this._state.remove(s),o}get ticks(){return this.getTicksAtTime(this.now())}set ticks(t){this.setTicksAtTime(t,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(t){const e=this.now(),n=this.frequency.timeToTicks(t,e);this.setTicksAtTime(n,e)}getSecondsAtTime(t){t=this.toSeconds(t);const e=this._state.getLastState("stopped",t),n={state:"paused",time:t};this._state.add(n);let s=e,i=0;return this._state.forEachBetween(e.time,t+this.sampleTime,t=>{let e=s.time;const n=this._tickOffset.get(t.time);n&&n.time>=s.time&&(i=n.seconds,e=n.time),"started"===s.state&&"started"!==t.state&&(i+=t.time-e),s=t}),this._state.remove(n),i}setTicksAtTime(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(t,e),ticks:t,time:e}),this}getStateAtTime(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)}getTimeOfTick(t,e=this.now()){const n=this._tickOffset.get(e),s=this._state.get(e),i=Math.max(n.time,s.time),o=this.frequency.getTicksAtTime(i)+t-n.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(t,e,n){let s=this._state.get(t);this._state.forEachBetween(t,e,e=>{s&&"started"===s.state&&"started"!==e.state&&this.forEachTickBetween(Math.max(s.time,t),e.time-this.sampleTime,n),s=e});let i=null;if(s&&"started"===s.state){const o=Math.max(s.time,t),r=this.frequency.getTicksAtTime(o),a=r-this.frequency.getTicksAtTime(s.time);let c=Math.ceil(a)-a;c=z(c,1)?0:c;let u=this.frequency.getTimeOfTick(r+c);for(;u{switch(t.state){case"started":const e=this._tickSource.getTicksAtTime(t.time);this.emit("start",t.time,e);break;case"stopped":0!==t.time&&this.emit("stop",t.time);break;case"paused":this.emit("pause",t.time)}}),this._tickSource.forEachTickBetween(t,e,(t,e)=>{this.callback(t,e)}))}getStateAtTime(t){const e=this.toSeconds(t);return this._state.getValueAtTime(e)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Z.mixin(Nt);class Pt extends V{constructor(t){super(),this.name="TimelineValue",this._timeline=new W({memory:10}),this._initialValue=t}set(t,e){return this._timeline.add({value:t,time:e}),this}get(t){const e=this._timeline.get(t);return e?e.value:this._initialValue}}class Lt extends xt{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(t){return this._getPPQ()*t}_secondsToUnits(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(t){return t}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}function zt(t,e){return new Lt(it(),t,e)}class Bt extends V{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(t){r(f(t.time),"Events must have a time property"),r(f(t.duration),"Events must have a duration parameter"),t.time=t.time.valueOf();let e=new Wt(t.time,t.time+t.duration,t);for(null===this._root?this._root=e:this._root.insert(e),this._length++;null!==e;)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this}remove(t){if(null!==this._root){const e=[];this._root.search(t.time,e);for(const n of e)if(n.event===t){this._removeNode(n),this._length--;break}}return this}get length(){return this._length}cancel(t){return this.forEachFrom(t,t=>this.remove(t)),this}_setRoot(t){this._root=t,null!==this._root&&(this._root.parent=null)}_replaceNodeInParent(t,e){null!==t.parent?(t.isLeftChild()?t.parent.left=e:t.parent.right=e,this._rebalance(t.parent)):this._setRoot(e)}_removeNode(t){if(null===t.left&&null===t.right)this._replaceNodeInParent(t,null);else if(null===t.right)this._replaceNodeInParent(t,t.left);else if(null===t.left)this._replaceNodeInParent(t,t.right);else{let e,n=null;if(t.getBalance()>0)if(null===t.left.right)e=t.left,e.right=t.right,n=e;else{for(e=t.left.right;null!==e.right;)e=e.right;e.parent&&(e.parent.right=e.left,n=e.parent,e.left=t.left,e.right=t.right)}else if(null===t.right.left)e=t.right,e.left=t.left,n=e;else{for(e=t.right.left;null!==e.left;)e=e.left;e.parent&&(e.parent.left=e.right,n=e.parent,e.left=t.left,e.right=t.right)}null!==t.parent?t.isLeftChild()?t.parent.left=e:t.parent.right=e:this._setRoot(e),n&&this._rebalance(n)}t.dispose()}_rotateLeft(t){const e=t.parent,n=t.isLeftChild(),s=t.right;s&&(t.right=s.left,s.left=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rotateRight(t){const e=t.parent,n=t.isLeftChild(),s=t.left;s&&(t.left=s.right,s.right=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rebalance(t){const e=t.getBalance();e>1&&t.left?t.left.getBalance()<0?this._rotateLeft(t.left):this._rotateRight(t):e<-1&&t.right&&(t.right.getBalance()>0?this._rotateRight(t.right):this._rotateLeft(t))}get(t){if(null!==this._root){const e=[];if(this._root.search(t,e),e.length>0){let t=e[0];for(let n=1;nt.low&&(t=e[n]);return t.event}}return null}forEach(t){if(null!==this._root){const e=[];this._root.traverse(t=>e.push(t)),e.forEach(e=>{e.event&&t(e.event)})}return this}forEachAtTime(t,e){if(null!==this._root){const n=[];this._root.search(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}forEachFrom(t,e){if(null!==this._root){const n=[];this._root.searchAfter(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}dispose(){return super.dispose(),null!==this._root&&this._root.traverse(t=>t.dispose()),this._root=null,this}}class Wt{constructor(t,e,n){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=n,this.low=t,this.high=e,this.max=this.high}insert(t){t.low<=this.low?null===this.left?this.left=t:this.left.insert(t):null===this.right?this.right=t:this.right.insert(t)}search(t,e){t>this.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))}searchAfter(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)}traverse(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)}updateHeight(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t}isLeftChild(){return null!==this.parent&&this.parent.left===this}get left(){return this._left}set left(t){this._left=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(t){this._right=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class Ut{constructor(t,e){this.id=Ut._eventId++;const n=Object.assign(Ut.getDefaults(),e);this.transport=t,this.callback=n.callback,this._once=n.once,this.time=n.time}static getDefaults(){return{callback:K,once:!1,time:0}}invoke(t){this.callback&&(this.callback(t),this._once&&this.transport.clear(this.id))}dispose(){return this.callback=void 0,this}}Ut._eventId=0;class Gt extends Ut{constructor(t,e){super(t,e),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const n=Object.assign(Gt.getDefaults(),e);this.duration=new Lt(t.context,n.duration).valueOf(),this._interval=new Lt(t.context,n.interval).valueOf(),this._nextTick=n.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Ut.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(t){this._createEvents(t),super.invoke(t)}_createEvents(t){const e=this.transport.getTicksAtTime(t);e>=this.time&&e>=this._nextTick&&this._nextTick+this._intervalthis.time&&(this._nextTick=this.time+Math.ceil((e-this.time)/this._interval)*this._interval),this._currentId=this.transport.scheduleOnce(this.invoke.bind(this),new Lt(this.context,this._nextTick).toSeconds()),this._nextTick+=this._interval,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Lt(this.context,this._nextTick).toSeconds())}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this}}class Yt extends Tt{constructor(){super(q(Yt.getDefaults(),arguments)),this.name="Transport",this._loop=new Pt(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new W,this._repeatedEvents=new Bt,this._syncedSignals=[],this._swingAmount=0;const t=q(Yt.getDefaults(),arguments);this._ppq=t.ppq,this._clock=new Nt({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=t.ppq,this.bpm.setValueAtTime(t.bpm,0),$(this,"bpm"),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(Tt.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(t,e){if(this._swingAmount>0&&e%this._ppq!=0&&e%(2*this._swingTicks)!=0){const n=e%(2*this._swingTicks)/(2*this._swingTicks),s=Math.sin(n*Math.PI)*this._swingAmount;t+=new Lt(this.context,2*this._swingTicks/3).toSeconds()*s}this._loop.get(t)&&e>=this._loopEnd&&(this.emit("loopEnd",t),this._clock.setTicksAtTime(this._loopStart,t),e=this._loopStart,this.emit("loopStart",t,this._clock.getSecondsAtTime(t)),this.emit("loop",t)),this._timeline.forEachAtTime(e,e=>e.invoke(t))}schedule(t,e){const n=new Ut(this,{callback:t,time:new xt(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}scheduleRepeat(t,e,n,s=1/0){const i=new Gt(this,{callback:t,duration:new _t(this.context,s).toTicks(),interval:new _t(this.context,e).toTicks(),time:new xt(this.context,n).toTicks()});return this._addEvent(i,this._repeatedEvents)}scheduleOnce(t,e){const n=new Ut(this,{callback:t,once:!0,time:new xt(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}clear(t){if(this._scheduledEvents.hasOwnProperty(t)){const e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this}_addEvent(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id}cancel(t=0){const e=this.toTicks(t);return this._timeline.forEachFrom(e,t=>this.clear(t.id)),this._repeatedEvents.forEachFrom(e,t=>this.clear(t.id)),this}_bindClockEvents(){this._clock.on("start",(t,e)=>{e=new Lt(this.context,e).toSeconds(),this.emit("start",t,e)}),this._clock.on("stop",t=>{this.emit("stop",t)}),this._clock.on("pause",t=>{this.emit("pause",t)})}get state(){return this._clock.getStateAtTime(this.now())}start(t,e){let n;return f(e)&&(n=this.toTicks(e)),this._clock.start(t,n),this}stop(t){return this._clock.stop(t),this}pause(t){return this._clock.pause(t),this}toggle(t){return t=this.toSeconds(t),"started"!==this._clock.getStateAtTime(t)?this.start(t):this.stop(t),this}get timeSignature(){return this._timeSignature}set timeSignature(t){y(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}get loopStart(){return new _t(this.context,this._loopStart,"i").toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t)}get loopEnd(){return new _t(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t)}get loop(){return this._loop.get(this.now())}set loop(t){this._loop.set(t,this.now())}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get swing(){return this._swingAmount}set swing(t){this._swingAmount=t}get swingSubdivision(){return new Lt(this.context,this._swingTicks).toNotation()}set swingSubdivision(t){this._swingTicks=this.toTicks(t)}get position(){const t=this.now(),e=this._clock.getTicksAtTime(t);return new Lt(this.context,e).toBarsBeatsSixteenths()}set position(t){const e=this.toTicks(t);this.ticks=e}get seconds(){return this._clock.seconds}set seconds(t){const e=this.now(),n=this._clock.frequency.timeToTicks(t,e);this.ticks=n}get progress(){if(this.loop){const t=this.now();return(this._clock.getTicksAtTime(t)-this._loopStart)/(this._loopEnd-this._loopStart)}return 0}get ticks(){return this._clock.ticks}set ticks(t){if(this._clock.ticks!==t){const e=this.now();if("started"===this.state){const n=this._clock.getTicksAtTime(e),s=this._clock.getTimeOfTick(Math.ceil(n));this.emit("stop",s),this._clock.setTicksAtTime(t,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this._clock.setTicksAtTime(t,e)}}getTicksAtTime(t){return Math.round(this._clock.getTicksAtTime(t))}getSecondsAtTime(t){return this._clock.getSecondsAtTime(t)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(t){this._clock.frequency.multiplier=t}nextSubdivision(t){if(t=this.toTicks(t),"started"!==this.state)return 0;{const e=this.now(),n=t-this.getTicksAtTime(e)%t;return this._clock.nextTickTime(n,e)}}syncSignal(t,e){if(!e){const n=this.now();if(0!==t.getValueAtTime(n)){const s=1/(60/this.bpm.getValueAtTime(n)/this.PPQ);e=t.getValueAtTime(n)/s}else e=0}const n=new Mt(e);return this.bpm.connect(n),n.connect(t._param),this._syncedSignals.push({initial:t.value,ratio:n,signal:t}),t.value=0,this}unsyncSignal(t){for(let e=this._syncedSignals.length-1;e>=0;e--){const n=this._syncedSignals[e];n.signal===t&&(n.ratio.dispose(),n.signal.value=n.initial,this._syncedSignals.splice(e,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),J(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Z.mixin(Yt),G(t=>{t.transport=new Yt({context:t})}),Q(t=>{t.transport.dispose()});class Qt extends Ct{constructor(){super(q(Qt.getDefaults(),arguments,["delayTime","maxDelay"])),this.name="Delay";const t=q(Qt.getDefaults(),arguments,["delayTime","maxDelay"]),e=this.toSeconds(t.maxDelay);this._maxDelay=Math.max(e,this.toSeconds(t.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(e),this.delayTime=new St({context:this.context,param:this._delayNode.delayTime,units:"time",value:t.delayTime,minValue:0,maxValue:this.maxDelay}),$(this,"delayTime")}static getDefaults(){return Object.assign(Ct.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Zt extends Ct{constructor(){super(q(Zt.getDefaults(),arguments,["volume"])),this.name="Volume";const t=q(Zt.getDefaults(),arguments,["volume"]);this.input=this.output=new Mt({context:this.context,gain:t.volume,units:"decibels"}),this.volume=this.output.gain,$(this,"volume"),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class Xt extends Ct{constructor(){super(q(Xt.getDefaults(),arguments)),this.name="Destination",this.input=new Zt({context:this.context}),this.output=new Mt({context:this.context}),this.volume=this.input.volume;const t=q(Xt.getDefaults(),arguments);kt(this.input,this.output,this.context.rawContext.destination),this.mute=t.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(t){this.input.mute=t}chain(...t){return this.input.disconnect(),t.unshift(this.input),t.push(this.output),kt(...t),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}function Ht(t,e,n=2,s=it().sampleRate){return S(this,void 0,void 0,(function*(){const i=it(),o=new et(n,e,s);ot(o),yield t(o);const r=o.render();ot(i);const a=yield r;return new tt(a)}))}G(t=>{t.destination=new Xt({context:t})}),Q(t=>{t.destination.dispose()});class $t extends V{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const t=q($t.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=t.baseUrl,Object.keys(t.urls).forEach(e=>{this._loadingCount++;const n=t.urls[e];this.add(e,n,this._bufferLoaded.bind(this,t.onload),t.onerror)})}static getDefaults(){return{baseUrl:"",onerror:K,onload:K,urls:{}}}has(t){return this._buffers.has(t.toString())}get(t){return r(this.has(t),"ToneAudioBuffers has no buffer named: "+t),this._buffers.get(t.toString())}_bufferLoaded(t){this._loadingCount--,0===this._loadingCount&&t&&t()}get loaded(){return Array.from(this._buffers).every(([t,e])=>e.loaded)}add(t,e,n=K,s=K){return b(e)?this._buffers.set(t.toString(),new tt(this.baseUrl+e,n,s)):this._buffers.set(t.toString(),new tt(e,n,s)),this}dispose(){return super.dispose(),this._buffers.forEach(t=>t.dispose()),this._buffers.clear(),this}}class Jt extends gt{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(t){return lt(super._frequencyToUnits(t))}_ticksToUnits(t){return lt(super._ticksToUnits(t))}_beatsToUnits(t){return lt(super._beatsToUnits(t))}_secondsToUnits(t){return lt(super._secondsToUnits(t))}toMidi(){return this.valueOf()}toFrequency(){return pt(this.toMidi())}transpose(t){return new Jt(this.context,this.toMidi()+t)}}function Kt(t,e){return new Jt(it(),t,e)}class te extends Tt{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new W,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(t,e){return this._events.add({callback:t,time:this.toSeconds(e)}),1===this._events.length&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(t){return this._events.cancel(this.toSeconds(t)),this}_drawLoop(){const t=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=t;){const e=this._events.shift();e&&t-e.time<=this.expiration&&e.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}G(t=>{t.draw=new te({context:t})}),Q(t=>{t.draw.dispose()});var ee=n(515);class ne extends Ct{constructor(t){super(t),this.input=void 0,this._state=new Ot("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=K,this._syncedStop=K,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Zt({context:this.context,mute:t.mute,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this.onstop=t.onstop}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,onstop:K,volume:0})}get state(){return this._synced?"started"===this.context.transport.state?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}_clampToCurrentTime(t){return this._synced?t:Math.max(t,this.context.currentTime)}start(t,e,n){let s=p(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(s=this._clampToCurrentTime(s),this._synced||"started"!==this._state.getValueAtTime(s))if(this.log("start",s),this._state.setStateAtTime("started",s),this._synced){const t=this._state.get(s);t&&(t.offset=this.toSeconds(I(e,0)),t.duration=n?this.toSeconds(n):void 0);const i=this.context.transport.schedule(t=>{this._start(t,e,n)},s);this._scheduled.push(i),"started"===this.context.transport.state&&this.context.transport.getSecondsAtTime(this.immediate())>s&&this._syncedStart(this.now(),this.context.transport.seconds)}else c(this.context),this._start(s,e,n);else r(N(s,this._state.get(s).time),"Start time must be strictly greater than previous start time"),this._state.cancel(s),this._state.setStateAtTime("started",s),this.log("restart",s),this.restart(s,e,n);return this}stop(t){let e=p(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(e=this._clampToCurrentTime(e),"started"===this._state.getValueAtTime(e)||f(this._state.getNextState("started",e))){if(this.log("stop",e),this._synced){const t=this.context.transport.schedule(this._stop.bind(this),e);this._scheduled.push(t)}else this._stop(e);this._state.cancel(e),this._state.setStateAtTime("stopped",e)}return this}restart(t,e,n){return t=this.toSeconds(t),"started"===this._state.getValueAtTime(t)&&(this._state.cancel(t),this._restart(t,e,n)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(t,e)=>{if(e>0){const n=this._state.get(e);if(n&&"started"===n.state&&n.time!==e){const s=e-this.toSeconds(n.time);let i;n.duration&&(i=this.toSeconds(n.duration)-s),this._start(t,this.toSeconds(n.offset)+s,i)}}},this._syncedStop=t=>{const e=this.context.transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));"started"===this._state.getValueAtTime(e)&&this._stop(t)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(t=>this.context.transport.clear(t)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=K,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class se extends jt{constructor(){super(q(se.getDefaults(),arguments,["url","onload"])),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1;const t=q(se.getDefaults(),arguments,["url","onload"]);At(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new St({context:this.context,param:this._source.playbackRate,units:"positive",value:t.playbackRate}),this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this._buffer=new tt(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(jt.getDefaults(),{url:new tt,loop:!1,loopEnd:0,loopStart:0,onload:K,onerror:K,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t}get curve(){return this._curve}set curve(t){this._curve=t}start(t,e,n,s=1){r(this.buffer.loaded,"buffer is either not set or not loaded");const i=this.toSeconds(t);this._startGain(i,s),e=this.loop?I(e,this.loopStart):I(e,0);let o=Math.max(this.toSeconds(e),0);if(this.loop){const t=this.toSeconds(this.loopEnd)||this.buffer.duration,e=this.toSeconds(this.loopStart),n=t-e;P(o,t)&&(o=(o-e)%n+e),z(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,L(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(i,o)),f(n)){let t=this.toSeconds(n);t=Math.max(t,0),this.stop(i+t)}return this}_stopSource(t){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(t)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(t){this._source.loopStart=this.toSeconds(t)}get loopEnd(){return this._source.loopEnd}set loopEnd(t){this._source.loopEnd=this.toSeconds(t)}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._source.loop}set loop(t){this._source.loop=t,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class ie extends ne{constructor(){super(q(ie.getDefaults(),arguments,["type"])),this.name="Noise",this._source=null;const t=q(ie.getDefaults(),arguments,["type"]);this._playbackRate=t.playbackRate,this.type=t.type,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(t){if(r(t in re,"Noise: invalid type: "+t),this._type!==t&&(this._type=t,"started"===this.state)){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._source&&(this._source.playbackRate.value=t)}_start(t){const e=re[this._type];this._source=new se({url:e,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(t),Math.random()*(e.duration-.001))}_stop(t){this._source&&(this._source.stop(this.toSeconds(t)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(t){this._stop(t),this._start(t)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const oe={brown:null,pink:null,white:null},re={get brown(){if(!oe.brown){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);t[e]=n;let s=0;for(let t=0;t<220500;t++){const e=2*Math.random()-1;n[t]=(s+.02*e)/1.02,s=n[t],n[t]*=3.5}}oe.brown=(new tt).fromArray(t)}return oe.brown},get pink(){if(!oe.pink){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);let s,i,o,r,a,c,u;t[e]=n,s=i=o=r=a=c=u=0;for(let t=0;t<220500;t++){const e=2*Math.random()-1;s=.99886*s+.0555179*e,i=.99332*i+.0750759*e,o=.969*o+.153852*e,r=.8665*r+.3104856*e,a=.55*a+.5329522*e,c=-.7616*c-.016898*e,n[t]=s+i+o+r+a+c+u+.5362*e,n[t]*=.11,u=.115926*e}}oe.pink=(new tt).fromArray(t)}return oe.pink},get white(){if(!oe.white){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);t[e]=n;for(let t=0;t<220500;t++)n[t]=2*Math.random()-1}oe.white=(new tt).fromArray(t)}return oe.white}};class ae extends Ct{constructor(){super(q(ae.getDefaults(),arguments,["volume"])),this.name="UserMedia";const t=q(ae.getDefaults(),arguments,["volume"]);this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this.mute=t.mute}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}open(t){return S(this,void 0,void 0,(function*(){r(ae.supported,"UserMedia is not supported"),"started"===this.state&&this.close();const e=yield ae.enumerateDevices();m(t)?this._device=e[t]:(this._device=e.find(e=>e.label===t||e.deviceId===t),!this._device&&e.length>0&&(this._device=e[0]),r(f(this._device),"No matching device "+t));const n={audio:{echoCancellation:!1,sampleRate:this.context.sampleRate,noiseSuppression:!1,mozNoiseSuppression:!1}};this._device&&(n.audio.deviceId=this._device.deviceId);const s=yield navigator.mediaDevices.getUserMedia(n);if(!this._stream){this._stream=s;const t=this.context.createMediaStreamSource(s);At(t,this.output),this._mediaStream=t}return this}))}close(){return this._stream&&this._mediaStream&&(this._stream.getAudioTracks().forEach(t=>{t.stop()}),this._stream=void 0,this._mediaStream.disconnect(),this._mediaStream=void 0),this._device=void 0,this}static enumerateDevices(){return S(this,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(t=>"audioinput"===t.kind)}))}get state(){return this._stream&&this._stream.active?"started":"stopped"}get deviceId(){return this._device?this._device.deviceId:void 0}get groupId(){return this._device?this._device.groupId:void 0}get label(){return this._device?this._device.label:void 0}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this.close(),this._volume.dispose(),this.volume.dispose(),this}static get supported(){return f(navigator.mediaDevices)&&f(navigator.mediaDevices.getUserMedia)}}function ce(t,e){return S(this,void 0,void 0,(function*(){const n=e/t.context.sampleRate,s=new et(1,n,t.context.sampleRate);return new t.constructor(Object.assign(t.get(),{frequency:2/n,detune:0,context:s})).toDestination().start(0),(yield s.render()).getChannelData(0)}))}class ue extends jt{constructor(){super(q(ue.getDefaults(),arguments,["frequency","type"])),this.name="ToneOscillatorNode",this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator];const t=q(ue.getDefaults(),arguments,["frequency","type"]);At(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new St({context:this.context,param:this._oscillator.frequency,units:"frequency",value:t.frequency}),this.detune=new St({context:this.context,param:this._oscillator.detune,units:"cents",value:t.detune}),$(this,["frequency","detune"])}static getDefaults(){return Object.assign(jt.getDefaults(),{detune:0,frequency:440,type:"sine"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._oscillator.start(e),this}_stopSource(t){this._oscillator.stop(t)}setPeriodicWave(t){return this._oscillator.setPeriodicWave(t),this}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}}class he extends ne{constructor(){super(q(he.getDefaults(),arguments,["frequency","type"])),this.name="Oscillator",this._oscillator=null;const t=q(he.getDefaults(),arguments,["frequency","type"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),$(this,"frequency"),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),$(this,"detune"),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&"custom"!==t.type&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:"sine"})}_start(t){const e=this.toSeconds(t),n=new ue({context:this.context,onended:()=>this.onstop(this)});this._oscillator=n,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(e)}_stop(t){const e=this.toSeconds(t);this._oscillator&&this._oscillator.stop(e)}_restart(t){const e=this.toSeconds(t);return this.log("restart",e),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(e),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if("custom"===this._type){return he._periodicWaveCache.find(t=>{return t.phase===this._phase&&(e=t.partials,n=this._partials,e.length===n.length&&e.every((t,e)=>n[e]===t));var e,n})}{const t=he._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}}get type(){return this._type}set type(t){this._type=t;const e=-1!==["sine","square","sawtooth","triangle"].indexOf(t);if(0===this._phase&&e)this._wave=void 0,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{const e=this._getCachedPeriodicWave();if(f(e)){const{partials:t,wave:n}=e;this._wave=n,this._partials=t,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}else{const[e,n]=this._getRealImaginary(t,this._phase),s=this.context.createPeriodicWave(e,n);this._wave=s,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave),he._periodicWaveCache.push({imag:n,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:e,type:this._type,wave:this._wave}),he._periodicWaveCache.length>100&&he._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(t){this.partialCount&&"custom"!==this._type&&"custom"!==t?this.type=t+this.partialCount:this.type=t}get partialCount(){return this._partialCount}set partialCount(t){a(t,0);let e=this._type;const n=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(n&&(e=n[1]),"custom"!==this._type)this.type=0===t?e:e+t.toString();else{const e=new Float32Array(t);this._partials.forEach((t,n)=>e[n]=t),this._partials=Array.from(e),this.type=this._type}}_getRealImaginary(t,e){let n=2048;const s=new Float32Array(n),i=new Float32Array(n);let o=1;if("custom"===t){if(o=this._partials.length+1,this._partialCount=this._partials.length,n=o,0===this._partials.length)return[s,i]}else{const e=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(t);e?(o=parseInt(e[2],10)+1,this._partialCount=parseInt(e[2],10),t=e[1],o=Math.max(o,2),n=o):this._partialCount=0,this._partials=[]}for(let r=1;r>1&1?-1:1):0,this._partials[r-1]=a;break;case"custom":a=this._partials[r-1];break;default:throw new TypeError("Oscillator: invalid type: "+t)}0!==a?(s[r]=-a*Math.sin(e*r),i[r]=a*Math.cos(e*r)):(s[r]=0,i[r]=0)}return[s,i]}_inverseFFT(t,e,n){let s=0;const i=t.length;for(let o=0;oe.includes(t)),"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class pe extends le{constructor(){super(...arguments),this.name="AudioToGain",this._norm=new de({context:this.context,mapping:t=>(t+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class fe extends Rt{constructor(){super(Object.assign(q(fe.getDefaults(),arguments,["value"]))),this.name="Multiply",this.override=!1;const t=q(fe.getDefaults(),arguments,["value"]);this._mult=this.input=this.output=new Mt({context:this.context,minValue:t.minValue,maxValue:t.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class _e extends ne{constructor(){super(q(_e.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="AMOscillator",this._modulationScale=new pe({context:this.context}),this._modulationNode=new Mt({context:this.context});const t=q(_e.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new he({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),$(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(he.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){this._modulator.restart(t),this._carrier.restart(t)}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class me extends ne{constructor(){super(q(me.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="FMOscillator",this._modulationNode=new Mt({context:this.context,gain:0});const t=q(me.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new he({context:this.context,detune:t.detune,frequency:0,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.detune=this._carrier.detune,this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this._modulator=new he({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this.modulationIndex=new fe({context:this.context,units:"positive",value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),$(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(he.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){return this._modulator.restart(t),this._carrier.restart(t),this}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class ge extends ne{constructor(){super(q(ge.getDefaults(),arguments,["frequency","width"])),this.name="PulseOscillator",this._widthGate=new Mt({context:this.context,gain:0}),this._thresh=new de({context:this.context,mapping:t=>t<=0?-1:1});const t=q(ge.getDefaults(),arguments,["frequency","width"]);this.width=new Rt({context:this.context,units:"audioRange",value:t.width}),this._triangle=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),$(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(t){t=this.toSeconds(t),this._triangle.start(t),this._widthGate.gain.setValueAtTime(1,t)}_stop(t){t=this.toSeconds(t),this._triangle.stop(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(0,t)}_restart(t){this._triangle.restart(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(1,t)}get phase(){return this._triangle.phase}set phase(t){this._triangle.phase=t}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(t){this._triangle.type=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class ve extends ne{constructor(){super(q(ve.getDefaults(),arguments,["frequency","type","spread"])),this.name="FatOscillator",this._oscillators=[];const t=q(ve.getDefaults(),arguments,["frequency","type","spread"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,$(this,["frequency","detune"])}static getDefaults(){return Object.assign(he.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(t){t=this.toSeconds(t),this._forEach(e=>e.start(t))}_stop(t){t=this.toSeconds(t),this._forEach(e=>e.stop(t))}_restart(t){this._forEach(e=>e.restart(t))}_forEach(t){for(let e=0;ee.type=t)}get spread(){return this._spread}set spread(t){if(this._spread=t,this._oscillators.length>1){const e=-t/2,n=t/(this._oscillators.length-1);this._forEach((t,s)=>t.detune.value=e+n*s)}}get count(){return this._oscillators.length}set count(t){if(a(t,1),this._oscillators.length!==t){this._forEach(t=>t.dispose()),this._oscillators=[];for(let e=0;ethis.onstop(this):K});"custom"===this.type&&(n.partials=this._partials),this.frequency.connect(n.frequency),this.detune.connect(n.detune),n.detune.overridden=!1,n.connect(this.output),this._oscillators[e]=n}this.spread=this._spread,"started"===this.state&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(t){this._phase=t,this._forEach(e=>e.phase=t)}get baseType(){return this._oscillators[0].baseType}set baseType(t){this._forEach(e=>e.baseType=t),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(t){this._partials=t,this._partialCount=this._partials.length,t.length&&(this._type="custom",this._forEach(e=>e.partials=t))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(t){this._partialCount=t,this._forEach(e=>e.partialCount=t),this._type=this._oscillators[0].type}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(t=>t.dispose()),this}}class ye extends ne{constructor(){super(q(ye.getDefaults(),arguments,["frequency","modulationFrequency"])),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new fe({context:this.context,value:2});const t=q(ye.getDefaults(),arguments,["frequency","modulationFrequency"]);this._pulse=new ge({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),$(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(t){t=this.toSeconds(t),this._modulator.start(t),this._pulse.start(t)}_stop(t){t=this.toSeconds(t),this._modulator.stop(t),this._pulse.stop(t)}_restart(t){this._modulator.restart(t),this._pulse.restart(t)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(t){this._modulator.phase=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const be={am:_e,fat:ve,fm:me,oscillator:he,pulse:ge,pwm:ye};class xe extends ne{constructor(){super(q(xe.getDefaults(),arguments,["frequency","type"])),this.name="OmniOscillator";const t=q(xe.getDefaults(),arguments,["frequency","type"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),$(this,["frequency","detune"]),this.set(t)}static getDefaults(){return Object.assign(he.getDefaults(),me.getDefaults(),_e.getDefaults(),ve.getDefaults(),ge.getDefaults(),ye.getDefaults())}_start(t){this._oscillator.start(t)}_stop(t){this._oscillator.stop(t)}_restart(t){return this._oscillator.restart(t),this}get type(){let t="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(t=this._sourceType),t+this._oscillator.type}set type(t){"fm"===t.substr(0,2)?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"am"===t.substr(0,2)?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"fat"===t.substr(0,3)?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(3)):"pwm"===t?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):"pulse"===t?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=t)}get partials(){return this._oscillator.partials}set partials(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partials=t)}get partialCount(){return this._oscillator.partialCount}set partialCount(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partialCount=t)}set(t){return Reflect.has(t,"type")&&t.type&&(this.type=t.type),super.set(t),this}_createNewOscillator(t){if(t!==this._sourceType){this._sourceType=t;const e=be[t],n=this.now();if(this._oscillator){const t=this._oscillator;t.stop(n),this.context.setTimeout(()=>t.dispose(),this.blockTime)}this._oscillator=new e({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),"started"===this.state&&this._oscillator.start(n)}}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t}get sourceType(){return this._sourceType}set sourceType(t){let e="sine";"pwm"!==this._oscillator.type&&"pulse"!==this._oscillator.type&&(e=this._oscillator.type),"fm"===t?this.type="fm"+e:"am"===t?this.type="am"+e:"fat"===t?this.type="fat"+e:"oscillator"===t?this.type=e:"pulse"===t?this.type="pulse":"pwm"===t&&(this.type="pwm")}_getOscType(t,e){return t instanceof be[e]}get baseType(){return this._oscillator.baseType}set baseType(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||"pulse"===t||"pwm"===t||(this._oscillator.baseType=t)}get width(){return this._getOscType(this._oscillator,"pulse")?this._oscillator.width:void 0}get count(){return this._getOscType(this._oscillator,"fat")?this._oscillator.count:void 0}set count(t){this._getOscType(this._oscillator,"fat")&&m(t)&&(this._oscillator.count=t)}get spread(){return this._getOscType(this._oscillator,"fat")?this._oscillator.spread:void 0}set spread(t){this._getOscType(this._oscillator,"fat")&&m(t)&&(this._oscillator.spread=t)}get modulationType(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.modulationType:void 0}set modulationType(t){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&b(t)&&(this._oscillator.modulationType=t)}get modulationIndex(){return this._getOscType(this._oscillator,"fm")?this._oscillator.modulationIndex:void 0}get harmonicity(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.harmonicity:void 0}get modulationFrequency(){return this._getOscType(this._oscillator,"pwm")?this._oscillator.modulationFrequency:void 0}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class we extends Rt{constructor(){super(Object.assign(q(we.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Add",this._sum=new Mt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,kt(this._constantSource,this._sum)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class Te extends le{constructor(){super(Object.assign(q(Te.getDefaults(),arguments,["min","max"]))),this.name="Scale";const t=q(Te.getDefaults(),arguments,["min","max"]);this._mult=this.input=new fe({context:this.context,value:t.max-t.min}),this._add=this.output=new we({context:this.context,value:t.min}),this._min=t.min,this._max=t.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(le.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(t){this._min=t,this._setRange()}get max(){return this._max}set max(t){this._max=t,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class Oe extends le{constructor(){super(Object.assign(q(Oe.getDefaults(),arguments))),this.name="Zero",this._gain=new Mt({context:this.context}),this.output=this._gain,this.input=void 0,At(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),Dt(this.context.getConstant(0),this._gain),this}}class Se extends Ct{constructor(){super(q(Se.getDefaults(),arguments,["frequency","min","max"])),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=St.prototype._fromType,this._toType=St.prototype._toType,this._is=St.prototype._is,this._clampValue=St.prototype._clampValue;const t=q(Se.getDefaults(),arguments,["frequency","min","max"]);this._oscillator=new he({context:this.context,frequency:t.frequency,type:t.type}),this.frequency=this._oscillator.frequency,this._amplitudeGain=new Mt({context:this.context,gain:t.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new Rt({context:this.context,units:"audioRange",value:0}),this._zeros=new Oe({context:this.context}),this._a2g=new pe({context:this.context}),this._scaler=this.output=new Te({context:this.context,max:t.max,min:t.min}),this.units=t.units,this.min=t.min,this.max=t.max,this._oscillator.chain(this._a2g,this._amplitudeGain,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),$(this,["amplitude","frequency"]),this.phase=t.phase}static getDefaults(){return Object.assign(Ct.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,phase:0,type:"sine",units:"number"})}start(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(0,t),this._oscillator.start(t),this}stop(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(this._stoppedValue,t),this._oscillator.stop(t),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}get min(){return this._toType(this._scaler.min)}set min(t){t=this._fromType(t),this._scaler.min=t}get max(){return this._toType(this._scaler.max)}set max(t){t=this._fromType(t),this._scaler.max=t}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t,this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t,this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get units(){return this._units}set units(t){const e=this.min,n=this.max;this._units=t,this.min=e,this.max=n}get state(){return this._oscillator.state}connect(t,e,n){return(t instanceof St||t instanceof Rt)&&(this.convert=t.convert,this.units=t.units),qt(this,t,e,n),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function Ce(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){a(s,t,e),n.set(this,s)}})}}function ke(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){a(this.toSeconds(s),t,e),n.set(this,s)}})}}class Ae extends ne{constructor(){super(q(Ae.getDefaults(),arguments,["url","onload"])),this.name="Player",this._activeSources=new Set;const t=q(Ae.getDefaults(),arguments,["url","onload"]);this._buffer=new tt({onload:this._onload.bind(this,t.onload),onerror:t.onerror,reverse:t.reverse,url:t.url}),this.autostart=t.autostart,this._loop=t.loop,this._loopStart=t.loopStart,this._loopEnd=t.loopEnd,this._playbackRate=t.playbackRate,this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:K,onerror:K,playbackRate:1,reverse:!1})}load(t){return S(this,void 0,void 0,(function*(){return yield this._buffer.load(t),this._onload(),this}))}_onload(t=K){t(),this.autostart&&this.start()}_onSourceEnd(t){this.onstop(this),this._activeSources.delete(t),0!==this._activeSources.size||this._synced||"started"!==this._state.getValueAtTime(this.now())||this._state.setStateAtTime("stopped",this.now())}start(t,e,n){return super.start(t,e,n),this}_start(t,e,n){e=this._loop?I(e,this._loopStart):I(e,0);let s=this.toSeconds(e);this._synced&&(s*=this._playbackRate);const i=n;n=I(n,Math.max(this._buffer.duration-s,0));let o=this.toSeconds(n);o/=this._playbackRate,t=this.toSeconds(t);const r=new se({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);this._loop||this._synced||(this._state.cancel(t+o),this._state.setStateAtTime("stopped",t+o,{implicitEnd:!0})),this._activeSources.add(r),this._loop&&p(i)?r.start(t,s):r.start(t,s,o-this.toSeconds(this.fadeOut))}_stop(t){const e=this.toSeconds(t);this._activeSources.forEach(t=>t.stop(e))}restart(t,e,n){return super.restart(t,e,n),this}_restart(t,e,n){this._stop(t),this._start(t,e,n)}seek(t,e){const n=this.toSeconds(e);if("started"===this._state.getValueAtTime(n)){const e=this.toSeconds(t);this._stop(n),this._start(n,e)}return this}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopStart=t})}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopEnd=t})}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._loop}set loop(t){if(this._loop!==t&&(this._loop=t,this._activeSources.forEach(e=>{e.loop=t}),t)){const t=this._state.getNextState("stopped",this.now());t&&this._state.cancel(t.time)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t;const e=this.now(),n=this._state.getNextState("stopped",e);n&&n.implicitEnd&&(this._state.cancel(n.time),this._activeSources.forEach(t=>t.cancelStop())),this._activeSources.forEach(n=>{n.playbackRate.setValueAtTime(t,e)})}get reverse(){return this._buffer.reverse}set reverse(t){this._buffer.reverse=t}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(t=>t.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}O([ke(0)],Ae.prototype,"fadeIn",void 0),O([ke(0)],Ae.prototype,"fadeOut",void 0);class De extends Ct{constructor(){super(q(De.getDefaults(),arguments,["urls","onload"],"urls")),this.name="Players",this.input=void 0,this._players=new Map;const t=q(De.getDefaults(),arguments,["urls","onload"],"urls");this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this._buffers=new $t({urls:t.urls,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.mute=t.mute,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{baseUrl:"",fadeIn:0,fadeOut:0,mute:!1,onload:K,onerror:K,urls:{},volume:0})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._players.forEach(e=>{e.fadeIn=t})}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._players.forEach(e=>{e.fadeOut=t})}get state(){return Array.from(this._players).some(([t,e])=>"started"===e.state)?"started":"stopped"}has(t){return this._buffers.has(t)}player(t){if(r(this.has(t),`No Player with the name ${t} exists on this object`),!this._players.has(t)){const e=new Ae({context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,url:this._buffers.get(t)}).connect(this.output);this._players.set(t,e)}return this._players.get(t)}get loaded(){return this._buffers.loaded}add(t,e,n){return r(!this._buffers.has(t),"A buffer with that name already exists on this object"),this._buffers.add(t,e,n),this}stopAll(t){return this._players.forEach(e=>e.stop(t)),this}dispose(){return super.dispose(),this._volume.dispose(),this.volume.dispose(),this._players.forEach(t=>t.dispose()),this._buffers.dispose(),this}}class Me extends ne{constructor(){super(q(Me.getDefaults(),arguments,["url","onload"])),this.name="GrainPlayer",this._loopStart=0,this._loopEnd=0,this._activeSources=[];const t=q(Me.getDefaults(),arguments,["url","onload"]);this.buffer=new tt({onload:t.onload,onerror:t.onerror,reverse:t.reverse,url:t.url}),this._clock=new Nt({context:this.context,callback:this._tick.bind(this),frequency:1/t.grainSize}),this._playbackRate=t.playbackRate,this._grainSize=t.grainSize,this._overlap=t.overlap,this.detune=t.detune,this.overlap=t.overlap,this.loop=t.loop,this.playbackRate=t.playbackRate,this.grainSize=t.grainSize,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.reverse=t.reverse,this._clock.on("stop",this._onstop.bind(this))}static getDefaults(){return Object.assign(ne.getDefaults(),{onload:K,onerror:K,overlap:.1,grainSize:.2,playbackRate:1,detune:0,loop:!1,loopStart:0,loopEnd:0,reverse:!1})}_start(t,e,n){e=I(e,0),e=this.toSeconds(e),t=this.toSeconds(t);const s=1/this._clock.frequency.getValueAtTime(t);this._clock.start(t,e/s),n&&this.stop(t+this.toSeconds(n))}restart(t,e,n){return super.restart(t,e,n),this}_restart(t,e,n){this._stop(t),this._start(t,e,n)}_stop(t){this._clock.stop(t)}_onstop(t){this._activeSources.forEach(e=>{e.fadeOut=0,e.stop(t)}),this.onstop(this)}_tick(t){const e=this._clock.getTicksAtTime(t),n=e*this._grainSize;if(this.log("offset",n),!this.loop&&n>this.buffer.duration)return void this.stop(t);const s=n{const t=this._activeSources.indexOf(i);-1!==t&&this._activeSources.splice(t,1)}}get playbackRate(){return this._playbackRate}set playbackRate(t){a(t,.001),this._playbackRate=t,this.grainSize=this._grainSize}get loopStart(){return this._loopStart}set loopStart(t){this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._loopStart=this.toSeconds(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._loopEnd=this.toSeconds(t)}get reverse(){return this.buffer.reverse}set reverse(t){this.buffer.reverse=t}get grainSize(){return this._grainSize}set grainSize(t){this._grainSize=this.toSeconds(t),this._clock.frequency.setValueAtTime(this._playbackRate/this._grainSize,this.now())}get overlap(){return this._overlap}set overlap(t){const e=this.toSeconds(t);a(e,0),this._overlap=e}get loaded(){return this.buffer.loaded}dispose(){return super.dispose(),this.buffer.dispose(),this._clock.dispose(),this._activeSources.forEach(t=>t.dispose()),this}}class je extends le{constructor(){super(...arguments),this.name="Abs",this._abs=new de({context:this.context,mapping:t=>Math.abs(t)<.001?0:Math.abs(t)}),this.input=this._abs,this.output=this._abs}dispose(){return super.dispose(),this._abs.dispose(),this}}class Ee extends le{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new de({context:this.context,mapping:t=>2*Math.abs(t)-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Re extends le{constructor(){super(...arguments),this.name="Negate",this._multiply=new fe({context:this.context,value:-1}),this.input=this._multiply,this.output=this._multiply}dispose(){return super.dispose(),this._multiply.dispose(),this}}class qe extends Rt{constructor(){super(Object.assign(q(qe.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Subtract",this._sum=new Mt({context:this.context}),this.input=this._sum,this.output=this._sum,this._neg=new Re({context:this.context}),this.subtrahend=this._param,kt(this._constantSource,this._neg,this._sum)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._neg.dispose(),this._sum.dispose(),this}}class Ie extends le{constructor(){super(Object.assign(q(Ie.getDefaults(),arguments))),this.name="GreaterThanZero",this._thresh=this.output=new de({context:this.context,length:127,mapping:t=>t<=0?0:1}),this._scale=this.input=new fe({context:this.context,value:1e4}),this._scale.connect(this._thresh)}dispose(){return super.dispose(),this._scale.dispose(),this._thresh.dispose(),this}}class Fe extends Rt{constructor(){super(Object.assign(q(Fe.getDefaults(),arguments,["value"]))),this.name="GreaterThan",this.override=!1;const t=q(Fe.getDefaults(),arguments,["value"]);this._subtract=this.input=new qe({context:this.context,value:t.value}),this._gtz=this.output=new Ie({context:this.context}),this.comparator=this._param=this._subtract.subtrahend,$(this,"comparator"),this._subtract.connect(this._gtz)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._gtz.dispose(),this._subtract.dispose(),this.comparator.dispose(),this}}class Ve extends le{constructor(){super(Object.assign(q(Ve.getDefaults(),arguments,["value"]))),this.name="Pow";const t=q(Ve.getDefaults(),arguments,["value"]);this._exponentScaler=this.input=this.output=new de({context:this.context,mapping:this._expFunc(t.value),length:8192}),this._exponent=t.value}static getDefaults(){return Object.assign(le.getDefaults(),{value:1})}_expFunc(t){return e=>Math.pow(Math.abs(e),t)}get value(){return this._exponent}set value(t){this._exponent=t,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Ne extends Te{constructor(){super(Object.assign(q(Ne.getDefaults(),arguments,["min","max","exponent"]))),this.name="ScaleExp";const t=q(Ne.getDefaults(),arguments,["min","max","exponent"]);this.input=this._exp=new Ve({context:this.context,value:t.exponent}),this._exp.connect(this._mult)}static getDefaults(){return Object.assign(Te.getDefaults(),{exponent:1})}get exponent(){return this._exp.value}set exponent(t){this._exp.value=t}dispose(){return super.dispose(),this._exp.dispose(),this}}class Pe extends Rt{constructor(){super(q(Rt.getDefaults(),arguments,["value","units"])),this.name="SyncedSignal",this.override=!1;const t=q(Rt.getDefaults(),arguments,["value","units"]);this._lastVal=t.value,this._synced=this.context.transport.scheduleRepeat(this._onTick.bind(this),"1i"),this._syncedCallback=this._anchorValue.bind(this),this.context.transport.on("start",this._syncedCallback),this.context.transport.on("pause",this._syncedCallback),this.context.transport.on("stop",this._syncedCallback),this._constantSource.disconnect(),this._constantSource.stop(0),this._constantSource=this.output=new Et({context:this.context,offset:t.value,units:t.units}).start(0),this.setValueAtTime(t.value,0)}_onTick(t){const e=super.getValueAtTime(this.context.transport.seconds);this._lastVal!==e&&(this._lastVal=e,this._constantSource.offset.setValueAtTime(e,t))}_anchorValue(t){const e=super.getValueAtTime(this.context.transport.seconds);this._lastVal=e,this._constantSource.offset.cancelAndHoldAtTime(t),this._constantSource.offset.setValueAtTime(e,t)}getValueAtTime(t){const e=new xt(this.context,t).toSeconds();return super.getValueAtTime(e)}setValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.setValueAtTime(t,n),this}linearRampToValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.linearRampToValueAtTime(t,n),this}exponentialRampToValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.exponentialRampToValueAtTime(t,n),this}setTargetAtTime(t,e,n){const s=new xt(this.context,e).toSeconds();return super.setTargetAtTime(t,s,n),this}cancelScheduledValues(t){const e=new xt(this.context,t).toSeconds();return super.cancelScheduledValues(e),this}setValueCurveAtTime(t,e,n,s){const i=new xt(this.context,e).toSeconds();return n=this.toSeconds(n),super.setValueCurveAtTime(t,i,n,s),this}cancelAndHoldAtTime(t){const e=new xt(this.context,t).toSeconds();return super.cancelAndHoldAtTime(e),this}setRampPoint(t){const e=new xt(this.context,t).toSeconds();return super.setRampPoint(e),this}exponentialRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.exponentialRampTo(t,e,s),this}linearRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.linearRampTo(t,e,s),this}targetRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.targetRampTo(t,e,s),this}dispose(){return super.dispose(),this.context.transport.clear(this._synced),this.context.transport.off("start",this._syncedCallback),this.context.transport.off("pause",this._syncedCallback),this.context.transport.off("stop",this._syncedCallback),this._constantSource.dispose(),this}}class Le extends Ct{constructor(){super(q(Le.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="Envelope",this._sig=new Rt({context:this.context,value:0}),this.output=this._sig,this.input=void 0;const t=q(Le.getDefaults(),arguments,["attack","decay","sustain","release"]);this.attack=t.attack,this.decay=t.decay,this.sustain=t.sustain,this.release=t.release,this.attackCurve=t.attackCurve,this.releaseCurve=t.releaseCurve,this.decayCurve=t.decayCurve}static getDefaults(){return Object.assign(Ct.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(t,e){if(b(t))return t;{let n;for(n in ze)if(ze[n][e]===t)return n;return t}}_setCurve(t,e,n){if(b(n)&&Reflect.has(ze,n)){const s=ze[n];g(s)?"_decayCurve"!==t&&(this[t]=s[e]):this[t]=s}else{if(!y(n)||"_decayCurve"===t)throw new Error("Envelope: invalid curve: "+n);this[t]=n}}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(t){this._setCurve("_attackCurve","In",t)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(t){this._setCurve("_releaseCurve","Out",t)}get decayCurve(){return this._decayCurve}set decayCurve(t){r(["linear","exponential"].some(e=>e===t),"Invalid envelope curve: "+t),this._decayCurve=t}triggerAttack(t,e=1){this.log("triggerAttack",t,e),t=this.toSeconds(t);let n=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),i=this.getValueAtTime(t);if(i>0){n=(1-i)/(1/n)}if(n0){const n=this.toSeconds(this.release);n{let t,e;const n=[];for(t=0;t<128;t++)n[t]=Math.sin(t/127*(Math.PI/2));const s=[];for(t=0;t<127;t++){e=t/127;const n=Math.sin(e*(2*Math.PI)*6.4-Math.PI/2)+1;s[t]=n/10+.83*e}s[127]=1;const i=[];for(t=0;t<128;t++)i[t]=Math.ceil(t/127*5)/5;const o=[];for(t=0;t<128;t++)e=t/127,o[t]=.5*(1-Math.cos(Math.PI*e));const r=[];for(t=0;t<128;t++){e=t/127;const n=4*Math.pow(e,3)+.2,s=Math.cos(n*Math.PI*2*e);r[t]=Math.abs(s*(1-e))}function a(t){const e=new Array(t.length);for(let n=0;n{const s=t[e],i=this.context.transport.schedule(s=>{t[e]=s,n.apply(this,t)},s);this._scheduledEvents.push(i)}}unsync(){return this._scheduledEvents.forEach(t=>this.context.transport.clear(t)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease),this}triggerAttackRelease(t,e,n,s){const i=this.toSeconds(n),o=this.toSeconds(e);return this.triggerAttack(t,i,s),this.triggerRelease(i+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class We extends Be{constructor(){super(q(We.getDefaults(),arguments));const t=q(We.getDefaults(),arguments);this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(Be.getDefaults(),{detune:0,onsilence:K,portamento:0})}triggerAttack(t,e,n=1){this.log("triggerAttack",t,e,n);const s=this.toSeconds(e);return this._triggerEnvelopeAttack(s,n),this.setNote(t,s),this}triggerRelease(t){this.log("triggerRelease",t);const e=this.toSeconds(t);return this._triggerEnvelopeRelease(e),this}setNote(t,e){const n=this.toSeconds(e),s=t instanceof gt?t.toFrequency():t;if(this.portamento>0&&this.getLevelAtTime(n)>.05){const t=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(s,t,n)}else this.frequency.setValueAtTime(s,n);return this}}O([ke(0)],We.prototype,"portamento",void 0);class Ue extends Le{constructor(){super(q(Ue.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new Mt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Ge extends We{constructor(){super(q(Ge.getDefaults(),arguments)),this.name="Synth";const t=q(Ge.getDefaults(),arguments);this.oscillator=new xe(Object.assign({context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new Ue(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),$(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(t,e){if(this.envelope.triggerAttack(t,e),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+n)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class Ye extends We{constructor(){super(q(Ye.getDefaults(),arguments)),this.name="ModulationSynth";const t=q(Ye.getDefaults(),arguments);this._carrier=new Ge({context:this.context,oscillator:t.oscillator,envelope:t.envelope,onsilence:()=>this.onsilence(this),volume:-10}),this._modulator=new Ge({context:this.context,oscillator:t.modulation,envelope:t.modulationEnvelope,volume:-10}),this.oscillator=this._carrier.oscillator,this.envelope=this._carrier.envelope,this.modulation=this._modulator.oscillator,this.modulationEnvelope=this._modulator.envelope,this.frequency=new Rt({context:this.context,units:"frequency"}),this.detune=new Rt({context:this.context,value:t.detune,units:"cents"}),this.harmonicity=new fe({context:this.context,value:t.harmonicity,minValue:0}),this._modulationNode=new Mt({context:this.context,gain:0}),$(this,["frequency","harmonicity","oscillator","envelope","modulation","modulationEnvelope","detune"])}static getDefaults(){return Object.assign(We.getDefaults(),{harmonicity:3,oscillator:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"sine"}),envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.01,decay:.01,sustain:1,release:.5}),modulation:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"square"}),modulationEnvelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.5,decay:0,sustain:1,release:.5})})}_triggerEnvelopeAttack(t,e){this._carrier._triggerEnvelopeAttack(t,e),this._modulator._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this._carrier._triggerEnvelopeRelease(t),this._modulator._triggerEnvelopeRelease(t),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this._carrier.dispose(),this._modulator.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._modulationNode.dispose(),this}}class Qe extends Ye{constructor(){super(q(Qe.getDefaults(),arguments)),this.name="AMSynth",this._modulationScale=new pe({context:this.context}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output)}dispose(){return super.dispose(),this._modulationScale.dispose(),this}}class Ze extends Ct{constructor(){super(q(Ze.getDefaults(),arguments,["frequency","type"])),this.name="BiquadFilter";const t=q(Ze.getDefaults(),arguments,["frequency","type"]);this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new St({context:this.context,units:"number",value:t.Q,param:this._filter.Q}),this.frequency=new St({context:this.context,units:"frequency",value:t.frequency,param:this._filter.frequency}),this.detune=new St({context:this.context,units:"cents",value:t.detune,param:this._filter.detune}),this.gain=new St({context:this.context,units:"gain",value:t.gain,param:this._filter.gain}),this.type=t.type}static getDefaults(){return Object.assign(Ct.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(t){r(-1!==["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(t),"Invalid filter type: "+t),this._filter.type=t}getFrequencyResponse(t=128){const e=new Float32Array(t);for(let n=0;ne.type=t)}get rolloff(){return this._rolloff}set rolloff(t){const e=m(t)?t:parseInt(t,10),n=[-12,-24,-48,-96];let s=n.indexOf(e);r(-1!==s,"rolloff can only be "+n.join(", ")),s+=1,this._rolloff=e,this.input.disconnect(),this._filters.forEach(t=>t.disconnect()),this._filters=new Array(s);for(let t=0;t1);return this._filters.forEach(()=>{e.getFrequencyResponse(t).forEach((t,e)=>n[e]*=t)}),e.dispose(),n}dispose(){return super.dispose(),this._filters.forEach(t=>{t.dispose()}),J(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class He extends Le{constructor(){super(q(He.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="FrequencyEnvelope";const t=q(He.getDefaults(),arguments,["attack","decay","sustain","release"]);this._octaves=t.octaves,this._baseFrequency=this.toFrequency(t.baseFrequency),this._exponent=this.input=new Ve({context:this.context,value:t.exponent}),this._scale=this.output=new Te({context:this.context,min:this._baseFrequency,max:this._baseFrequency*Math.pow(2,this._octaves)}),this._sig.chain(this._exponent,this._scale)}static getDefaults(){return Object.assign(Le.getDefaults(),{baseFrequency:200,exponent:1,octaves:4})}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){const e=this.toFrequency(t);a(e,0),this._baseFrequency=e,this._scale.min=this._baseFrequency,this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){a(t,0),this._octaves=t,this._scale.max=this._baseFrequency*Math.pow(2,t)}get exponent(){return this._exponent.value}set exponent(t){this._exponent.value=t}dispose(){return super.dispose(),this._exponent.dispose(),this._scale.dispose(),this}}class $e extends We{constructor(){super(q($e.getDefaults(),arguments)),this.name="MonoSynth";const t=q($e.getDefaults(),arguments);this.oscillator=new xe(Object.assign(t.oscillator,{context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)})),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.filter=new Xe(Object.assign(t.filter,{context:this.context})),this.filterEnvelope=new He(Object.assign(t.filterEnvelope,{context:this.context})),this.envelope=new Ue(Object.assign(t.envelope,{context:this.context})),this.oscillator.chain(this.filter,this.envelope,this.output),this.filterEnvelope.connect(this.filter.frequency),$(this,["oscillator","frequency","detune","filter","filterEnvelope","envelope"])}static getDefaults(){return Object.assign(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.9}),filter:Object.assign(F(Xe.getDefaults(),Object.keys(Ct.getDefaults())),{Q:1,rolloff:-12,type:"lowpass"}),filterEnvelope:Object.assign(F(He.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.6,baseFrequency:200,decay:.2,exponent:2,octaves:3,release:2,sustain:.5}),oscillator:Object.assign(F(xe.getDefaults(),Object.keys(ne.getDefaults())),{type:"sawtooth"})})}_triggerEnvelopeAttack(t,e=1){if(this.envelope.triggerAttack(t,e),this.filterEnvelope.triggerAttack(t),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+n)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.filterEnvelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this.filterEnvelope.dispose(),this.filter.dispose(),this}}class Je extends We{constructor(){super(q(Je.getDefaults(),arguments)),this.name="DuoSynth";const t=q(Je.getDefaults(),arguments);this.voice0=new $e(Object.assign(t.voice0,{context:this.context,onsilence:()=>this.onsilence(this)})),this.voice1=new $e(Object.assign(t.voice1,{context:this.context})),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this._vibrato=new Se({frequency:t.vibratoRate,context:this.context,min:-50,max:50}),this._vibrato.start(),this.vibratoRate=this._vibrato.frequency,this._vibratoGain=new Mt({context:this.context,units:"normalRange",gain:t.vibratoAmount}),this.vibratoAmount=this._vibratoGain.gain,this.frequency=new Rt({context:this.context,units:"frequency",value:440}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this.frequency.connect(this.voice0.frequency),this.frequency.chain(this.harmonicity,this.voice1.frequency),this._vibrato.connect(this._vibratoGain),this._vibratoGain.fan(this.voice0.detune,this.voice1.detune),this.detune.fan(this.voice0.detune,this.voice1.detune),this.voice0.connect(this.output),this.voice1.connect(this.output),$(this,["voice0","voice1","frequency","vibratoAmount","vibratoRate"])}getLevelAtTime(t){return t=this.toSeconds(t),this.voice0.envelope.getValueAtTime(t)+this.voice1.envelope.getValueAtTime(t)}static getDefaults(){return R(We.getDefaults(),{vibratoAmount:.5,vibratoRate:5,harmonicity:1.5,voice0:R(F($e.getDefaults(),Object.keys(We.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}}),voice1:R(F($e.getDefaults(),Object.keys(We.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}})})}_triggerEnvelopeAttack(t,e){this.voice0._triggerEnvelopeAttack(t,e),this.voice1._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this.voice0._triggerEnvelopeRelease(t),this.voice1._triggerEnvelopeRelease(t),this}dispose(){return super.dispose(),this.voice0.dispose(),this.voice1.dispose(),this.frequency.dispose(),this.detune.dispose(),this._vibrato.dispose(),this.vibratoRate.dispose(),this._vibratoGain.dispose(),this.harmonicity.dispose(),this}}class Ke extends Ye{constructor(){super(q(Ke.getDefaults(),arguments)),this.name="FMSynth";const t=q(Ke.getDefaults(),arguments);this.modulationIndex=new fe({context:this.context,value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output)}static getDefaults(){return Object.assign(Ye.getDefaults(),{modulationIndex:10})}dispose(){return super.dispose(),this.modulationIndex.dispose(),this}}const tn=[1,1.483,1.932,2.546,2.63,3.897];class en extends We{constructor(){super(q(en.getDefaults(),arguments)),this.name="MetalSynth",this._oscillators=[],this._freqMultipliers=[];const t=q(en.getDefaults(),arguments);this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this.frequency=new Rt({context:this.context,units:"frequency"}),this._amplitude=new Mt({context:this.context,gain:0}).connect(this.output),this._highpass=new Xe({Q:0,context:this.context,type:"highpass"}).connect(this._amplitude);for(let e=0;ethis.onsilence(this):K,type:"square"});n.connect(this._highpass),this._oscillators[e]=n;const s=new fe({context:this.context,value:tn[e]});this._freqMultipliers[e]=s,this.frequency.chain(s,n.frequency),this.detune.connect(n.detune)}this._filterFreqScaler=new Te({context:this.context,max:7e3,min:this.toFrequency(t.resonance)}),this.envelope=new Le({attack:t.envelope.attack,attackCurve:"linear",context:this.context,decay:t.envelope.decay,release:t.envelope.release,sustain:0}),this.envelope.chain(this._filterFreqScaler,this._highpass.frequency),this.envelope.connect(this._amplitude.gain),this._octaves=t.octaves,this.octaves=t.octaves}static getDefaults(){return R(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.001,decay:1.4,release:.2}),harmonicity:5.1,modulationIndex:32,octaves:1.5,resonance:4e3})}_triggerEnvelopeAttack(t,e=1){return this.envelope.triggerAttack(t,e),this._oscillators.forEach(e=>e.start(t)),0===this.envelope.sustain&&this._oscillators.forEach(e=>{e.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay))}),this}_triggerEnvelopeRelease(t){return this.envelope.triggerRelease(t),this._oscillators.forEach(e=>e.stop(t+this.toSeconds(this.envelope.release))),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}get modulationIndex(){return this._oscillators[0].modulationIndex.value}set modulationIndex(t){this._oscillators.forEach(e=>e.modulationIndex.value=t)}get harmonicity(){return this._oscillators[0].harmonicity.value}set harmonicity(t){this._oscillators.forEach(e=>e.harmonicity.value=t)}get resonance(){return this._filterFreqScaler.min}set resonance(t){this._filterFreqScaler.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._filterFreqScaler.max=this._filterFreqScaler.min*Math.pow(2,t)}dispose(){return super.dispose(),this._oscillators.forEach(t=>t.dispose()),this._freqMultipliers.forEach(t=>t.dispose()),this.frequency.dispose(),this.detune.dispose(),this._filterFreqScaler.dispose(),this._amplitude.dispose(),this.envelope.dispose(),this._highpass.dispose(),this}}class nn extends Ge{constructor(){super(q(nn.getDefaults(),arguments)),this.name="MembraneSynth",this.portamento=0;const t=q(nn.getDefaults(),arguments);this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,$(this,["oscillator","envelope"])}static getDefaults(){return R(We.getDefaults(),Ge.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(t,e){const n=this.toSeconds(e),s=this.toFrequency(t instanceof gt?t.toFrequency():t),i=s*this.octaves;return this.oscillator.frequency.setValueAtTime(i,n),this.oscillator.frequency.exponentialRampToValueAtTime(s,n+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}O([Ce(0)],nn.prototype,"octaves",void 0),O([ke(0)],nn.prototype,"pitchDecay",void 0);class sn extends Be{constructor(){super(q(sn.getDefaults(),arguments)),this.name="NoiseSynth";const t=q(sn.getDefaults(),arguments);this.noise=new ie(Object.assign({context:this.context},t.noise)),this.envelope=new Ue(Object.assign({context:this.context},t.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Be.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(F(ie.getDefaults(),Object.keys(ne.getDefaults())),{type:"white"})})}triggerAttack(t,e=1){return t=this.toSeconds(t),this.envelope.triggerAttack(t,e),this.noise.start(t),0===this.envelope.sustain&&this.noise.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(t){return t=this.toSeconds(t),this.envelope.triggerRelease(t),this.noise.stop(t+this.toSeconds(this.envelope.release)),this}sync(){return this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0),this}triggerAttackRelease(t,e,n=1){return e=this.toSeconds(e),t=this.toSeconds(t),this.triggerAttack(e,n),this.triggerRelease(e+t),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const on=new Set;function rn(t){on.add(t)}function an(t,e){const n=`registerProcessor("${t}", ${e})`;on.add(n)}class cn extends Ct{constructor(t){super(t),this.name="ToneAudioWorklet",this.workletOptions={},this.onprocessorerror=K;const e=URL.createObjectURL(new Blob([Array.from(on).join("\n")],{type:"text/javascript"})),n=this._audioWorkletName();this._dummyGain=this.context.createGain(),this._dummyParam=this._dummyGain.gain,this.context.addAudioWorkletModule(e,n).then(()=>{this.disposed||(this._worklet=this.context.createAudioWorkletNode(n,this.workletOptions),this._worklet.onprocessorerror=this.onprocessorerror.bind(this),this.onReady(this._worklet))})}dispose(){return super.dispose(),this._dummyGain.disconnect(),this._worklet&&(this._worklet.port.postMessage("dispose"),this._worklet.disconnect()),this}}rn('\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the [[ToneAudioWorklet]]. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it\'s disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t   \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === "dispose") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n');rn("\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n");rn("\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n");an("feedback-comb-filter",'\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: "delayTime",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}, {\n\t\t\t\tname: "feedback",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n');class un extends cn{constructor(){super(q(un.getDefaults(),arguments,["delayTime","resonance"])),this.name="FeedbackCombFilter";const t=q(un.getDefaults(),arguments,["delayTime","resonance"]);this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.delayTime=new St({context:this.context,value:t.delayTime,units:"time",minValue:0,maxValue:1,param:this._dummyParam,swappable:!0}),this.resonance=new St({context:this.context,value:t.resonance,units:"normalRange",param:this._dummyParam,swappable:!0}),$(this,["resonance","delayTime"])}_audioWorkletName(){return"feedback-comb-filter"}static getDefaults(){return Object.assign(Ct.getDefaults(),{delayTime:.1,resonance:.5})}onReady(t){kt(this.input,t,this.output);const e=t.parameters.get("delayTime");this.delayTime.setParam(e);const n=t.parameters.get("feedback");this.resonance.setParam(n)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.delayTime.dispose(),this.resonance.dispose(),this}}class hn extends Ct{constructor(){super(q(hn.getDefaults(),arguments,["frequency","type"])),this.name="OnePoleFilter";const t=q(hn.getDefaults(),arguments,["frequency","type"]);this._frequency=t.frequency,this._type=t.type,this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this._createFilter()}static getDefaults(){return Object.assign(Ct.getDefaults(),{frequency:880,type:"lowpass"})}_createFilter(){const t=this._filter,e=this.toFrequency(this._frequency),n=1/(2*Math.PI*e);if("lowpass"===this._type){const t=1/(n*this.context.sampleRate),e=t-1;this._filter=this.context.createIIRFilter([t,0],[1,e])}else{const t=1/(n*this.context.sampleRate)-1;this._filter=this.context.createIIRFilter([1,-1],[1,t])}this.input.chain(this._filter,this.output),t&&this.context.setTimeout(()=>{this.disposed||(this.input.disconnect(t),t.disconnect())},this.blockTime)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._createFilter()}get type(){return this._type}set type(t){this._type=t,this._createFilter()}getFrequencyResponse(t=128){const e=new Float32Array(t);for(let n=0;ne.voice===t);this._activeVoices.splice(e,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const t=this._availableVoices.shift(),e=this._voices.indexOf(t);this._voices.splice(e,1),this.context.isOffline||t.dispose()}}_triggerAttack(t,e,n){t.forEach(t=>{const s=new Jt(this.context,t).toMidi(),i=this._getNextAvailableVoice();i&&(i.triggerAttack(t,e,n),this._activeVoices.push({midi:s,voice:i,released:!1}),this.log("triggerAttack",t,e))})}_triggerRelease(t,e){t.forEach(t=>{const n=new Jt(this.context,t).toMidi(),s=this._activeVoices.find(({midi:t,released:e})=>t===n&&!e);s&&(s.voice.triggerRelease(e),s.released=!0,this.log("triggerRelease",t,e))})}_scheduleEvent(t,e,n,s){r(!this.disposed,"Synth was already disposed"),n<=this.now()?"attack"===t?this._triggerAttack(e,n,s):this._triggerRelease(e,n):this.context.setTimeout(()=>{this._scheduleEvent(t,e,n,s)},n-this.now())}triggerAttack(t,e,n){Array.isArray(t)||(t=[t]);const s=this.toSeconds(e);return this._scheduleEvent("attack",t,s,n),this}triggerRelease(t,e){Array.isArray(t)||(t=[t]);const n=this.toSeconds(e);return this._scheduleEvent("release",t,n),this}triggerAttackRelease(t,e,n,s){const i=this.toSeconds(n);if(this.triggerAttack(t,i,s),y(e)){r(y(t),"If the duration is an array, the notes must also be an array"),t=t;for(let n=0;n0,"The duration must be greater than 0"),this.triggerRelease(t[n],i+o)}}else{const n=this.toSeconds(e);r(n>0,"The duration must be greater than 0"),this.triggerRelease(t,i+n)}return this}sync(){return this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this}set(t){const e=F(t,["onsilence","context"]);return this.options=R(this.options,e),this._voices.forEach(t=>t.set(e)),this._dummyVoice.set(e),this}get(){return this._dummyVoice.get()}releaseAll(t){const e=this.toSeconds(t);return this._activeVoices.forEach(({voice:t})=>{t.triggerRelease(e)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(t=>t.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class fn extends Be{constructor(){super(q(fn.getDefaults(),arguments,["urls","onload","baseUrl"],"urls")),this.name="Sampler",this._activeSources=new Map;const t=q(fn.getDefaults(),arguments,["urls","onload","baseUrl"],"urls"),e={};Object.keys(t.urls).forEach(n=>{const s=parseInt(n,10);if(r(x(n)||m(s)&&isFinite(s),"url key is neither a note or midi pitch: "+n),x(n)){const s=new gt(this.context,n).toMidi();e[s]=t.urls[n]}else m(s)&&isFinite(s)&&(e[s]=t.urls[s])}),this._buffers=new $t({urls:e,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.attack=t.attack,this.release=t.release,this.curve=t.curve,this._buffers.loaded&&Promise.resolve().then(t.onload)}static getDefaults(){return Object.assign(Be.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:K,onerror:K,release:.1,urls:{}})}_findClosest(t){let e=0;for(;e<96;){if(this._buffers.has(t+e))return-e;if(this._buffers.has(t-e))return e;e++}throw new Error("No available buffers for note: "+t)}triggerAttack(t,e,n=1){return this.log("triggerAttack",t,e,n),Array.isArray(t)||(t=[t]),t.forEach(t=>{const s=dt(new gt(this.context,t).toFrequency()),i=Math.round(s),o=s-i,r=this._findClosest(i),a=i-r,c=this._buffers.get(a),u=ut(r+o),h=new se({url:c,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:u}).connect(this.output);h.start(e,0,c.duration/u,n),y(this._activeSources.get(i))||this._activeSources.set(i,[]),this._activeSources.get(i).push(h),h.onended=()=>{if(this._activeSources&&this._activeSources.has(i)){const t=this._activeSources.get(i),e=t.indexOf(h);-1!==e&&t.splice(e,1)}}}),this}triggerRelease(t,e){return this.log("triggerRelease",t,e),Array.isArray(t)||(t=[t]),t.forEach(t=>{const n=new gt(this.context,t).toMidi();if(this._activeSources.has(n)&&this._activeSources.get(n).length){const t=this._activeSources.get(n);e=this.toSeconds(e),t.forEach(t=>{t.stop(e)}),this._activeSources.set(n,[])}}),this}releaseAll(t){const e=this.toSeconds(t);return this._activeSources.forEach(t=>{for(;t.length;){t.shift().stop(e)}}),this}sync(){return this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this}triggerAttackRelease(t,e,n,s=1){const i=this.toSeconds(n);return this.triggerAttack(t,i,s),y(e)?(r(y(t),"notes must be an array when duration is array"),t.forEach((t,n)=>{const s=e[Math.min(n,e.length-1)];this.triggerRelease(t,i+this.toSeconds(s))})):this.triggerRelease(t,i+this.toSeconds(e)),this}add(t,e,n){if(r(x(t)||isFinite(t),"note must be a pitch or midi: "+t),x(t)){const s=new gt(this.context,t).toMidi();this._buffers.add(s,e,n)}else this._buffers.add(t,e,n);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(t=>{t.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}O([ke(0)],fn.prototype,"attack",void 0),O([ke(0)],fn.prototype,"release",void 0);class _n extends Tt{constructor(){super(q(_n.getDefaults(),arguments,["callback","value"])),this.name="ToneEvent",this._state=new Ot("stopped"),this._startOffset=0;const t=q(_n.getDefaults(),arguments,["callback","value"]);this._loop=t.loop,this.callback=t.callback,this.value=t.value,this._loopStart=this.toTicks(t.loopStart),this._loopEnd=this.toTicks(t.loopEnd),this._playbackRate=t.playbackRate,this._probability=t.probability,this._humanize=t.humanize,this.mute=t.mute,this._playbackRate=t.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(Tt.getDefaults(),{callback:K,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(t=-1){this._state.forEachFrom(t,t=>{let e;if("started"===t.state){-1!==t.id&&this.context.transport.clear(t.id);const n=t.time+Math.round(this.startOffset/this._playbackRate);if(!0===this._loop||m(this._loop)&&this._loop>1){e=1/0,m(this._loop)&&(e=this._loop*this._getLoopDuration());const s=this._state.getAfter(n);null!==s&&(e=Math.min(e,s.time-n)),e!==1/0&&(this._state.setStateAtTime("stopped",n+e+1,{id:-1}),e=new Lt(this.context,e));const i=new Lt(this.context,this._getLoopDuration());t.id=this.context.transport.scheduleRepeat(this._tick.bind(this),i,new Lt(this.context,n),e)}else t.id=this.context.transport.schedule(this._tick.bind(this),new Lt(this.context,n))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t}get probability(){return this._probability}set probability(t){this._probability=t}get humanize(){return this._humanize}set humanize(t){this._humanize=t}start(t){const e=this.toTicks(t);return"stopped"===this._state.getValueAtTime(e)&&(this._state.add({id:-1,state:"started",time:e}),this._rescheduleEvents(e)),this}stop(t){this.cancel(t);const e=this.toTicks(t);if("started"===this._state.getValueAtTime(e)){this._state.setStateAtTime("stopped",e,{id:-1});const t=this._state.getBefore(e);let n=e;null!==t&&(n=t.time),this._rescheduleEvents(n)}return this}cancel(t){t=I(t,-1/0);const e=this.toTicks(t);return this._state.forEachFrom(e,t=>{this.context.transport.clear(t.id)}),this._state.cancel(e),this}_tick(t){const e=this.context.transport.getTicksAtTime(t);if(!this.mute&&"started"===this._state.getValueAtTime(e)){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let e=.02;v(this.humanize)||(e=this.toSeconds(this.humanize)),t+=(2*Math.random()-1)*e}this.callback(t,this.value)}}_getLoopDuration(){return Math.round((this._loopEnd-this._loopStart)/this._playbackRate)}get loop(){return this._loop}set loop(t){this._loop=t,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._rescheduleEvents()}get loopEnd(){return new Lt(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._rescheduleEvents()}get loopStart(){return new Lt(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const t=this.context.transport.ticks,e=this._state.get(t);if(null!==e&&"started"===e.state){const n=this._getLoopDuration();return(t-e.time)%n/n}return 0}return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class mn extends Tt{constructor(){super(q(mn.getDefaults(),arguments,["callback","interval"])),this.name="Loop";const t=q(mn.getDefaults(),arguments,["callback","interval"]);this._event=new _n({context:this.context,callback:this._tick.bind(this),loop:!0,loopEnd:t.interval,playbackRate:t.playbackRate,probability:t.probability}),this.callback=t.callback,this.iterations=t.iterations}static getDefaults(){return Object.assign(Tt.getDefaults(),{interval:"4n",callback:K,playbackRate:1,iterations:1/0,probability:1,mute:!1,humanize:!1})}start(t){return this._event.start(t),this}stop(t){return this._event.stop(t),this}cancel(t){return this._event.cancel(t),this}_tick(t){this.callback(t)}get state(){return this._event.state}get progress(){return this._event.progress}get interval(){return this._event.loopEnd}set interval(t){this._event.loopEnd=t}get playbackRate(){return this._event.playbackRate}set playbackRate(t){this._event.playbackRate=t}get humanize(){return this._event.humanize}set humanize(t){this._event.humanize=t}get probability(){return this._event.probability}set probability(t){this._event.probability=t}get mute(){return this._event.mute}set mute(t){this._event.mute=t}get iterations(){return!0===this._event.loop?1/0:this._event.loop}set iterations(t){this._event.loop=t===1/0||t}dispose(){return super.dispose(),this._event.dispose(),this}}class gn extends _n{constructor(){super(q(gn.getDefaults(),arguments,["callback","events"])),this.name="Part",this._state=new Ot("stopped"),this._events=new Set;const t=q(gn.getDefaults(),arguments,["callback","events"]);this._state.increasing=!0,t.events.forEach(t=>{y(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(_n.getDefaults(),{events:[]})}start(t,e){const n=this.toTicks(t);if("started"!==this._state.getValueAtTime(n)){e=I(e,this._loop?this._loopStart:0),e=this._loop?I(e,this._loopStart):I(e,0);const t=this.toTicks(e);this._state.add({id:-1,offset:t,state:"started",time:n}),this._forEach(e=>{this._startNote(e,n,t)})}return this}_startNote(t,e,n){e-=n,this._loop?t.startOffset>=this._loopStart&&t.startOffset=n&&(t.loop=!1,t.start(new Lt(this.context,e))):t.startOffset>=n&&t.start(new Lt(this.context,e))}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(t){const e=this.toTicks(t);return this._state.cancel(e),this._state.setStateAtTime("stopped",e),this._forEach(e=>{e.stop(t)}),this}at(t,e){const n=new xt(this.context,t).toTicks(),s=new Lt(this.context,1).toSeconds(),i=this._events.values();let o=i.next();for(;!o.done;){const t=o.value;if(Math.abs(n-t.startOffset){"started"===e.state?this._startNote(t,e.time,e.offset):t.stop(new Lt(this.context,e.time))})}remove(t,e){return g(t)&&t.hasOwnProperty("time")&&(t=(e=t).time),t=this.toTicks(t),this._events.forEach(n=>{n.startOffset===t&&(p(e)||f(e)&&n.value===e)&&(this._events.delete(n),n.dispose())}),this}clear(){return this._forEach(t=>t.dispose()),this._events.clear(),this}cancel(t){return this._forEach(e=>e.cancel(t)),this._state.cancel(this.toTicks(t)),this}_forEach(t){return this._events&&this._events.forEach(e=>{e instanceof gn?e._forEach(t):t(e)}),this}_setAll(t,e){this._forEach(n=>{n[t]=e})}_tick(t,e){this.mute||this.callback(t,e)}_testLoopBoundries(t){this._loop&&(t.startOffset=this._loopEnd)?t.cancel(0):"stopped"===t.state&&this._restartEvent(t)}get probability(){return this._probability}set probability(t){this._probability=t,this._setAll("probability",t)}get humanize(){return this._humanize}set humanize(t){this._humanize=t,this._setAll("humanize",t)}get loop(){return this._loop}set loop(t){this._loop=t,this._forEach(e=>{e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.loop=t,this._testLoopBoundries(e)})}get loopEnd(){return new Lt(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._forEach(e=>{e.loopEnd=t,this._testLoopBoundries(e)})}get loopStart(){return new Lt(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._setAll("playbackRate",t)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}function*vn(t){let e=0;for(;e=0;)e=xn(e,t),yield t[e],e--}function*bn(t,e){for(;;)yield*e(t)}function xn(t,e){return B(t,0,e.length-1)}function*wn(t,e){let n=e?0:t.length-1;for(;;)n=xn(n,t),yield t[n],e?(n++,n>=t.length-1&&(e=!1)):(n--,n<=0&&(e=!0))}function*Tn(t){let e=0,n=0;for(;e=0;)e=xn(e,t),yield t[e],n++,e+=n%2?-2:1}function*Sn(t){const e=[];for(let n=0;n0;){const n=xn(e.splice(Math.floor(e.length*Math.random()),1)[0],t);yield t[n]}}function*Cn(t,e="up",n=0){switch(r(t.length>0,"The array must have more than one value in it"),e){case"up":yield*bn(t,vn);case"down":yield*bn(t,yn);case"upDown":yield*wn(t,!0);case"downUp":yield*wn(t,!1);case"alternateUp":yield*bn(t,Tn);case"alternateDown":yield*bn(t,On);case"random":yield*function*(t){for(;;){const e=Math.floor(Math.random()*t.length);yield t[e]}}(t);case"randomOnce":yield*bn(t,Sn);case"randomWalk":yield*function*(t){let e=Math.floor(Math.random()*t.length);for(;;)0===e?e++:e===t.length-1||Math.random()<.5?e--:e++,yield t[e]}(t)}}class kn extends mn{constructor(){super(q(kn.getDefaults(),arguments,["callback","values","pattern"])),this.name="Pattern";const t=q(kn.getDefaults(),arguments,["callback","values","pattern"]);this.callback=t.callback,this._values=t.values,this._pattern=Cn(t.values,t.pattern),this._type=t.pattern}static getDefaults(){return Object.assign(mn.getDefaults(),{pattern:"up",values:[],callback:K})}_tick(t){const e=this._pattern.next();this._value=e.value,this.callback(t,this._value)}get values(){return this._values}set values(t){this._values=t,this.pattern=this._type}get value(){return this._value}get pattern(){return this._type}set pattern(t){this._type=t,this._pattern=Cn(this._values,this._type)}}class An extends _n{constructor(){super(q(An.getDefaults(),arguments,["callback","events","subdivision"])),this.name="Sequence",this._part=new gn({callback:this._seqCallback.bind(this),context:this.context}),this._events=[],this._eventsArray=[];const t=q(An.getDefaults(),arguments,["callback","events","subdivision"]);this._subdivision=this.toTicks(t.subdivision),this.events=t.events,this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.playbackRate=t.playbackRate,this.probability=t.probability,this.humanize=t.humanize,this.mute=t.mute,this.playbackRate=t.playbackRate}static getDefaults(){return Object.assign(F(_n.getDefaults(),["value"]),{events:[],loop:!0,loopEnd:0,loopStart:0,subdivision:"8n"})}_seqCallback(t,e){null!==e&&this.callback(t,e)}get events(){return this._events}set events(t){this.clear(),this._eventsArray=t,this._events=this._createSequence(this._eventsArray),this._eventsUpdated()}start(t,e){return this._part.start(t,e?this._indexTime(e):e),this}stop(t){return this._part.stop(t),this}get subdivision(){return new Lt(this.context,this._subdivision).toSeconds()}_createSequence(t){return new Proxy(t,{get:(t,e)=>t[e],set:(t,e,n)=>(b(e)&&isFinite(parseInt(e,10))&&y(n)?t[e]=this._createSequence(n):t[e]=n,this._eventsUpdated(),!0)})}_eventsUpdated(){this._part.clear(),this._rescheduleSequence(this._eventsArray,this._subdivision,this.startOffset),this.loopEnd=this.loopEnd}_rescheduleSequence(t,e,n){t.forEach((t,s)=>{const i=s*e+n;if(y(t))this._rescheduleSequence(t,e/t.length,i);else{const e=new Lt(this.context,i,"i").toSeconds();this._part.add(e,t)}})}_indexTime(t){return new Lt(this.context,t*this._subdivision+this.startOffset).toSeconds()}clear(){return this._part.clear(),this}dispose(){return super.dispose(),this._part.dispose(),this}get loop(){return this._part.loop}set loop(t){this._part.loop=t}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this._part.loopStart=this._indexTime(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this._part.loopEnd=0===t?this._indexTime(this._eventsArray.length):this._indexTime(t)}get startOffset(){return this._part.startOffset}set startOffset(t){this._part.startOffset=t}get playbackRate(){return this._part.playbackRate}set playbackRate(t){this._part.playbackRate=t}get probability(){return this._part.probability}set probability(t){this._part.probability=t}get progress(){return this._part.progress}get humanize(){return this._part.humanize}set humanize(t){this._part.humanize=t}get length(){return this._part.length}}class Dn extends Ct{constructor(){super(Object.assign(q(Dn.getDefaults(),arguments,["fade"]))),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new Ee({context:this.context}),this.a=new Mt({context:this.context,gain:0}),this.b=new Mt({context:this.context,gain:0}),this.output=new Mt({context:this.context}),this._internalChannels=[this.a,this.b];const t=q(Dn.getDefaults(),arguments,["fade"]);this.fade=new Rt({context:this.context,units:"normalRange",value:t.fade}),$(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",At(this._split,this.a.gain,0),At(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(Ct.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}class Mn extends Ct{constructor(t){super(t),this.name="Effect",this._dryWet=new Dn({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new Mt({context:this.context}),this.effectReturn=new Mt({context:this.context}),this.input=new Mt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(t.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],$(this,"wet")}static getDefaults(){return Object.assign(Ct.getDefaults(),{wet:1})}connectEffect(t){return this._internalChannels.push(t),this.effectSend.chain(t,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}}class jn extends Mn{constructor(t){super(t),this.name="LFOEffect",this._lfo=new Se({context:this.context,frequency:t.frequency,amplitude:t.depth}),this.depth=this._lfo.amplitude,this.frequency=this._lfo.frequency,this.type=t.type,$(this,["frequency","depth"])}static getDefaults(){return Object.assign(Mn.getDefaults(),{frequency:1,type:"sine",depth:1})}start(t){return this._lfo.start(t),this}stop(t){return this._lfo.stop(t),this}sync(){return this._lfo.sync(),this}unsync(){return this._lfo.unsync(),this}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class En extends jn{constructor(){super(q(En.getDefaults(),arguments,["frequency","baseFrequency","octaves"])),this.name="AutoFilter";const t=q(En.getDefaults(),arguments,["frequency","baseFrequency","octaves"]);this.filter=new Xe(Object.assign(t.filter,{context:this.context})),this.connectEffect(this.filter),this._lfo.connect(this.filter.frequency),this.octaves=t.octaves,this.baseFrequency=t.baseFrequency}static getDefaults(){return Object.assign(jn.getDefaults(),{baseFrequency:200,octaves:2.6,filter:{type:"lowpass",rolloff:-12,Q:1}})}get baseFrequency(){return this._lfo.min}set baseFrequency(t){this._lfo.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._lfo.max=this._lfo.min*Math.pow(2,t)}dispose(){return super.dispose(),this.filter.dispose(),this}}class Rn extends Ct{constructor(){super(Object.assign(q(Rn.getDefaults(),arguments,["pan"]))),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner;const t=q(Rn.getDefaults(),arguments,["pan"]);this.pan=new St({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode="explicit",$(this,"pan")}static getDefaults(){return Object.assign(Ct.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}class qn extends jn{constructor(){super(q(qn.getDefaults(),arguments,["frequency"])),this.name="AutoPanner";const t=q(qn.getDefaults(),arguments,["frequency"]);this._panner=new Rn({context:this.context,channelCount:t.channelCount}),this.connectEffect(this._panner),this._lfo.connect(this._panner.pan),this._lfo.min=-1,this._lfo.max=1}static getDefaults(){return Object.assign(jn.getDefaults(),{channelCount:1})}dispose(){return super.dispose(),this._panner.dispose(),this}}class In extends Ct{constructor(){super(q(In.getDefaults(),arguments,["smoothing"])),this.name="Follower";const t=q(In.getDefaults(),arguments,["smoothing"]);this._abs=this.input=new je({context:this.context}),this._lowpass=this.output=new hn({context:this.context,frequency:1/this.toSeconds(t.smoothing),type:"lowpass"}),this._abs.connect(this._lowpass),this._smoothing=t.smoothing}static getDefaults(){return Object.assign(Ct.getDefaults(),{smoothing:.05})}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this._lowpass.frequency=1/this.toSeconds(this.smoothing)}dispose(){return super.dispose(),this._abs.dispose(),this._lowpass.dispose(),this}}class Fn extends Mn{constructor(){super(q(Fn.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"])),this.name="AutoWah";const t=q(Fn.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"]);this._follower=new In({context:this.context,smoothing:t.follower}),this._sweepRange=new Ne({context:this.context,min:0,max:1,exponent:.5}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this._inputBoost=new Mt({context:this.context}),this._bandpass=new Xe({context:this.context,rolloff:-48,frequency:0,Q:t.Q}),this._peaking=new Xe({context:this.context,type:"peaking"}),this._peaking.gain.value=t.gain,this.gain=this._peaking.gain,this.Q=this._bandpass.Q,this.effectSend.chain(this._inputBoost,this._follower,this._sweepRange),this._sweepRange.connect(this._bandpass.frequency),this._sweepRange.connect(this._peaking.frequency),this.effectSend.chain(this._bandpass,this._peaking,this.effectReturn),this._setSweepRange(),this.sensitivity=t.sensitivity,$(this,["gain","Q"])}static getDefaults(){return Object.assign(Mn.getDefaults(),{baseFrequency:100,octaves:6,sensitivity:0,Q:2,gain:2,follower:.2})}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._setSweepRange()}get follower(){return this._follower.smoothing}set follower(t){this._follower.smoothing=t}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){this._baseFrequency=this.toFrequency(t),this._setSweepRange()}get sensitivity(){return ct(1/this._inputBoost.gain.value)}set sensitivity(t){this._inputBoost.gain.value=1/at(t)}_setSweepRange(){this._sweepRange.min=this._baseFrequency,this._sweepRange.max=Math.min(this._baseFrequency*Math.pow(2,this._octaves),this.context.sampleRate/2)}dispose(){return super.dispose(),this._follower.dispose(),this._sweepRange.dispose(),this._bandpass.dispose(),this._peaking.dispose(),this._inputBoost.dispose(),this}}an("bit-crusher","\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n");class Vn extends Mn{constructor(){super(q(Vn.getDefaults(),arguments,["bits"])),this.name="BitCrusher";const t=q(Vn.getDefaults(),arguments,["bits"]);this._bitCrusherWorklet=new Nn({context:this.context,bits:t.bits}),this.connectEffect(this._bitCrusherWorklet),this.bits=this._bitCrusherWorklet.bits}static getDefaults(){return Object.assign(Mn.getDefaults(),{bits:4})}dispose(){return super.dispose(),this._bitCrusherWorklet.dispose(),this}}class Nn extends cn{constructor(){super(q(Nn.getDefaults(),arguments)),this.name="BitCrusherWorklet";const t=q(Nn.getDefaults(),arguments);this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.bits=new St({context:this.context,value:t.bits,units:"positive",minValue:1,maxValue:16,param:this._dummyParam,swappable:!0})}static getDefaults(){return Object.assign(cn.getDefaults(),{bits:12})}_audioWorkletName(){return"bit-crusher"}onReady(t){kt(this.input,t,this.output);const e=t.parameters.get("bits");this.bits.setParam(e)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.bits.dispose(),this}}class Pn extends Mn{constructor(){super(q(Pn.getDefaults(),arguments,["order"])),this.name="Chebyshev";const t=q(Pn.getDefaults(),arguments,["order"]);this._shaper=new de({context:this.context,length:4096}),this._order=t.order,this.connectEffect(this._shaper),this.order=t.order,this.oversample=t.oversample}static getDefaults(){return Object.assign(Mn.getDefaults(),{order:1,oversample:"none"})}_getCoefficient(t,e,n){return n.has(e)||(0===e?n.set(e,0):1===e?n.set(e,t):n.set(e,2*t*this._getCoefficient(t,e-1,n)-this._getCoefficient(t,e-2,n))),n.get(e)}get order(){return this._order}set order(t){this._order=t,this._shaper.setMap(e=>this._getCoefficient(e,t,new Map))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class Ln extends Ct{constructor(){super(q(Ln.getDefaults(),arguments,["channels"])),this.name="Split";const t=q(Ln.getDefaults(),arguments,["channels"]);this._splitter=this.input=this.output=this.context.createChannelSplitter(t.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(Ct.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class zn extends Ct{constructor(){super(q(zn.getDefaults(),arguments,["channels"])),this.name="Merge";const t=q(zn.getDefaults(),arguments,["channels"]);this._merger=this.output=this.input=this.context.createChannelMerger(t.channels)}static getDefaults(){return Object.assign(Ct.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class Bn extends Ct{constructor(t){super(t),this.name="StereoEffect",this.input=new Mt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new Dn({context:this.context,fade:t.wet}),this.wet=this._dryWet.fade,this._split=new Ln({context:this.context,channels:2}),this._merge=new zn({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),$(this,["wet"])}connectEffectLeft(...t){this._split.connect(t[0],0,0),kt(...t),At(t[t.length-1],this._merge,0,0)}connectEffectRight(...t){this._split.connect(t[0],1,0),kt(...t),At(t[t.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(Ct.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class Wn extends Bn{constructor(t){super(t),this.feedback=new Rt({context:this.context,value:t.feedback,units:"normalRange"}),this._feedbackL=new Mt({context:this.context}),this._feedbackR=new Mt({context:this.context}),this._feedbackSplit=new Ln({context:this.context,channels:2}),this._feedbackMerge=new zn({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),$(this,["feedback"])}static getDefaults(){return Object.assign(Bn.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class Un extends Wn{constructor(){super(q(Un.getDefaults(),arguments,["frequency","delayTime","depth"])),this.name="Chorus";const t=q(Un.getDefaults(),arguments,["frequency","delayTime","depth"]);this._depth=t.depth,this._delayTime=t.delayTime/1e3,this._lfoL=new Se({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new Se({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Qt({context:this.context}),this._delayNodeR=new Qt({context:this.context}),this.frequency=this._lfoL.frequency,$(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=t.type,this.spread=t.spread}static getDefaults(){return Object.assign(Wn.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(t){this._depth=t;const e=this._delayTime*t;this._lfoL.min=Math.max(this._delayTime-e,0),this._lfoL.max=this._delayTime+e,this._lfoR.min=Math.max(this._delayTime-e,0),this._lfoR.max=this._delayTime+e}get delayTime(){return 1e3*this._delayTime}set delayTime(t){this._delayTime=t/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class Gn extends Mn{constructor(){super(q(Gn.getDefaults(),arguments,["distortion"])),this.name="Distortion";const t=q(Gn.getDefaults(),arguments,["distortion"]);this._shaper=new de({context:this.context,length:4096}),this._distortion=t.distortion,this.connectEffect(this._shaper),this.distortion=t.distortion,this.oversample=t.oversample}static getDefaults(){return Object.assign(Mn.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(t){this._distortion=t;const e=100*t,n=Math.PI/180;this._shaper.setMap(t=>Math.abs(t)<.001?0:(3+e)*t*20*n/(Math.PI+e*Math.abs(t)))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class Yn extends Mn{constructor(t){super(t),this.name="FeedbackEffect",this._feedbackGain=new Mt({context:this.context,gain:t.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,$(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Mn.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class Qn extends Yn{constructor(){super(q(Qn.getDefaults(),arguments,["delayTime","feedback"])),this.name="FeedbackDelay";const t=q(Qn.getDefaults(),arguments,["delayTime","feedback"]);this._delayNode=new Qt({context:this.context,delayTime:t.delayTime,maxDelay:t.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),$(this,"delayTime")}static getDefaults(){return Object.assign(Yn.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class Zn extends Ct{constructor(t){super(t),this.name="PhaseShiftAllpass",this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.offset90=new Mt({context:this.context});this._bank0=this._createAllPassFilterBank([.6923878,.9360654322959,.988229522686,.9987488452737]),this._bank1=this._createAllPassFilterBank([.4021921162426,.856171088242,.9722909545651,.9952884791278]),this._oneSampleDelay=this.context.createIIRFilter([0,1],[1,0]),kt(this.input,...this._bank0,this._oneSampleDelay,this.output),kt(this.input,...this._bank1,this.offset90)}_createAllPassFilterBank(t){return t.map(t=>{const e=[[t*t,0,-1],[1,0,-t*t]];return this.context.createIIRFilter(e[0],e[1])})}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.offset90.dispose(),this._bank0.forEach(t=>t.disconnect()),this._bank1.forEach(t=>t.disconnect()),this._oneSampleDelay.disconnect(),this}}class Xn extends Mn{constructor(){super(q(Xn.getDefaults(),arguments,["frequency"])),this.name="FrequencyShifter";const t=q(Xn.getDefaults(),arguments,["frequency"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency,minValue:-this.context.sampleRate/2,maxValue:this.context.sampleRate/2}),this._sine=new ue({context:this.context,type:"sine"}),this._cosine=new he({context:this.context,phase:-90,type:"sine"}),this._sineMultiply=new fe({context:this.context}),this._cosineMultiply=new fe({context:this.context}),this._negate=new Re({context:this.context}),this._add=new we({context:this.context}),this._phaseShifter=new Zn({context:this.context}),this.effectSend.connect(this._phaseShifter),this.frequency.fan(this._sine.frequency,this._cosine.frequency),this._phaseShifter.offset90.connect(this._cosineMultiply),this._cosine.connect(this._cosineMultiply.factor),this._phaseShifter.connect(this._sineMultiply),this._sine.connect(this._sineMultiply.factor),this._sineMultiply.connect(this._negate),this._cosineMultiply.connect(this._add),this._negate.connect(this._add.addend),this._add.connect(this.effectReturn);const e=this.immediate();this._sine.start(e),this._cosine.start(e)}static getDefaults(){return Object.assign(Mn.getDefaults(),{frequency:0})}dispose(){return super.dispose(),this.frequency.dispose(),this._add.dispose(),this._cosine.dispose(),this._cosineMultiply.dispose(),this._negate.dispose(),this._phaseShifter.dispose(),this._sine.dispose(),this._sineMultiply.dispose(),this}}const Hn=[1557/44100,1617/44100,1491/44100,1422/44100,1277/44100,1356/44100,1188/44100,1116/44100],$n=[225,556,441,341];class Jn extends Bn{constructor(){super(q(Jn.getDefaults(),arguments,["roomSize","dampening"])),this.name="Freeverb",this._combFilters=[],this._allpassFiltersL=[],this._allpassFiltersR=[];const t=q(Jn.getDefaults(),arguments,["roomSize","dampening"]);this.roomSize=new Rt({context:this.context,value:t.roomSize,units:"normalRange"}),this._allpassFiltersL=$n.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._allpassFiltersR=$n.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._combFilters=Hn.map((e,n)=>{const s=new ln({context:this.context,dampening:t.dampening,delayTime:e});return ne.dampening=t)}dispose(){return super.dispose(),this._allpassFiltersL.forEach(t=>t.disconnect()),this._allpassFiltersR.forEach(t=>t.disconnect()),this._combFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this}}const Kn=[.06748,.06404,.08212,.09004],ts=[.773,.802,.753,.733],es=[347,113,37];class ns extends Bn{constructor(){super(q(ns.getDefaults(),arguments,["roomSize"])),this.name="JCReverb",this._allpassFilters=[],this._feedbackCombFilters=[];const t=q(ns.getDefaults(),arguments,["roomSize"]);this.roomSize=new Rt({context:this.context,value:t.roomSize,units:"normalRange"}),this._scaleRoomSize=new Te({context:this.context,min:-.733,max:.197}),this._allpassFilters=es.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._feedbackCombFilters=Kn.map((t,e)=>{const n=new un({context:this.context,delayTime:t});return this._scaleRoomSize.connect(n.resonance),n.resonance.value=ts[e],et.disconnect()),this._feedbackCombFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this._scaleRoomSize.dispose(),this}}class ss extends Wn{constructor(t){super(t),this._feedbackL.disconnect(),this._feedbackL.connect(this._feedbackMerge,0,1),this._feedbackR.disconnect(),this._feedbackR.connect(this._feedbackMerge,0,0),$(this,["feedback"])}}class is extends ss{constructor(){super(q(is.getDefaults(),arguments,["delayTime","feedback"])),this.name="PingPongDelay";const t=q(is.getDefaults(),arguments,["delayTime","feedback"]);this._leftDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this._rightDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this._rightPreDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this.delayTime=new Rt({context:this.context,units:"time",value:t.delayTime}),this.connectEffectLeft(this._leftDelay),this.connectEffectRight(this._rightPreDelay,this._rightDelay),this.delayTime.fan(this._leftDelay.delayTime,this._rightDelay.delayTime,this._rightPreDelay.delayTime),this._feedbackL.disconnect(),this._feedbackL.connect(this._rightDelay),$(this,["delayTime"])}static getDefaults(){return Object.assign(ss.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._leftDelay.dispose(),this._rightDelay.dispose(),this._rightPreDelay.dispose(),this.delayTime.dispose(),this}}class os extends Yn{constructor(){super(q(os.getDefaults(),arguments,["pitch"])),this.name="PitchShift";const t=q(os.getDefaults(),arguments,["pitch"]);this._frequency=new Rt({context:this.context}),this._delayA=new Qt({maxDelay:1,context:this.context}),this._lfoA=new Se({context:this.context,min:0,max:.1,type:"sawtooth"}).connect(this._delayA.delayTime),this._delayB=new Qt({maxDelay:1,context:this.context}),this._lfoB=new Se({context:this.context,min:0,max:.1,type:"sawtooth",phase:180}).connect(this._delayB.delayTime),this._crossFade=new Dn({context:this.context}),this._crossFadeLFO=new Se({context:this.context,min:0,max:1,type:"triangle",phase:90}).connect(this._crossFade.fade),this._feedbackDelay=new Qt({delayTime:t.delayTime,context:this.context}),this.delayTime=this._feedbackDelay.delayTime,$(this,"delayTime"),this._pitch=t.pitch,this._windowSize=t.windowSize,this._delayA.connect(this._crossFade.a),this._delayB.connect(this._crossFade.b),this._frequency.fan(this._lfoA.frequency,this._lfoB.frequency,this._crossFadeLFO.frequency),this.effectSend.fan(this._delayA,this._delayB),this._crossFade.chain(this._feedbackDelay,this.effectReturn);const e=this.now();this._lfoA.start(e),this._lfoB.start(e),this._crossFadeLFO.start(e),this.windowSize=this._windowSize}static getDefaults(){return Object.assign(Yn.getDefaults(),{pitch:0,windowSize:.1,delayTime:0,feedback:0})}get pitch(){return this._pitch}set pitch(t){this._pitch=t;let e=0;t<0?(this._lfoA.min=0,this._lfoA.max=this._windowSize,this._lfoB.min=0,this._lfoB.max=this._windowSize,e=ut(t-1)+1):(this._lfoA.min=this._windowSize,this._lfoA.max=0,this._lfoB.min=this._windowSize,this._lfoB.max=0,e=ut(t)-1),this._frequency.value=e*(1.2/this._windowSize)}get windowSize(){return this._windowSize}set windowSize(t){this._windowSize=this.toSeconds(t),this.pitch=this._pitch}dispose(){return super.dispose(),this._frequency.dispose(),this._delayA.dispose(),this._delayB.dispose(),this._lfoA.dispose(),this._lfoB.dispose(),this._crossFade.dispose(),this._crossFadeLFO.dispose(),this._feedbackDelay.dispose(),this}}class rs extends Bn{constructor(){super(q(rs.getDefaults(),arguments,["frequency","octaves","baseFrequency"])),this.name="Phaser";const t=q(rs.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);this._lfoL=new Se({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new Se({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this.Q=new Rt({context:this.context,value:t.Q,units:"positive"}),this._filtersL=this._makeFilters(t.stages,this._lfoL),this._filtersR=this._makeFilters(t.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=t.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=t.baseFrequency,this.octaves=t.octaves,this._lfoL.start(),this._lfoR.start(),$(this,["frequency","Q"])}static getDefaults(){return Object.assign(Bn.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(t,e){const n=[];for(let s=0;st.disconnect()),this._filtersR.forEach(t=>t.disconnect()),this.frequency.dispose(),this}}class as extends Mn{constructor(){super(q(as.getDefaults(),arguments,["decay"])),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve();const t=q(as.getDefaults(),arguments,["decay"]);this._decay=t.decay,this._preDelay=t.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Mn.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(t){a(t=this.toSeconds(t),.001),this._decay=t,this.generate()}get preDelay(){return this._preDelay}set preDelay(t){a(t=this.toSeconds(t),0),this._preDelay=t,this.generate()}generate(){return S(this,void 0,void 0,(function*(){const t=this.ready,e=new et(2,this._decay+this._preDelay,this.context.sampleRate),n=new ie({context:e}),s=new ie({context:e}),i=new zn({context:e});n.connect(i,0,0),s.connect(i,0,1);const o=new Mt({context:e}).toDestination();i.connect(o),n.start(0),s.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const r=e.render();return this.ready=r.then(K),yield t,this._convolver.buffer=(yield r).get(),this}))}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class cs extends Ct{constructor(){super(q(cs.getDefaults(),arguments)),this.name="MidSideSplit",this._split=this.input=new Ln({channels:2,context:this.context}),this._midAdd=new we({context:this.context}),this.mid=new fe({context:this.context,value:Math.SQRT1_2}),this._sideSubtract=new qe({context:this.context}),this.side=new fe({context:this.context,value:Math.SQRT1_2}),this._split.connect(this._midAdd,0),this._split.connect(this._midAdd.addend,1),this._split.connect(this._sideSubtract,0),this._split.connect(this._sideSubtract.subtrahend,1),this._midAdd.connect(this.mid),this._sideSubtract.connect(this.side)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midAdd.dispose(),this._sideSubtract.dispose(),this._split.dispose(),this}}class us extends Ct{constructor(){super(q(us.getDefaults(),arguments)),this.name="MidSideMerge",this.mid=new Mt({context:this.context}),this.side=new Mt({context:this.context}),this._left=new we({context:this.context}),this._leftMult=new fe({context:this.context,value:Math.SQRT1_2}),this._right=new qe({context:this.context}),this._rightMult=new fe({context:this.context,value:Math.SQRT1_2}),this._merge=this.output=new zn({context:this.context}),this.mid.fan(this._left),this.side.connect(this._left.addend),this.mid.connect(this._right),this.side.connect(this._right.subtrahend),this._left.connect(this._leftMult),this._right.connect(this._rightMult),this._leftMult.connect(this._merge,0,0),this._rightMult.connect(this._merge,0,1)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._leftMult.dispose(),this._rightMult.dispose(),this._left.dispose(),this._right.dispose(),this}}class hs extends Mn{constructor(t){super(t),this.name="MidSideEffect",this._midSideMerge=new us({context:this.context}),this._midSideSplit=new cs({context:this.context}),this._midSend=this._midSideSplit.mid,this._sideSend=this._midSideSplit.side,this._midReturn=this._midSideMerge.mid,this._sideReturn=this._midSideMerge.side,this.effectSend.connect(this._midSideSplit),this._midSideMerge.connect(this.effectReturn)}connectEffectMid(...t){this._midSend.chain(...t,this._midReturn)}connectEffectSide(...t){this._sideSend.chain(...t,this._sideReturn)}dispose(){return super.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this._midSend.dispose(),this._sideSend.dispose(),this._midReturn.dispose(),this._sideReturn.dispose(),this}}class ls extends hs{constructor(){super(q(ls.getDefaults(),arguments,["width"])),this.name="StereoWidener";const t=q(ls.getDefaults(),arguments,["width"]);this.width=new Rt({context:this.context,value:t.width,units:"normalRange"}),$(this,["width"]),this._twoTimesWidthMid=new fe({context:this.context,value:2}),this._twoTimesWidthSide=new fe({context:this.context,value:2}),this._midMult=new fe({context:this.context}),this._twoTimesWidthMid.connect(this._midMult.factor),this.connectEffectMid(this._midMult),this._oneMinusWidth=new qe({context:this.context}),this._oneMinusWidth.connect(this._twoTimesWidthMid),At(this.context.getConstant(1),this._oneMinusWidth),this.width.connect(this._oneMinusWidth.subtrahend),this._sideMult=new fe({context:this.context}),this.width.connect(this._twoTimesWidthSide),this._twoTimesWidthSide.connect(this._sideMult.factor),this.connectEffectSide(this._sideMult)}static getDefaults(){return Object.assign(hs.getDefaults(),{width:.5})}dispose(){return super.dispose(),this.width.dispose(),this._midMult.dispose(),this._sideMult.dispose(),this._twoTimesWidthMid.dispose(),this._twoTimesWidthSide.dispose(),this._oneMinusWidth.dispose(),this}}class ds extends Bn{constructor(){super(q(ds.getDefaults(),arguments,["frequency","depth"])),this.name="Tremolo";const t=q(ds.getDefaults(),arguments,["frequency","depth"]);this._lfoL=new Se({context:this.context,type:t.type,min:1,max:0}),this._lfoR=new Se({context:this.context,type:t.type,min:1,max:0}),this._amplitudeL=new Mt({context:this.context}),this._amplitudeR=new Mt({context:this.context}),this.frequency=new Rt({context:this.context,value:t.frequency,units:"frequency"}),this.depth=new Rt({context:this.context,value:t.depth,units:"normalRange"}),$(this,["frequency","depth"]),this.connectEffectLeft(this._amplitudeL),this.connectEffectRight(this._amplitudeR),this._lfoL.connect(this._amplitudeL.gain),this._lfoR.connect(this._amplitudeR.gain),this.frequency.fan(this._lfoL.frequency,this._lfoR.frequency),this.depth.fan(this._lfoR.amplitude,this._lfoL.amplitude),this.spread=t.spread}static getDefaults(){return Object.assign(Bn.getDefaults(),{frequency:10,type:"sine",depth:.5,spread:180})}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this.context.transport.syncSignal(this.frequency),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this.context.transport.unsyncSignal(this.frequency),this}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._amplitudeL.dispose(),this._amplitudeR.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class ps extends Mn{constructor(){super(q(ps.getDefaults(),arguments,["frequency","depth"])),this.name="Vibrato";const t=q(ps.getDefaults(),arguments,["frequency","depth"]);this._delayNode=new Qt({context:this.context,delayTime:0,maxDelay:t.maxDelay}),this._lfo=new Se({context:this.context,type:t.type,min:0,max:t.maxDelay,frequency:t.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=t.depth,$(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Mn.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class fs extends Ct{constructor(){super(q(fs.getDefaults(),arguments,["type","size"])),this.name="Analyser",this._analysers=[],this._buffers=[];const t=q(fs.getDefaults(),arguments,["type","size"]);this.input=this.output=this._gain=new Mt({context:this.context}),this._split=new Ln({context:this.context,channels:t.channels}),this.input.connect(this._split),a(t.channels,1);for(let e=0;e{const n=this._buffers[e];"fft"===this._type?t.getFloatFrequencyData(n):"waveform"===this._type&&t.getFloatTimeDomainData(n)}),1===this.channels?this._buffers[0]:this._buffers}get size(){return this._analysers[0].frequencyBinCount}set size(t){this._analysers.forEach((e,n)=>{e.fftSize=2*t,this._buffers[n]=new Float32Array(t)})}get channels(){return this._analysers.length}get type(){return this._type}set type(t){r("waveform"===t||"fft"===t,"Analyser: invalid type: "+t),this._type=t}get smoothing(){return this._analysers[0].smoothingTimeConstant}set smoothing(t){this._analysers.forEach(e=>e.smoothingTimeConstant=t)}dispose(){return super.dispose(),this._analysers.forEach(t=>t.disconnect()),this._split.dispose(),this._gain.dispose(),this}}class _s extends Ct{constructor(){super(q(_s.getDefaults(),arguments)),this.name="MeterBase",this.input=this.output=this._analyser=new fs({context:this.context,size:256,type:"waveform"})}dispose(){return super.dispose(),this._analyser.dispose(),this}}class ms extends _s{constructor(){super(q(ms.getDefaults(),arguments,["smoothing"])),this.name="Meter",this._rms=0;const t=q(ms.getDefaults(),arguments,["smoothing"]);this.input=this.output=this._analyser=new fs({context:this.context,size:256,type:"waveform",channels:t.channels}),this.smoothing=t.smoothing,this.normalRange=t.normalRange}static getDefaults(){return Object.assign(_s.getDefaults(),{smoothing:.8,normalRange:!1,channels:1})}getLevel(){return d("'getLevel' has been changed to 'getValue'"),this.getValue()}getValue(){const t=this._analyser.getValue(),e=(1===this.channels?[t]:t).map(t=>{const e=t.reduce((t,e)=>t+e*e,0),n=Math.sqrt(e/t.length);return this._rms=Math.max(n,this._rms*this.smoothing),this.normalRange?this._rms:ct(this._rms)});return 1===this.channels?e[0]:e}get channels(){return this._analyser.channels}dispose(){return super.dispose(),this._analyser.dispose(),this}}class gs extends _s{constructor(){super(q(gs.getDefaults(),arguments,["size"])),this.name="FFT";const t=q(gs.getDefaults(),arguments,["size"]);this.normalRange=t.normalRange,this._analyser.type="fft",this.size=t.size}static getDefaults(){return Object.assign(Ct.getDefaults(),{normalRange:!1,size:1024,smoothing:.8})}getValue(){return this._analyser.getValue().map(t=>this.normalRange?at(t):t)}get size(){return this._analyser.size}set size(t){this._analyser.size=t}get smoothing(){return this._analyser.smoothing}set smoothing(t){this._analyser.smoothing=t}getFrequencyOfIndex(t){return r(0<=t&&tt._updateSolo())}get muted(){return 0===this.input.gain.value}_addSolo(){bs._soloed.has(this.context)||bs._soloed.set(this.context,new Set),bs._soloed.get(this.context).add(this)}_removeSolo(){bs._soloed.has(this.context)&&bs._soloed.get(this.context).delete(this)}_isSoloed(){return bs._soloed.has(this.context)&&bs._soloed.get(this.context).has(this)}_noSolos(){return!bs._soloed.has(this.context)||bs._soloed.has(this.context)&&0===bs._soloed.get(this.context).size}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),bs._allSolos.get(this.context).delete(this),this._removeSolo(),this}}bs._allSolos=new Map,bs._soloed=new Map;class xs extends Ct{constructor(){super(q(xs.getDefaults(),arguments,["pan","volume"])),this.name="PanVol";const t=q(xs.getDefaults(),arguments,["pan","volume"]);this._panner=this.input=new Rn({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,$(this,["pan","volume"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class ws extends Ct{constructor(){super(q(ws.getDefaults(),arguments,["volume","pan"])),this.name="Channel";const t=q(ws.getDefaults(),arguments,["volume","pan"]);this._solo=this.input=new bs({solo:t.solo,context:this.context}),this._panVol=this.output=new xs({context:this.context,pan:t.pan,volume:t.volume,mute:t.mute,channelCount:t.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),$(this,["pan","volume"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(t){this._solo.solo=t}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(t){this._panVol.mute=t}_getBus(t){return ws.buses.has(t)||ws.buses.set(t,new Mt({context:this.context})),ws.buses.get(t)}send(t,e=0){const n=this._getBus(t),s=new Mt({context:this.context,units:"decibels",gain:e});return this.connect(s),s.connect(n),s}receive(t){return this._getBus(t).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}ws.buses=new Map;class Ts extends Ct{constructor(){super(q(Ts.getDefaults(),arguments,["lowFrequency","highFrequency"])),this.name="MultibandSplit",this.input=new Mt({context:this.context}),this.output=void 0,this.low=new Xe({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Xe({context:this.context,frequency:0,type:"highpass"}),this.mid=new Xe({context:this.context,frequency:0,type:"lowpass"}),this.high=new Xe({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high];const t=q(Ts.getDefaults(),arguments,["lowFrequency","highFrequency"]);this.lowFrequency=new Rt({context:this.context,units:"frequency",value:t.lowFrequency}),this.highFrequency=new Rt({context:this.context,units:"frequency",value:t.highFrequency}),this.Q=new Rt({context:this.context,units:"positive",value:t.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),$(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),J(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class Os extends Ct{constructor(){super(...arguments),this.name="Listener",this.positionX=new St({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new St({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new St({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new St({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new St({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new St({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new St({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new St({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new St({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(Ct.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}G(t=>{t.listener=new Os({context:t})}),Q(t=>{t.listener.dispose()});class Ss extends Ct{constructor(){super(q(Ss.getDefaults(),arguments,["positionX","positionY","positionZ"])),this.name="Panner3D";const t=q(Ss.getDefaults(),arguments,["positionX","positionY","positionZ"]);this._panner=this.input=this.output=this.context.createPanner(),this.panningModel=t.panningModel,this.maxDistance=t.maxDistance,this.distanceModel=t.distanceModel,this.coneOuterGain=t.coneOuterGain,this.coneOuterAngle=t.coneOuterAngle,this.coneInnerAngle=t.coneInnerAngle,this.refDistance=t.refDistance,this.rolloffFactor=t.rolloffFactor,this.positionX=new St({context:this.context,param:this._panner.positionX,value:t.positionX}),this.positionY=new St({context:this.context,param:this._panner.positionY,value:t.positionY}),this.positionZ=new St({context:this.context,param:this._panner.positionZ,value:t.positionZ}),this.orientationX=new St({context:this.context,param:this._panner.orientationX,value:t.orientationX}),this.orientationY=new St({context:this.context,param:this._panner.orientationY,value:t.orientationY}),this.orientationZ=new St({context:this.context,param:this._panner.orientationZ,value:t.orientationZ})}static getDefaults(){return Object.assign(Ct.getDefaults(),{coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:0,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1})}setPosition(t,e,n){return this.positionX.value=t,this.positionY.value=e,this.positionZ.value=n,this}setOrientation(t,e,n){return this.orientationX.value=t,this.orientationY.value=e,this.orientationZ.value=n,this}get panningModel(){return this._panner.panningModel}set panningModel(t){this._panner.panningModel=t}get refDistance(){return this._panner.refDistance}set refDistance(t){this._panner.refDistance=t}get rolloffFactor(){return this._panner.rolloffFactor}set rolloffFactor(t){this._panner.rolloffFactor=t}get distanceModel(){return this._panner.distanceModel}set distanceModel(t){this._panner.distanceModel=t}get coneInnerAngle(){return this._panner.coneInnerAngle}set coneInnerAngle(t){this._panner.coneInnerAngle=t}get coneOuterAngle(){return this._panner.coneOuterAngle}set coneOuterAngle(t){this._panner.coneOuterAngle=t}get coneOuterGain(){return this._panner.coneOuterGain}set coneOuterGain(t){this._panner.coneOuterGain=t}get maxDistance(){return this._panner.maxDistance}set maxDistance(t){this._panner.maxDistance=t}dispose(){return super.dispose(),this._panner.disconnect(),this.orientationX.dispose(),this.orientationY.dispose(),this.orientationZ.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this}}class Cs extends Ct{constructor(){super(q(Cs.getDefaults(),arguments)),this.name="Recorder";const t=q(Cs.getDefaults(),arguments);this.input=new Mt({context:this.context}),r(Cs.supported,"Media Recorder API is not available"),this._stream=this.context.createMediaStreamDestination(),this.input.connect(this._stream),this._recorder=new MediaRecorder(this._stream.stream,{mimeType:t.mimeType})}static getDefaults(){return Ct.getDefaults()}get mimeType(){return this._recorder.mimeType}static get supported(){return null!==w&&Reflect.has(w,"MediaRecorder")}get state(){return"inactive"===this._recorder.state?"stopped":"paused"===this._recorder.state?"paused":"started"}start(){return S(this,void 0,void 0,(function*(){r("started"!==this.state,"Recorder is already started");const t=new Promise(t=>{const e=()=>{this._recorder.removeEventListener("start",e,!1),t()};this._recorder.addEventListener("start",e,!1)});return this._recorder.start(),yield t}))}stop(){return S(this,void 0,void 0,(function*(){r("stopped"!==this.state,"Recorder is not started");const t=new Promise(t=>{const e=n=>{this._recorder.removeEventListener("dataavailable",e,!1),t(n.data)};this._recorder.addEventListener("dataavailable",e,!1)});return this._recorder.stop(),yield t}))}pause(){return r("started"===this.state,"Recorder must be started"),this._recorder.pause(),this}dispose(){return super.dispose(),this.input.dispose(),this._stream.disconnect(),this}}class ks extends Ct{constructor(){super(q(ks.getDefaults(),arguments,["threshold","ratio"])),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor;const t=q(ks.getDefaults(),arguments,["threshold","ratio"]);this.threshold=new St({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:t.threshold}),this.attack=new St({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:t.attack}),this.release=new St({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:t.release}),this.knee=new St({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:t.knee}),this.ratio=new St({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:t.ratio}),$(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class As extends Ct{constructor(){super(Object.assign(q(As.getDefaults(),arguments,["threshold","smoothing"]))),this.name="Gate";const t=q(As.getDefaults(),arguments,["threshold","smoothing"]);this._follower=new In({context:this.context,smoothing:t.smoothing}),this._gt=new Fe({context:this.context,value:at(t.threshold)}),this.input=new Mt({context:this.context}),this._gate=this.output=new Mt({context:this.context}),this.input.connect(this._gate),this.input.chain(this._follower,this._gt,this._gate.gain)}static getDefaults(){return Object.assign(Ct.getDefaults(),{smoothing:.1,threshold:-40})}get threshold(){return ct(this._gt.value)}set threshold(t){this._gt.value=at(t)}get smoothing(){return this._follower.smoothing}set smoothing(t){this._follower.smoothing=t}dispose(){return super.dispose(),this.input.dispose(),this._follower.dispose(),this._gt.dispose(),this._gate.dispose(),this}}class Ds extends Ct{constructor(){super(Object.assign(q(Ds.getDefaults(),arguments,["threshold"]))),this.name="Limiter";const t=q(Ds.getDefaults(),arguments,["threshold"]);this._compressor=this.input=this.output=new ks({context:this.context,ratio:20,attack:0,release:0,threshold:t.threshold}),this.threshold=this._compressor.threshold,$(this,"threshold")}static getDefaults(){return Object.assign(Ct.getDefaults(),{threshold:-12})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.dispose(),this.threshold.dispose(),this}}class Ms extends Ct{constructor(){super(Object.assign(q(Ms.getDefaults(),arguments))),this.name="MidSideCompressor";const t=q(Ms.getDefaults(),arguments);this._midSideSplit=this.input=new cs({context:this.context}),this._midSideMerge=this.output=new us({context:this.context}),this.mid=new ks(Object.assign(t.mid,{context:this.context})),this.side=new ks(Object.assign(t.side,{context:this.context})),this._midSideSplit.mid.chain(this.mid,this._midSideMerge.mid),this._midSideSplit.side.chain(this.side,this._midSideMerge.side),$(this,["mid","side"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},side:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10}})}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this}}class js extends Ct{constructor(){super(Object.assign(q(js.getDefaults(),arguments))),this.name="MultibandCompressor";const t=q(js.getDefaults(),arguments);this._splitter=this.input=new Ts({context:this.context,lowFrequency:t.lowFrequency,highFrequency:t.highFrequency}),this.lowFrequency=this._splitter.lowFrequency,this.highFrequency=this._splitter.highFrequency,this.output=new Mt({context:this.context}),this.low=new ks(Object.assign(t.low,{context:this.context})),this.mid=new ks(Object.assign(t.mid,{context:this.context})),this.high=new ks(Object.assign(t.high,{context:this.context})),this._splitter.low.chain(this.low,this.output),this._splitter.mid.chain(this.mid,this.output),this._splitter.high.chain(this.high,this.output),$(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{lowFrequency:250,highFrequency:2e3,low:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10},mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},high:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16}})}dispose(){return super.dispose(),this._splitter.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.output.dispose(),this}}class Es extends Ct{constructor(){super(q(Es.getDefaults(),arguments,["low","mid","high"])),this.name="EQ3",this.output=new Mt({context:this.context}),this._internalChannels=[];const t=q(Es.getDefaults(),arguments,["low","mid","high"]);this.input=this._multibandSplit=new Ts({context:this.context,highFrequency:t.highFrequency,lowFrequency:t.lowFrequency}),this._lowGain=new Mt({context:this.context,gain:t.low,units:"decibels"}),this._midGain=new Mt({context:this.context,gain:t.mid,units:"decibels"}),this._highGain=new Mt({context:this.context,gain:t.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),$(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(Ct.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),J(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}class Rs extends Ct{constructor(){super(q(Rs.getDefaults(),arguments,["url","onload"])),this.name="Convolver",this._convolver=this.context.createConvolver();const t=q(Rs.getDefaults(),arguments,["url","onload"]);this._buffer=new tt(t.url,e=>{this.buffer=e,t.onload()}),this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this._buffer.loaded&&(this.buffer=this._buffer),this.normalize=t.normalize,this.input.chain(this._convolver,this.output)}static getDefaults(){return Object.assign(Ct.getDefaults(),{normalize:!0,onload:K})}load(t){return S(this,void 0,void 0,(function*(){this.buffer=yield this._buffer.load(t)}))}get buffer(){return this._buffer.length?this._buffer:null}set buffer(t){t&&this._buffer.set(t),this._convolver.buffer&&(this.input.disconnect(),this._convolver.disconnect(),this._convolver=this.context.createConvolver(),this.input.chain(this._convolver,this.output));const e=this._buffer.get();this._convolver.buffer=e||null}get normalize(){return this._convolver.normalize}set normalize(t){this._convolver.normalize=t}dispose(){return super.dispose(),this._buffer.dispose(),this._convolver.disconnect(),this}}function qs(){return it().now()}function Is(){return it().immediate()}const Fs=it().transport;function Vs(){return it().transport}const Ns=it().destination,Ps=it().destination;function Ls(){return it().destination}const zs=it().listener;function Bs(){return it().listener}const Ws=it().draw;function Us(){return it().draw}const Gs=it();function Ys(){return tt.loaded()}const Qs=tt,Zs=$t,Xs=se}])}));
 //# sourceMappingURL=Tone.js.map
\ No newline at end of file

From 3e51205bb0bb5a5aa976243417a421527d006b1a Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 11 Oct 2020 20:19:00 +0200
Subject: [PATCH 29/85] temporary disable recordings to let new Tone work

in and out
---
 ports.js | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/ports.js b/ports.js
index cb9e0c8..f96f55d 100644
--- a/ports.js
+++ b/ports.js
@@ -10,13 +10,14 @@ if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
-    , nodeToRecord = Tone.context.createGain()
-    , recorder = new Recorder(nodeToRecord)
-    , mic = new Tone.UserMedia()
-    , micToRecord = Tone.context.createGain()
-    , micRecorder = new Recorder(micToRecord)
-Tone.Master.connect(nodeToRecord)
-mic.connect(micToRecord)
+//    , ctx = new AudioContext()
+//    , nodeToRecord = Tone.context._context.createGain()
+//    , recorder = new Recorder(nodeToRecord)
+//    , mic = new Tone.UserMedia()
+//    , micToRecord = Tone.context.createGain()
+//    , micRecorder = new Recorder(micToRecord)
+//Tone.Master.connect(nodeToRecord)
+//mic.connect(micToRecord)
 ro.observe(document.getElementById('svgResizeObserver'))
 
 let playing = {}

From c0cd51664d51af9b2b6d22d1dfd73a313b46069f Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Fri, 16 Oct 2020 15:25:12 +0200
Subject: [PATCH 30/85] Engines sends loop percents instead of loop times

JS engine can manage cases where the duration of the saved wheel differs from actual duration of the buffer
---
 src/Engine.elm | 2 +-
 src/Sound.elm  | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/Engine.elm b/src/Engine.elm
index dc1e37d..f096fa3 100644
--- a/src/Engine.elm
+++ b/src/Engine.elm
@@ -111,7 +111,7 @@ encodeWheel w hasView parentUid =
         ++ (case Wheel.getWheelContent w of
                 Content.S s ->
                     [ ( "soundName", E.string <| Sound.toString s )
-                    , ( "loopPoints", E.list E.float <| Sound.getLoopPoints s )
+                    , ( "loopPercents", E.list E.float <| Sound.getLoopPercentsList s )
                     ]
 
                 Content.M m ->
diff --git a/src/Sound.elm b/src/Sound.elm
index fa9568f..abe5522 100644
--- a/src/Sound.elm
+++ b/src/Sound.elm
@@ -47,9 +47,9 @@ fileName (S { path }) =
                             String.split "/" path
 
 
-getLoopPoints : Sound -> List Float
-getLoopPoints (S { startPercent, endPercent, duration }) =
-    [ startPercent * duration, endPercent * duration ]
+getLoopPercentsList : Sound -> List Float
+getLoopPercentsList (S { startPercent, endPercent }) =
+    [ startPercent, endPercent ]
 
 
 getLoopPercents : Sound -> ( Float, Float )

From b2cde867a987341f7b0c1e808c1b5736aee6cf45 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Fri, 16 Oct 2020 15:38:13 +0200
Subject: [PATCH 31/85] Changed Tone buffers into WebAudio buffers

---
 ports.js | 22 +++++++++++++++++-----
 1 file changed, 17 insertions(+), 5 deletions(-)

diff --git a/ports.js b/ports.js
index f96f55d..9a32dd7 100644
--- a/ports.js
+++ b/ports.js
@@ -1,6 +1,6 @@
 const app = Elm.Main.init({flags : {width : window.innerWidth, height : window.innerHeight}})
 
-if (app.ports.loadSound) app.ports.loadSound.subscribe(createBuffer)
+if (app.ports.loadSound) app.ports.loadSound.subscribe(loadSound)
 if (app.ports.toEngine) app.ports.toEngine.subscribe(engine)
 if (app.ports.toggleRecord) app.ports.toggleRecord.subscribe(toggleRecord)
 if (app.ports.requestSoundDraw) app.ports.requestSoundDraw.subscribe(drawSound)
@@ -10,6 +10,8 @@ if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
+    , ctx = new AudioContext()
+ctx.suspend()
 //    , ctx = new AudioContext()
 //    , nodeToRecord = Tone.context._context.createGain()
 //    , recorder = new Recorder(nodeToRecord)
@@ -30,19 +32,29 @@ function sendSize(entries) {
 
 function drawSound(soundName) {
   if (buffers[soundName]) {
-    drawSamples(Array.from(buffers[soundName].getChannelData()))
+    drawSamples(Array.from(buffers[soundName].getChannelData(0))) // TODO mix channels ?
     app.ports.soundDrawn.send(soundName)
   } else console.log(soundName + ' isn’t loaded, cannot draw')
 }
 
-function createBuffer(soundName) {
+function loadSound(soundName) {
   if (buffers[soundName]) {
     app.ports.soundLoaded.send(soundName + ' already Loaded')
   } else {
-    buffers[soundName] = new Tone.Buffer('./sons/' + soundName, ()=>loadOk(soundName), e=>loadErr(e, soundName))
+    createBuffer(soundName).then(b => {
+      buffers[soundName] = b
+      loadOk(soundName)
+    }).catch(err => loadErr(err, soundName))
   }
 }
 
+async function createBuffer(soundName) {
+  const response = await fetch('./sons/' + soundName)
+      , arrayBuffer = await response.arrayBuffer()
+      , audioBuffer = await ctx.decodeAudioData(arrayBuffer)
+  return audioBuffer
+}
+
 function loadOk(soundName) {
   app.ports.soundLoaded.send(
   { path : soundName
@@ -83,7 +95,7 @@ function inputRec(name) {
 function cutSample(infos) {
     if (!buffers[infos.fromFileName]) {console.error(infos.fromFileName + " ain’t loaded, cannot cut");return;}
 
-    let buf = buffers[infos.fromFileName]._buffer
+    let buf = buffers[infos.fromFileName]
       , start = infos.percents[0] * buf.length - 1
       , end = infos.percents[1] * buf.length + 1
       , newBuf = new AudioBuffer(

From 8cf96657a8e91e30660083f1208fd72b4f298602 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Fri, 16 Oct 2020 15:44:54 +0200
Subject: [PATCH 32/85] WIP scheduler

Should have commited sooner
---
 scheduler.js | 283 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 283 insertions(+)
 create mode 100644 scheduler.js

diff --git a/scheduler.js b/scheduler.js
new file mode 100644
index 0000000..8401ad0
--- /dev/null
+++ b/scheduler.js
@@ -0,0 +1,283 @@
+let scheduler = {
+    interval : 20
+  , lookAhead : 100
+  , running : false
+  , intervalId : -1
+  , startTime : -1
+  
+  , getTime() {
+    if (!this.running) return -1;
+    return ctx.currentTime - this.startTime
+  }
+  , toCtxTime(t) {
+    if (!this.running) return -1;
+    return t + this.startTime
+  }
+  
+  , startThenPlay(topGears) {
+    if (this.running) this.playPause(topGears)
+    
+    else {
+      this.running = true
+
+      ctx.resume().then(() => {
+        this.startTime = ctx.currentTime
+        this.intervalId = setInterval(() => this.work(), this.interval)
+        this.work()
+        this.nextRequestId = requestAnimationFrame(() => this.draw())
+        this.playPause(topGears)
+      })
+    }
+  }
+  
+  , stop() {
+    if (!this.running) return;
+    
+    this.running = false
+    
+    for (id in this.playingTopModels) { // TODO loop also inside collars and mobiles, make a map function walking all sounds in the tree to use also in work and ?
+      let model = this.playingTopModels[id]
+      for (player of model.players) {
+        player.node.stop()
+      }
+    }
+    
+    ctx.suspend()
+    clearInterval(this.intervalId)
+    cancelAnimationFrame(this.nextRequestId)
+    this.intervalId = -1
+    this.nextRequestId = -1
+    this.startTime = -1
+    this.modelsToDraw = []
+    this.playingTopModels = {}
+  }
+  
+  
+  , playingTopModels : {}
+  , prepare(model, destination, parentRate) {
+    // TODO this is creating a new func instance for each method for each model
+    // It’s bad!! Should be in proto ?
+    model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}] // TODO should replace model.running & isPlayingAt
+    model.lastScheduledTime = 0
+    model.players = []
+    model.getPlayerIndexAt = function(now) { // TODO should be replaced by get last topTime when isPlayingAt is reworked with playPauseTimes
+      now = now || scheduler.getTime()
+      for (let i = 0 ; i < this.players.length ; i++) {
+        let pl = this.players[i]
+        if (pl.startTime <= now && now < pl.stopTime) return i;
+      }
+      return -1;
+    }
+    model.isPlayingAt = function(now) { // not same as running, this is exactly at time asked
+      return this.getPlayerIndexAt(now) != -1
+    }
+    model.freePlayer = function(startTime) {
+      this.players = this.players.filter(v => v.startTime != startTime)
+    }
+    model.running = false // not same as isPlaying, this is according to interactions (/w latency)
+    
+    if (model.soundName) {
+      model.buffer = buffers[model.soundName]
+      // TODO beware, buffer duration could differ from saved duration in Elm model (due to resampling)
+      // probably it’s preferable to use saved duration from elm
+      // but, is it compensated by downward TODO ?
+      model.bufferDuration = model.buffer.duration
+      model.loopStartDur = model.loopPercents[0] * model.bufferDuration
+      model.loopEndDur = model.loopPercents[1] * model.bufferDuration
+      model.duration = model.loopEndDur - model.loopStartDur
+      model.rate = parentRate * model.duration / model.length
+      model.offsetDur = model.startPercent * model.duration
+    }
+
+    let gain = ctx.createGain()
+    gain.connect(destination)
+    model.gainNode = gain
+    model.setVolume = v => gain.value = v
+
+    if (model.view && model.id) {
+      let el = document.getElementById(model.id)
+        , tr = svg.createSVGTransform()
+      tr.setRotate(0,0,0)
+      el.transform.baseVal.initialize(tr)
+
+      model.view = {
+          tr : tr
+        , moveTo : function (percent) {
+          this.tr.setRotate(percent * 360, 0, 0)
+        }
+      }
+      
+      this.modelsToDraw.push(model)
+    }
+    this.playingTopModels[model.id] = model
+  }
+  
+  , playPause(topGears) {
+    let t = this.getTime() + playPauseLatency
+    for (model of topGears) {
+      if (!this.playingTopModels[model.id]) this.prepare(model, masterGain, 1)
+      model = this.playingTopModels[model.id]
+
+      if (model.running) {
+        model.running = false
+        model.playPauseTimes.push({date : t, play : false})
+      } else {
+        model.running = model.drawFlag = true
+        model.playPauseTimes.push({date : t, play : true})
+      }
+    }
+  }
+  
+  , work() { // TODO presently specific to soundWheels, todo collar & mobile
+    let now = this.getTime()
+      , max = now + this.lookAhead / 1000
+    for (id in this.playingTopModels) {
+      let model = this.playingTopModels[id]
+        , ppt = model.playPauseTimes
+        , limit = Math.min(now, model.lastScheduledTime)
+//        , keepIndex = 0
+//      model.playPauseTimes = model.playPauseTimes.sort((a,b) => a.date - b.date)
+//      for (let i in model.playPauseTimes) {
+//        if (model.playPauseTimes[i].date >= limit) {
+//          keepIndex = i - 1
+//          break;
+//        }
+//      }
+//      model.playPauseTimes = model.playPauseTimes.slice(keepIndex)
+      // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
+      // This is the assumption of user play and pause
+      // collar or another source of play pause should manage their specificities
+      
+      // Clean play pause events before last
+      ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduleTime)) - 1)
+      
+      let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
+        , nextState = ppt[nextStateIndex]
+        , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
+        , scheduleTime = model.lastScheduleTime
+      if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
+        scheduleTime = nextState.date // Bring back the scheduler
+        if (!nextState.play) { // If we should’ve pause
+          // Undo scheduled plays and schedule pause for the last
+          // TODO register paused time or percent in model or nextState
+          nextState.done = true // Pause is done
+          lastState = nextState // Move state forward
+          nextState = ppt[++nextStateIndex]
+        }
+      }
+      
+//      let undoDate = 0
+//      for (let state of model.playPauseTimes) {
+//        if (undoDate) state.done = false
+//        else if (!state.done) undoDate = state.date
+//        
+//      }
+//      
+//      if (undoDate && undoDate < model.lastScheduleTime)
+//      for (let player of model.players) {
+//        // WARNING should be impossible, but if this stops
+//        if (player.startTime <= undoDate && undoDate <= player.stopTime) player.node.stop(this.getCtxTime(undoDate))
+//        else if (player.startTime > undoDate) player.node.stop()
+//      }
+//      
+//      let scheduleTime = Math.min(undoDate, model.lastScheduleTime)
+      
+      if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + scheduleTime)
+      
+//      let lastIndexPlayPause = model.playPauseTimes.length - 1
+//      while (model.playPauseTimes[lastIndexPlayPause].date > model.lastScheduledTime) lastIndexPlayPause--
+//      let lastState = model.playPauseTimes[lastIndexPlayPause]
+//        , nextState = model.playPauseTimes[lastIndexPlayPause + 1]
+      
+      for (let t = model.lastScheduledTime ; t < max ; ) {
+        if (lastState.play) { // If we’re playing
+          if (nextState && nextState.date < max) { // And should pause
+            // Schedule then pause
+          } else { // And keep playing
+            // Schedule normally
+            
+          }
+        } else { // If we’re paused
+          if (nextState && nextState.date < max) { // And should play
+            // Schedule start
+          } else { // And keep pausing
+            // Do nothing
+            t = max
+          }
+        }
+      }
+      
+      if (model.timeToStart != -1) {
+        let t = model.timeToStart // TODO What if timeToStart < now for wathever reason, it’ll make a mess ! Easily tested in debug, as time goes on when in a breakpoint
+          , duration = model.loopEndDur - model.pauseOffsetDur
+          , length = duration / model.rate
+          , stopTime = t + length
+          , player = this.schedulePlayer(t, model, model.offsetDur, duration, length)
+        model.players.push({
+            node : player
+          , startTime : t
+          , stopTime : stopTime
+          , topTime : t - (model.offsetDur / model.rate)
+        })
+        // WARNING onended is set after the call to start, so there’s a possibility that it has already ended before setting the callback, hence memory leak, but there’s probably no chance that happens
+        let closureT = t
+        player.onended = () => model.players = model.players.filter(v => v.startTime != closureT)
+        t = stopTime
+        while (t < max) {
+          let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
+          model.players.push({
+              node : player
+            , startTime : t
+            , stopTime : t + model.length
+            , topTime : t
+          })
+          // WARNING same as before, onended added after started, so eventually after ended
+          let loopClosureT = t
+          player.onended = () => model.players = model.players.filter(v => v.startTime != loopClosureT)
+          t += model.length
+        }
+        
+        model.timeToStart = -1
+      } else {}
+    }
+  }
+  , scheduleLoop(t, maxT, model) {
+    let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
+  }
+  , schedulePlayer(t, model, startOffset, duration, length) {
+    let player = ctx.createBufferSource()
+      , ctxStartTime = t + this.startTime
+      , ctxStopTime = ctxStartTime + length
+    player.buffer = model.buffer
+    player.playbackRate.value = model.rate // TODO to go realTime rate, maybe use setValueAtTime
+    player.connect(model.gainNode)
+    player.onended = () => model.freePlayer(t)
+    player.start(ctxStartTime, startOffset, duration)
+    player.stop(ctxStopTime) // TODO stop and duration in schedulePlayer do the same thing, is it good ? Does it compensate for inexact buffer.duration ? See upward
+    return player
+  }
+  
+  
+  , nextRequestId : -1
+  , modelsToDraw : []
+  
+  , draw() {
+    for (model of this.modelsToDraw) {
+      if (!model.drawFlag) return;
+      
+      let now = scheduler.getTime()
+        , cur = model.getPlayerIndexAt(now)
+        , lastTopTime = -1
+        , playing = cur != -1
+      
+      if (!playing) topTime = now - model.offsetDur / model.rate
+      else topTime = model.players[cur].topTime
+      
+      let percent = (now - topTime) / model.length
+      
+      model.view.moveTo(percent)
+      model.drawFlag = model.running || playing
+    }
+    this.nextRequestId = requestAnimationFrame(() => this.draw())
+  }
+}

From 7ee0b1a6a361a236c5fa754a07843c7b6767b856 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:22:57 +0200
Subject: [PATCH 33/85] crazy lookAhead to prevent crazy lag when interacting

---
 scheduler.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 8401ad0..6e41ab3 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -1,6 +1,6 @@
 let scheduler = {
-    interval : 20
-  , lookAhead : 100
+    interval : 50
+  , lookAhead : 2000
   , running : false
   , intervalId : -1
   , startTime : -1

From 17aad3229dd8850fe47640f42a25cbab294db589 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:24:28 +0200
Subject: [PATCH 34/85] clear intervals first when stopping

---
 scheduler.js | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 6e41ab3..8ad6b1e 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -33,6 +33,9 @@ let scheduler = {
   , stop() {
     if (!this.running) return;
     
+    clearInterval(this.intervalId)
+    cancelAnimationFrame(this.nextRequestId)
+    
     this.running = false
     
     for (id in this.playingTopModels) { // TODO loop also inside collars and mobiles, make a map function walking all sounds in the tree to use also in work and ?
@@ -43,8 +46,6 @@ let scheduler = {
     }
     
     ctx.suspend()
-    clearInterval(this.intervalId)
-    cancelAnimationFrame(this.nextRequestId)
     this.intervalId = -1
     this.nextRequestId = -1
     this.startTime = -1

From 98c5cf41472c5fd6fe7a886250e5963a34cb775c Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:24:47 +0200
Subject: [PATCH 35/85] reset rotation when stoping

---
 scheduler.js | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/scheduler.js b/scheduler.js
index 8ad6b1e..101efe8 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -45,6 +45,10 @@ let scheduler = {
       }
     }
     
+    for (model of this.modelsToDraw) {
+      model.view.moveTo(0)
+    }
+    
     ctx.suspend()
     this.intervalId = -1
     this.nextRequestId = -1

From 01ea55a426ca6b1bbf862100c81e395ad8c914cb Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:28:03 +0200
Subject: [PATCH 36/85] freaking typo

---
 scheduler.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 101efe8..b0f2062 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -154,12 +154,12 @@ let scheduler = {
       // collar or another source of play pause should manage their specificities
       
       // Clean play pause events before last
-      ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduleTime)) - 1)
+      ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduledTime)) - 1)
       
       let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
         , nextState = ppt[nextStateIndex]
         , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
-        , scheduleTime = model.lastScheduleTime
+        , scheduleTime = model.lastScheduledTime
       if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
         scheduleTime = nextState.date // Bring back the scheduler
         if (!nextState.play) { // If we should’ve pause

From 8ebbdd080fc11f5750b132dba6b9bb79126e9c46 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:29:16 +0200
Subject: [PATCH 37/85] comment out first test

---
 scheduler.js | 64 ++++++++++++++++++++++++++--------------------------
 1 file changed, 32 insertions(+), 32 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index b0f2062..ac1be42 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -212,38 +212,38 @@ let scheduler = {
         }
       }
       
-      if (model.timeToStart != -1) {
-        let t = model.timeToStart // TODO What if timeToStart < now for wathever reason, it’ll make a mess ! Easily tested in debug, as time goes on when in a breakpoint
-          , duration = model.loopEndDur - model.pauseOffsetDur
-          , length = duration / model.rate
-          , stopTime = t + length
-          , player = this.schedulePlayer(t, model, model.offsetDur, duration, length)
-        model.players.push({
-            node : player
-          , startTime : t
-          , stopTime : stopTime
-          , topTime : t - (model.offsetDur / model.rate)
-        })
-        // WARNING onended is set after the call to start, so there’s a possibility that it has already ended before setting the callback, hence memory leak, but there’s probably no chance that happens
-        let closureT = t
-        player.onended = () => model.players = model.players.filter(v => v.startTime != closureT)
-        t = stopTime
-        while (t < max) {
-          let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
-          model.players.push({
-              node : player
-            , startTime : t
-            , stopTime : t + model.length
-            , topTime : t
-          })
-          // WARNING same as before, onended added after started, so eventually after ended
-          let loopClosureT = t
-          player.onended = () => model.players = model.players.filter(v => v.startTime != loopClosureT)
-          t += model.length
-        }
-        
-        model.timeToStart = -1
-      } else {}
+//      if (model.timeToStart != -1) {
+//        let t = model.timeToStart // TODO What if timeToStart < now for wathever reason, it’ll make a mess ! Easily tested in debug, as time goes on when in a breakpoint
+//          , duration = model.loopEndDur - model.pauseOffsetDur
+//          , length = duration / model.rate
+//          , stopTime = t + length
+//          , player = this.schedulePlayer(t, model, model.offsetDur, duration, length)
+//        model.players.push({
+//            node : player
+//          , startTime : t
+//          , stopTime : stopTime
+//          , topTime : t - (model.offsetDur / model.rate)
+//        })
+//        // WARNING onended is set after the call to start, so there’s a possibility that it has already ended before setting the callback, hence memory leak, but there’s probably no chance that happens
+//        let closureT = t
+//        player.onended = () => model.players = model.players.filter(v => v.startTime != closureT)
+//        t = stopTime
+//        while (t < max) {
+//          let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
+//          model.players.push({
+//              node : player
+//            , startTime : t
+//            , stopTime : t + model.length
+//            , topTime : t
+//          })
+//          // WARNING same as before, onended added after started, so eventually after ended
+//          let loopClosureT = t
+//          player.onended = () => model.players = model.players.filter(v => v.startTime != loopClosureT)
+//          t += model.length
+//        }
+//        
+//        model.timeToStart = -1
+//      } else {}
     }
   }
   , scheduleLoop(t, maxT, model) {

From ce2d1d35a58a9626b6c721dae770f33c8b0a2eb6 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:30:01 +0200
Subject: [PATCH 38/85] basic scheduler finished

---
 scheduler.js | 78 +++++++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 65 insertions(+), 13 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index ac1be42..c8a0814 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -160,14 +160,22 @@ let scheduler = {
         , nextState = ppt[nextStateIndex]
         , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
         , scheduleTime = model.lastScheduledTime
+        , advanceState = () => {
+          nextState.done = true
+          lastState = nextState
+          nextState = ppt[++nextStateIndex]
+        }
       if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
         scheduleTime = nextState.date // Bring back the scheduler
         if (!nextState.play) { // If we should’ve pause
-          // Undo scheduled plays and schedule pause for the last
-          // TODO register paused time or percent in model or nextState
-          nextState.done = true // Pause is done
-          lastState = nextState // Move state forward
-          nextState = ppt[++nextStateIndex]
+          for (let pl of model.players) {
+            if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
+              pl.node.stop(this.toCtxTime(scheduleTime))
+              nextState.percentPaused = (scheduleTime - pl.startTime) / model.length
+            }
+            if (pl.startTime > scheduleTime) pl.node.stop()
+          }
+          advanceState()
         }
       }
       
@@ -194,23 +202,55 @@ let scheduler = {
 //      let lastState = model.playPauseTimes[lastIndexPlayPause]
 //        , nextState = model.playPauseTimes[lastIndexPlayPause + 1]
       
-      for (let t = model.lastScheduledTime ; t < max ; ) {
+      while (scheduleTime < max) {
+        
+        let t = scheduleTime
+        
         if (lastState.play) { // If we’re playing
+          
           if (nextState && nextState.date < max) { // And should pause
-            // Schedule then pause
+            
+            let newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+            
+              , startTime = newPlayers[newPlayers.length - 1].stopTime
+              , length = nextState.date - startTime
+              , duration = length * model.rate
+            
+            newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+            
+            model.players = model.players.concat(newPlayers)
+            
+            nextState.percentPaused = length / model.length
+            
+            scheduleTime = nextState.date
+            
+            advanceState()
+            
           } else { // And keep playing
-            // Schedule normally
+            
+            let newPlayers = this.scheduleLoop(t, max, model)
+            model.players = model.players.concat(newPlayers)
+            scheduleTime = model.players[model.players.length - 1].stopTime
             
           }
+          
         } else { // If we’re paused
+          
           if (nextState && nextState.date < max) { // And should play
-            // Schedule start
+            
+            let newPlayer = this.scheduleStart(t, model, lastState.percentPaused * model.duration + model.loopStartDur)
+            model.players.push(newPlayer)
+            scheduleTime = newPlayer.stopTime
+            advanceState()
+            
           } else { // And keep pausing
-            // Do nothing
-            t = max
+            
+            scheduleTime = max
+            
           }
         }
       }
+      model.lastScheduledTime = scheduleTime
       
 //      if (model.timeToStart != -1) {
 //        let t = model.timeToStart // TODO What if timeToStart < now for wathever reason, it’ll make a mess ! Easily tested in debug, as time goes on when in a breakpoint
@@ -247,7 +287,14 @@ let scheduler = {
     }
   }
   , scheduleLoop(t, maxT, model) {
-    let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
+    return [
+      this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
+    ].concat(t + model.length >= maxT ? [] : this.scheduleLoop(t + model.length, maxT, model))
+  }
+  , scheduleStart(t, model, offsetDur) {
+    let dur = model.loopEndDur - offsetDur
+      , len = dur / model.rate
+    return this.schedulePlayer(t, model, offsetDur, dur, len)
   }
   , schedulePlayer(t, model, startOffset, duration, length) {
     let player = ctx.createBufferSource()
@@ -259,7 +306,12 @@ let scheduler = {
     player.onended = () => model.freePlayer(t)
     player.start(ctxStartTime, startOffset, duration)
     player.stop(ctxStopTime) // TODO stop and duration in schedulePlayer do the same thing, is it good ? Does it compensate for inexact buffer.duration ? See upward
-    return player
+    return {
+        node : player
+      , startTime : t
+      , stopTime : t + length
+      , startPosDur : startOffset
+    }
   }
   
   

From 7910a0144bc75512dd14819d2583ddc962a8856a Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:30:25 +0200
Subject: [PATCH 39/85] WIP update draw to test

---
 scheduler.js | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index c8a0814..77dd013 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -325,15 +325,17 @@ let scheduler = {
       let now = scheduler.getTime()
         , cur = model.getPlayerIndexAt(now)
         , lastTopTime = -1
-        , playing = cur != -1
+        , player = model.players[cur]
       
-      if (!playing) topTime = now - model.offsetDur / model.rate
-      else topTime = model.players[cur].topTime
+//      if (!player) lastTopTime = now - model.offsetDur / model.rate // TODO faux, voir percentPaused mtn
+//      else lastTopTime = model.players[cur].topTime
       
-      let percent = (now - topTime) / model.length
+//      let percent = (now - lastTopTime) / model.length
+      
+      let percent = player ? (now - player.startTime) / model.length + (player.startPosDur - model.offsetDur) / model.duration : 0
       
       model.view.moveTo(percent)
-      model.drawFlag = model.running || playing
+      model.drawFlag = model.running || cur != -1
     }
     this.nextRequestId = requestAnimationFrame(() => this.draw())
   }

From 036da8a703efb9139101fd982dc9bfd5e11b89dc Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:31:24 +0200
Subject: [PATCH 40/85] temporarily deactivate recorders

---
 ports.js | 34 +++++++++++++++++-----------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/ports.js b/ports.js
index 9a32dd7..bb0e4dc 100644
--- a/ports.js
+++ b/ports.js
@@ -5,8 +5,8 @@ if (app.ports.toEngine) app.ports.toEngine.subscribe(engine)
 if (app.ports.toggleRecord) app.ports.toggleRecord.subscribe(toggleRecord)
 if (app.ports.requestSoundDraw) app.ports.requestSoundDraw.subscribe(drawSound)
 if (app.ports.requestCutSample) app.ports.requestCutSample.subscribe(cutSample)
-if (app.ports.openMic) app.ports.openMic.subscribe(openMic)
-if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
+//if (app.ports.openMic) app.ports.openMic.subscribe(openMic)
+//if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
@@ -76,21 +76,21 @@ function toggleRecord(bool) {
     }
 }
 
-function openMic() {
-  Tone.start()
-  mic.open().then(
-    () => app.ports.micOpened.send(null)
-  ).catch(console.error)
-}
-
-function inputRec(name) {
-  if (name) {
-    micRecorder.stop()
-    micRecorder.exportWAV(bl => app.ports.gotNewSample.send(new File([bl], name + ".wav", {type: "audio/wav"})))
-    micRecorder.clear()
-  } else if (mic.state == "started") micRecorder.record()
-  else console.error("won’t record mic if it ain’t opened !")
-}
+//function openMic() {
+//  Tone.start()
+//  mic.open().then(
+//    () => app.ports.micOpened.send(null)
+//  ).catch(console.error)
+//}
+//
+//function inputRec(name) {
+//  if (name) {
+//    micRecorder.stop()
+//    micRecorder.exportWAV(bl => app.ports.gotNewSample.send(new File([bl], name + ".wav", {type: "audio/wav"})))
+//    micRecorder.clear()
+//  } else if (mic.state == "started") micRecorder.record()
+//  else console.error("won’t record mic if it ain’t opened !")
+//}
 
 function cutSample(infos) {
     if (!buffers[infos.fromFileName]) {console.error(infos.fromFileName + " ain’t loaded, cannot cut");return;}

From 28567c9ca727fae1e655f69e4a8048fdb51576fc Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:33:25 +0200
Subject: [PATCH 41/85] minimum integation for testing

---
 ports.js | 21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)

diff --git a/ports.js b/ports.js
index bb0e4dc..9019133 100644
--- a/ports.js
+++ b/ports.js
@@ -22,7 +22,7 @@ ctx.suspend()
 //mic.connect(micToRecord)
 ro.observe(document.getElementById('svgResizeObserver'))
 
-let playing = {}
+//let playing = {}
 
 let deb = null
 
@@ -112,18 +112,23 @@ function cutSample(infos) {
     app.ports.gotNewSample.send(new File([audioBufferToWav(newBuf)], infos.newFileName + ".wav", {type: "audio/wav"}))
 }
 
-function engine(o) {
+let playPauseLatency = .1
+  , masterGain = ctx.createGain()
+masterGain.connect(ctx.destination)
+function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
   let model = null
   switch ( o.action ) {
     case "stopReset" :
-        for ( id in playing) {
-            stop(playing[id])
-        }
-        playing = {}
+        scheduler.stop()
+//        for ( id in playing) {
+//            stop(playing[id])
+//        }
+//        playing = {}
         break;
     case "playPause" :
-        let t = Tone.now()+0.1
-        o.gears.map(g=>playPause(g,t))
+        scheduler.startThenPlay(o.gears)
+//        let t = scheduler.getTime() + playPauseLatency
+//        o.gears.map(g => scheduler.playPause(g, t))
         break;
     case "mute" :
         model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])

From 84e355e80c32b9564ac5b1c33aad823d2b09b48f Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:34:33 +0200
Subject: [PATCH 42/85] better naming in objects from elm engine to js engine

duration is content, length is wheel
---
 src/Engine.elm | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/Engine.elm b/src/Engine.elm
index f096fa3..867a9e3 100644
--- a/src/Engine.elm
+++ b/src/Engine.elm
@@ -149,7 +149,7 @@ encodeGear hasView parentUid coll id =
 encodeMobile : Mobeel -> Bool -> String -> E.Value
 encodeMobile { motor, gears } hasView parentUid =
     E.object
-        [ ( "length", E.float <| Harmo.getLengthId motor gears )
+        [ ( "duration", E.float <| Harmo.getLengthId motor gears )
         , ( "gears", E.list (encodeGear hasView parentUid gears) <| Motor.getMotored motor gears )
         ]
 
@@ -157,7 +157,7 @@ encodeMobile { motor, gears } hasView parentUid =
 encodeCollar : Colleer -> Bool -> String -> E.Value
 encodeCollar c hasView parentUid =
     E.object
-        [ ( "length", E.float <| Collar.getCumulLengthAt c.matrice c )
+        [ ( "duration", E.float <| Collar.getCumulLengthAt c.matrice c )
         , ( "loopStart", E.float c.loop )
         , ( "beads", E.list (encodeBead hasView parentUid) <| List.indexedMap (\i el -> ( i, el )) <| Collar.getBeads c )
         ]

From d500203e17ef607dc0d5a1d48e1b89180d268f16 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 02:35:09 +0200
Subject: [PATCH 43/85] include scheduler instead of playable

---
 ports.html | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ports.html b/ports.html
index 0626a68..cc39cf9 100644
--- a/ports.html
+++ b/ports.html
@@ -14,7 +14,7 @@
     
     
     
-    
+    
     
     
   

From 5f00c48057d2c41928b041e1d4769ee81ae9f176 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 13:41:17 +0200
Subject: [PATCH 44/85] volume and mute done

---
 ports.js     | 20 ++++++++++++++------
 scheduler.js |  5 ++++-
 2 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/ports.js b/ports.js
index 9019133..7a6fc35 100644
--- a/ports.js
+++ b/ports.js
@@ -131,17 +131,25 @@ function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
 //        o.gears.map(g => scheduler.playPause(g, t))
         break;
     case "mute" :
-        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
+//        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
+        model = scheduler.playingTopModels[o.id] // TODO beads inside collars
         if (model) {
-            model.mute = o.value
-            setVolume(model)
+          model.mute = o.value
+          model.updateVolume()
+//            if (o.value) {
+//              model.setVolume(0)
+//            } else {
+//              model.setVolume(model.volume)
+//            }
         }
         break;
     case "volume" :
-        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
+//        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
+        model = scheduler.playingTopModels[o.id] // TODO beads inside collars
         if (model) {
-            model.volume = o.value
-            setVolume(model)
+          model.volume = o.value
+          model.updateVolume()
+//            if (!model.mute) model.setVolume(o.value)
         }
         break;
     }
diff --git a/scheduler.js b/scheduler.js
index 77dd013..fb98bd7 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -97,7 +97,10 @@ let scheduler = {
     let gain = ctx.createGain()
     gain.connect(destination)
     model.gainNode = gain
-    model.setVolume = v => gain.value = v
+    model.updateVolume = function() {
+      this.gainNode.gain.value = this.mute ? 0 : this.volume
+    } // TODO volume should rather be in dB
+    model.updateVolume()
 
     if (model.view && model.id) {
       let el = document.getElementById(model.id)

From 53dc56e0db20cc5172a7ea421362a5e0ad8d82c5 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 15:38:22 +0200
Subject: [PATCH 45/85] fix forgot to declare loop variable locally

---
 scheduler.js | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index fb98bd7..f3cee9b 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -38,14 +38,14 @@ let scheduler = {
     
     this.running = false
     
-    for (id in this.playingTopModels) { // TODO loop also inside collars and mobiles, make a map function walking all sounds in the tree to use also in work and ?
+    for (let id in this.playingTopModels) { // TODO loop also inside collars and mobiles, make a map function walking all sounds in the tree to use also in work and ?
       let model = this.playingTopModels[id]
-      for (player of model.players) {
+      for (let player of model.players) {
         player.node.stop()
       }
     }
     
-    for (model of this.modelsToDraw) {
+    for (let model of this.modelsToDraw) {
       model.view.moveTo(0)
     }
     
@@ -122,7 +122,7 @@ let scheduler = {
   
   , playPause(topGears) {
     let t = this.getTime() + playPauseLatency
-    for (model of topGears) {
+    for (let model of topGears) {
       if (!this.playingTopModels[model.id]) this.prepare(model, masterGain, 1)
       model = this.playingTopModels[model.id]
 
@@ -139,7 +139,7 @@ let scheduler = {
   , work() { // TODO presently specific to soundWheels, todo collar & mobile
     let now = this.getTime()
       , max = now + this.lookAhead / 1000
-    for (id in this.playingTopModels) {
+    for (let id in this.playingTopModels) {
       let model = this.playingTopModels[id]
         , ppt = model.playPauseTimes
         , limit = Math.min(now, model.lastScheduledTime)
@@ -322,7 +322,7 @@ let scheduler = {
   , modelsToDraw : []
   
   , draw() {
-    for (model of this.modelsToDraw) {
+    for (let model of this.modelsToDraw) {
       if (!model.drawFlag) return;
       
       let now = scheduler.getTime()

From 62813768def96e73ef2bdfc7508fe21e17acb2bc Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 15:47:47 +0200
Subject: [PATCH 46/85] use lastPlayPause in draw

replaces :
model.running
model.getPlayerIndexAt
model.isPlayingAt
player.startPosDur
model.drawFlag
---
 scheduler.js | 59 +++++++++++++++++++++++++++++-----------------------
 1 file changed, 33 insertions(+), 26 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index f3cee9b..a6f1ccf 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -62,24 +62,24 @@ let scheduler = {
   , prepare(model, destination, parentRate) {
     // TODO this is creating a new func instance for each method for each model
     // It’s bad!! Should be in proto ?
-    model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}] // TODO should replace model.running & isPlayingAt
+    model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}]
     model.lastScheduledTime = 0
     model.players = []
-    model.getPlayerIndexAt = function(now) { // TODO should be replaced by get last topTime when isPlayingAt is reworked with playPauseTimes
-      now = now || scheduler.getTime()
-      for (let i = 0 ; i < this.players.length ; i++) {
-        let pl = this.players[i]
-        if (pl.startTime <= now && now < pl.stopTime) return i;
-      }
-      return -1;
-    }
-    model.isPlayingAt = function(now) { // not same as running, this is exactly at time asked
-      return this.getPlayerIndexAt(now) != -1
+//    model.getPlayerIndexAt = function(now) {
+//      now = now || scheduler.getTime()
+//      for (let i = 0 ; i < this.players.length ; i++) {
+//        let pl = this.players[i]
+//        if (pl.startTime <= now && now < pl.stopTime) return i;
+//      }
+//      return -1;
+//    }
+    model.lastPlayPauseAt = function(now) {
+      return this.playPauseTimes.slice().reverse().find(v => v.date <= now)
     }
     model.freePlayer = function(startTime) {
       this.players = this.players.filter(v => v.startTime != startTime)
     }
-    model.running = false // not same as isPlaying, this is according to interactions (/w latency)
+//    model.running = false // not same as isPlaying, this is according to interactions (/w latency)
     
     if (model.soundName) {
       model.buffer = buffers[model.soundName]
@@ -126,11 +126,11 @@ let scheduler = {
       if (!this.playingTopModels[model.id]) this.prepare(model, masterGain, 1)
       model = this.playingTopModels[model.id]
 
-      if (model.running) {
-        model.running = false
+      let running = model.playPauseTimes[model.playPauseTimes.length - 1].play
+      
+      if (running) {
         model.playPauseTimes.push({date : t, play : false})
       } else {
-        model.running = model.drawFlag = true
         model.playPauseTimes.push({date : t, play : true})
       }
     }
@@ -244,6 +244,7 @@ let scheduler = {
             let newPlayer = this.scheduleStart(t, model, lastState.percentPaused * model.duration + model.loopStartDur)
             model.players.push(newPlayer)
             scheduleTime = newPlayer.stopTime
+            nextState.percentStarted = lastState.percentPaused
             advanceState()
             
           } else { // And keep pausing
@@ -313,7 +314,7 @@ let scheduler = {
         node : player
       , startTime : t
       , stopTime : t + length
-      , startPosDur : startOffset
+//      , startPosDur : startOffset
     }
   }
   
@@ -322,23 +323,29 @@ let scheduler = {
   , modelsToDraw : []
   
   , draw() {
+    // TODO keeps drawing event when paused. is it bad ?
+    // TODO percent keeps growing, will it overflow ?
     for (let model of this.modelsToDraw) {
-      if (!model.drawFlag) return;
-      
       let now = scheduler.getTime()
-        , cur = model.getPlayerIndexAt(now)
-        , lastTopTime = -1
-        , player = model.players[cur]
+        , lastState = model.lastPlayPauseAt(now)
       
-//      if (!player) lastTopTime = now - model.offsetDur / model.rate // TODO faux, voir percentPaused mtn
-//      else lastTopTime = model.players[cur].topTime
+      let percent = lastState.play ? lastState.percentStarted + (now - lastState.date) / model.length : lastState.percentPaused
       
-//      let percent = (now - lastTopTime) / model.length
       
-      let percent = player ? (now - player.startTime) / model.length + (player.startPosDur - model.offsetDur) / model.duration : 0
+      
+      
+//        , cur = model.getPlayerIndexAt(now)
+//        , player = model.players[cur]
+//      
+////      if (!player) lastTopTime = now - model.offsetDur / model.rate // TODO faux, voir percentPaused mtn
+////      else lastTopTime = model.players[cur].topTime
+//      
+////      let percent = (now - lastTopTime) / model.length
+//      
+//      let percent = player ? (now - player.startTime) / model.length + (player.startPosDur - model.offsetDur) / model.duration : 0
       
       model.view.moveTo(percent)
-      model.drawFlag = model.running || cur != -1
+//      model.drawFlag = model.running || cur != -1
     }
     this.nextRequestId = requestAnimationFrame(() => this.draw())
   }

From 5cd5d50e03b4374851ae8d2fb3818f094d6bbee0 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 15:53:50 +0200
Subject: [PATCH 47/85] clean

---
 scheduler.js | 96 +++-------------------------------------------------
 1 file changed, 5 insertions(+), 91 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index a6f1ccf..c98b82f 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -65,27 +65,18 @@ let scheduler = {
     model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}]
     model.lastScheduledTime = 0
     model.players = []
-//    model.getPlayerIndexAt = function(now) {
-//      now = now || scheduler.getTime()
-//      for (let i = 0 ; i < this.players.length ; i++) {
-//        let pl = this.players[i]
-//        if (pl.startTime <= now && now < pl.stopTime) return i;
-//      }
-//      return -1;
-//    }
     model.lastPlayPauseAt = function(now) {
       return this.playPauseTimes.slice().reverse().find(v => v.date <= now)
     }
     model.freePlayer = function(startTime) {
       this.players = this.players.filter(v => v.startTime != startTime)
     }
-//    model.running = false // not same as isPlaying, this is according to interactions (/w latency)
     
     if (model.soundName) {
       model.buffer = buffers[model.soundName]
       // TODO beware, buffer duration could differ from saved duration in Elm model (due to resampling)
       // probably it’s preferable to use saved duration from elm
-      // but, is it compensated by downward TODO ?
+      // but, is it compensated by downward TODO ? (in schedulePlayer)
       model.bufferDuration = model.buffer.duration
       model.loopStartDur = model.loopPercents[0] * model.bufferDuration
       model.loopEndDur = model.loopPercents[1] * model.bufferDuration
@@ -142,16 +133,6 @@ let scheduler = {
     for (let id in this.playingTopModels) {
       let model = this.playingTopModels[id]
         , ppt = model.playPauseTimes
-        , limit = Math.min(now, model.lastScheduledTime)
-//        , keepIndex = 0
-//      model.playPauseTimes = model.playPauseTimes.sort((a,b) => a.date - b.date)
-//      for (let i in model.playPauseTimes) {
-//        if (model.playPauseTimes[i].date >= limit) {
-//          keepIndex = i - 1
-//          break;
-//        }
-//      }
-//      model.playPauseTimes = model.playPauseTimes.slice(keepIndex)
       // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
       // This is the assumption of user play and pause
       // collar or another source of play pause should manage their specificities
@@ -182,29 +163,8 @@ let scheduler = {
         }
       }
       
-//      let undoDate = 0
-//      for (let state of model.playPauseTimes) {
-//        if (undoDate) state.done = false
-//        else if (!state.done) undoDate = state.date
-//        
-//      }
-//      
-//      if (undoDate && undoDate < model.lastScheduleTime)
-//      for (let player of model.players) {
-//        // WARNING should be impossible, but if this stops
-//        if (player.startTime <= undoDate && undoDate <= player.stopTime) player.node.stop(this.getCtxTime(undoDate))
-//        else if (player.startTime > undoDate) player.node.stop()
-//      }
-//      
-//      let scheduleTime = Math.min(undoDate, model.lastScheduleTime)
-      
       if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + scheduleTime)
       
-//      let lastIndexPlayPause = model.playPauseTimes.length - 1
-//      while (model.playPauseTimes[lastIndexPlayPause].date > model.lastScheduledTime) lastIndexPlayPause--
-//      let lastState = model.playPauseTimes[lastIndexPlayPause]
-//        , nextState = model.playPauseTimes[lastIndexPlayPause + 1]
-      
       while (scheduleTime < max) {
         
         let t = scheduleTime
@@ -255,39 +215,6 @@ let scheduler = {
         }
       }
       model.lastScheduledTime = scheduleTime
-      
-//      if (model.timeToStart != -1) {
-//        let t = model.timeToStart // TODO What if timeToStart < now for wathever reason, it’ll make a mess ! Easily tested in debug, as time goes on when in a breakpoint
-//          , duration = model.loopEndDur - model.pauseOffsetDur
-//          , length = duration / model.rate
-//          , stopTime = t + length
-//          , player = this.schedulePlayer(t, model, model.offsetDur, duration, length)
-//        model.players.push({
-//            node : player
-//          , startTime : t
-//          , stopTime : stopTime
-//          , topTime : t - (model.offsetDur / model.rate)
-//        })
-//        // WARNING onended is set after the call to start, so there’s a possibility that it has already ended before setting the callback, hence memory leak, but there’s probably no chance that happens
-//        let closureT = t
-//        player.onended = () => model.players = model.players.filter(v => v.startTime != closureT)
-//        t = stopTime
-//        while (t < max) {
-//          let player = this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)
-//          model.players.push({
-//              node : player
-//            , startTime : t
-//            , stopTime : t + model.length
-//            , topTime : t
-//          })
-//          // WARNING same as before, onended added after started, so eventually after ended
-//          let loopClosureT = t
-//          player.onended = () => model.players = model.players.filter(v => v.startTime != loopClosureT)
-//          t += model.length
-//        }
-//        
-//        model.timeToStart = -1
-//      } else {}
     }
   }
   , scheduleLoop(t, maxT, model) {
@@ -309,12 +236,11 @@ let scheduler = {
     player.connect(model.gainNode)
     player.onended = () => model.freePlayer(t)
     player.start(ctxStartTime, startOffset, duration)
-    player.stop(ctxStopTime) // TODO stop and duration in schedulePlayer do the same thing, is it good ? Does it compensate for inexact buffer.duration ? See upward
+    player.stop(ctxStopTime) // TODO stop and duration in schedulePlayer do the same thing, is it good ? Does it compensate for inexact buffer.duration ? See upward in prepare sound
     return {
         node : player
       , startTime : t
       , stopTime : t + length
-//      , startPosDur : startOffset
     }
   }
   
@@ -329,23 +255,11 @@ let scheduler = {
       let now = scheduler.getTime()
         , lastState = model.lastPlayPauseAt(now)
       
-      let percent = lastState.play ? lastState.percentStarted + (now - lastState.date) / model.length : lastState.percentPaused
-      
-      
-      
-      
-//        , cur = model.getPlayerIndexAt(now)
-//        , player = model.players[cur]
-//      
-////      if (!player) lastTopTime = now - model.offsetDur / model.rate // TODO faux, voir percentPaused mtn
-////      else lastTopTime = model.players[cur].topTime
-//      
-////      let percent = (now - lastTopTime) / model.length
-//      
-//      let percent = player ? (now - player.startTime) / model.length + (player.startPosDur - model.offsetDur) / model.duration : 0
+      let percent = lastState.play ?
+          lastState.percentStarted + (now - lastState.date) / model.length :
+          lastState.percentPaused
       
       model.view.moveTo(percent)
-//      model.drawFlag = model.running || cur != -1
     }
     this.nextRequestId = requestAnimationFrame(() => this.draw())
   }

From 0a9d366030e6605737fcd62e4fb6f666d19e4233 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 16:39:43 +0200
Subject: [PATCH 48/85] prepare collar

---
 scheduler.js | 31 +++++++++++++++++++------------
 1 file changed, 19 insertions(+), 12 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index c98b82f..a7bd41a 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -64,15 +64,23 @@ let scheduler = {
     // It’s bad!! Should be in proto ?
     model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}]
     model.lastScheduledTime = 0
-    model.players = []
     model.lastPlayPauseAt = function(now) {
       return this.playPauseTimes.slice().reverse().find(v => v.date <= now)
     }
-    model.freePlayer = function(startTime) {
-      this.players = this.players.filter(v => v.startTime != startTime)
-    }
+
+    let gain = ctx.createGain()
+    gain.connect(destination)
+    model.gainNode = gain
+    model.updateVolume = function() {
+      this.gainNode.gain.value = this.mute ? 0 : this.volume
+    } // TODO volume should rather be in dB
+    model.updateVolume()
     
     if (model.soundName) {
+      model.players = []
+      model.freePlayer = function(startTime) {
+        this.players = this.players.filter(v => v.startTime != startTime)
+      }
       model.buffer = buffers[model.soundName]
       // TODO beware, buffer duration could differ from saved duration in Elm model (due to resampling)
       // probably it’s preferable to use saved duration from elm
@@ -84,14 +92,13 @@ let scheduler = {
       model.rate = parentRate * model.duration / model.length
       model.offsetDur = model.startPercent * model.duration
     }
-
-    let gain = ctx.createGain()
-    gain.connect(destination)
-    model.gainNode = gain
-    model.updateVolume = function() {
-      this.gainNode.gain.value = this.mute ? 0 : this.volume
-    } // TODO volume should rather be in dB
-    model.updateVolume()
+    
+    if (model.collar) {
+      model.duration = model.collar.length
+      model.rate = parentRate * model.duration / model.length
+      model.offsetDur = model.startPercent * model.duration
+      model.subWheels = model.collar.beads.map(v => this.prepare(v, model.gainNode, model.rate))
+    }
 
     if (model.view && model.id) {
       let el = document.getElementById(model.id)

From 36778e845bf9b1e3b4542be57dfa0c010e71ae66 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 16:40:09 +0200
Subject: [PATCH 49/85] layout work function for collar

---
 scheduler.js | 74 ++++++++++++++++++++++++++++++++++++----------------
 1 file changed, 52 insertions(+), 22 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index a7bd41a..49afcc9 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -158,14 +158,23 @@ let scheduler = {
         }
       if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
         scheduleTime = nextState.date // Bring back the scheduler
+        
         if (!nextState.play) { // If we should’ve pause
-          for (let pl of model.players) {
-            if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
-              pl.node.stop(this.toCtxTime(scheduleTime))
-              nextState.percentPaused = (scheduleTime - pl.startTime) / model.length
+          
+          if (model.soundName) { // If sound, undo players
+            for (let pl of model.players) {
+              if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
+                pl.node.stop(this.toCtxTime(scheduleTime))
+                nextState.percentPaused = (scheduleTime - pl.startTime) / model.length
+              }
+              if (pl.startTime > scheduleTime) pl.node.stop()
             }
-            if (pl.startTime > scheduleTime) pl.node.stop()
           }
+          
+          if (model.collar) { // If collar, undo playPause of subWheels
+            // TODO collar undo
+          }
+          
           advanceState()
         }
       }
@@ -180,17 +189,23 @@ let scheduler = {
           
           if (nextState && nextState.date < max) { // And should pause
             
-            let newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
-            
-              , startTime = newPlayers[newPlayers.length - 1].stopTime
-              , length = nextState.date - startTime
-              , duration = length * model.rate
-            
-            newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
-            
-            model.players = model.players.concat(newPlayers)
+            if (model.soundName) {
+              let newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+
+                , startTime = newPlayers[newPlayers.length - 1].stopTime
+                , length = nextState.date - startTime
+                , duration = length * model.rate
+
+              newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+
+              model.players = model.players.concat(newPlayers)
+
+              nextState.percentPaused = length / model.length
+            }
             
-            nextState.percentPaused = length / model.length
+            if (model.collar) {
+              // TODO collar pause
+            }
             
             scheduleTime = nextState.date
             
@@ -198,9 +213,15 @@ let scheduler = {
             
           } else { // And keep playing
             
-            let newPlayers = this.scheduleLoop(t, max, model)
-            model.players = model.players.concat(newPlayers)
-            scheduleTime = model.players[model.players.length - 1].stopTime
+            if (model.soundName) {
+              let newPlayers = this.scheduleLoop(t, max, model)
+              model.players = model.players.concat(newPlayers)
+              scheduleTime = model.players[model.players.length - 1].stopTime
+            }
+            
+            if (model.collar) {
+              // TODO collar play
+            }
             
           }
           
@@ -208,11 +229,20 @@ let scheduler = {
           
           if (nextState && nextState.date < max) { // And should play
             
-            let newPlayer = this.scheduleStart(t, model, lastState.percentPaused * model.duration + model.loopStartDur)
-            model.players.push(newPlayer)
-            scheduleTime = newPlayer.stopTime
-            nextState.percentStarted = lastState.percentPaused
+            if (model.soundName) {
+              let offsetDur = lastState.percentPaused * model.duration + model.loopStartDur
+                , newPlayer = this.scheduleStart(t, model, offsetDur)
+              model.players.push(newPlayer)
+              scheduleTime = newPlayer.stopTime
+              nextState.percentStarted = lastState.percentPaused
+            }
+            
+            if (model.collar) {
+              // TODO collar start
+            }
+            
             advanceState()
+
             
           } else { // And keep pausing
             

From 4f167775290b68fadae7d46a6905278f64bb6721 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 17 Oct 2020 17:48:25 +0200
Subject: [PATCH 50/85] fix startOffset

clean model.offsetDur
use model.startPercent instead
---
 scheduler.js | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 49afcc9..89d6075 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -90,13 +90,11 @@ let scheduler = {
       model.loopEndDur = model.loopPercents[1] * model.bufferDuration
       model.duration = model.loopEndDur - model.loopStartDur
       model.rate = parentRate * model.duration / model.length
-      model.offsetDur = model.startPercent * model.duration
     }
     
     if (model.collar) {
       model.duration = model.collar.length
       model.rate = parentRate * model.duration / model.length
-      model.offsetDur = model.startPercent * model.duration
       model.subWheels = model.collar.beads.map(v => this.prepare(v, model.gainNode, model.rate))
     }
 
@@ -165,7 +163,7 @@ let scheduler = {
             for (let pl of model.players) {
               if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
                 pl.node.stop(this.toCtxTime(scheduleTime))
-                nextState.percentPaused = (scheduleTime - pl.startTime) / model.length
+                nextState.percentPaused = clampPercent((scheduleTime - pl.startTime) / model.length - model.startPercent)
               }
               if (pl.startTime > scheduleTime) pl.node.stop()
             }
@@ -200,7 +198,7 @@ let scheduler = {
 
               model.players = model.players.concat(newPlayers)
 
-              nextState.percentPaused = length / model.length
+              nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
             }
             
             if (model.collar) {
@@ -230,7 +228,8 @@ let scheduler = {
           if (nextState && nextState.date < max) { // And should play
             
             if (model.soundName) {
-              let offsetDur = lastState.percentPaused * model.duration + model.loopStartDur
+              let soundPercent = clampPercent(lastState.percentPaused + model.startPercent)
+                , offsetDur = soundPercent * model.duration + model.loopStartDur
                 , newPlayer = this.scheduleStart(t, model, offsetDur)
               model.players.push(newPlayer)
               scheduleTime = newPlayer.stopTime
@@ -292,12 +291,16 @@ let scheduler = {
       let now = scheduler.getTime()
         , lastState = model.lastPlayPauseAt(now)
       
-      let percent = lastState.play ?
+      let percent = clampPercent(lastState.play ?
           lastState.percentStarted + (now - lastState.date) / model.length :
-          lastState.percentPaused
+          lastState.percentPaused)
       
       model.view.moveTo(percent)
     }
     this.nextRequestId = requestAnimationFrame(() => this.draw())
   }
 }
+
+function clampPercent(p) {
+  return p - Math.floor(p)
+}

From 551be3854de6e70fc8df001dadd0380d3222afe0 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 11:44:05 +0200
Subject: [PATCH 51/85] length is now the real time length

---
 scheduler.js | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/scheduler.js b/scheduler.js
index 89d6075..d25ade9 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -97,6 +97,10 @@ let scheduler = {
       model.rate = parentRate * model.duration / model.length
       model.subWheels = model.collar.beads.map(v => this.prepare(v, model.gainNode, model.rate))
     }
+    
+    model.realLength = model.length / parentRate
+    model.lengthBeforeParentRate = model.length
+    model.length = model.realLength
 
     if (model.view && model.id) {
       let el = document.getElementById(model.id)

From 86a8e9fef00f7f5384555cf3b6c88ded9ae81578 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 11:53:40 +0200
Subject: [PATCH 52/85] =?UTF-8?q?prepare=20and=20schedule=20don=E2=80=99t?=
 =?UTF-8?q?=20use=20playingTopModels?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

because subWheels
---
 scheduler.js | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index d25ade9..58241d4 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -117,13 +117,14 @@ let scheduler = {
       
       this.modelsToDraw.push(model)
     }
-    this.playingTopModels[model.id] = model
+    return model
   }
   
   , playPause(topGears) {
     let t = this.getTime() + playPauseLatency
     for (let model of topGears) {
-      if (!this.playingTopModels[model.id]) this.prepare(model, masterGain, 1)
+      if (!this.playingTopModels[model.id])
+        this.playingTopModels[model.id] = this.prepare(model, masterGain, 1)
       model = this.playingTopModels[model.id]
 
       let running = model.playPauseTimes[model.playPauseTimes.length - 1].play
@@ -140,8 +141,12 @@ let scheduler = {
     let now = this.getTime()
       , max = now + this.lookAhead / 1000
     for (let id in this.playingTopModels) {
-      let model = this.playingTopModels[id]
-        , ppt = model.playPauseTimes
+      this.schedule(this.playingTopModels[id], now, max)
+    }
+  }
+      
+  , schedule(model, now, max) {
+      let ppt = model.playPauseTimes
       // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
       // This is the assumption of user play and pause
       // collar or another source of play pause should manage their specificities

From 5783256d2da70f38128511fa494e6af967b760f9 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 11:54:18 +0200
Subject: [PATCH 53/85] prepare collar

---
 scheduler.js | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/scheduler.js b/scheduler.js
index 58241d4..0a3cedf 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -93,7 +93,16 @@ let scheduler = {
     }
     
     if (model.collar) {
-      model.duration = model.collar.length
+      // WARNING collarOffset : ignore collar startPercent because it’s broken now (see todolist)
+      model.startPercent = 0
+      model.nextBead = 0
+      model.duration = model.collar.duration
+      model.beadsDurs = model.collar.beads.map(v => v.length)
+      model.beadsCumulDurs = []
+      for (let cumul = 0, i = 0 ; i < model.beadsDurs.length ; i++) {
+        cumul += model.beadsDurs[i]
+        model.beadsCumulDurs.push(cumul)
+      }
       model.rate = parentRate * model.duration / model.length
       model.subWheels = model.collar.beads.map(v => this.prepare(v, model.gainNode, model.rate))
     }

From 1143532238710abdee57f80ee73ed3369fe81c89 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 11:56:41 +0200
Subject: [PATCH 54/85] fix sound pause
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

when there’s less than a full play to schedule before pause
---
 scheduler.js | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 0a3cedf..bfc4cff 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -206,17 +206,29 @@ let scheduler = {
           if (nextState && nextState.date < max) { // And should pause
             
             if (model.soundName) {
-              let newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+              if (nextState.date <= t) { // No need to play more, even partially
 
-                , startTime = newPlayers[newPlayers.length - 1].stopTime
-                , length = nextState.date - startTime
-                , duration = length * model.rate
+                nextState.percentPaused = clampPercent(0 - model.startPercent)
 
-              newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+              } else {
+                let newPlayers = []
+                  , startTime
 
-              model.players = model.players.concat(newPlayers)
+                if (nextState.date > t + model.length) { // At least one full play
+                  newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+                  startTime = newPlayers[newPlayers.length - 1].stopTime
+                } else { // Just a partial play
+                  startTime = t
+                }
+                let length = nextState.date - startTime
+                  , duration = length * model.rate
+
+                newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
 
-              nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+                model.players = model.players.concat(newPlayers)
+
+                nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+              }
             }
             
             if (model.collar) {

From 8f45e9ea4e1daee9697553f72ff811bb1d065d28 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 12:28:32 +0200
Subject: [PATCH 55/85] fix use of t and scheduleTime inside schedule()

---
 scheduler.js | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index bfc4cff..b0756dd 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -235,7 +235,7 @@ let scheduler = {
               // TODO collar pause
             }
             
-            scheduleTime = nextState.date
+            t = nextState.date
             
             advanceState()
             
@@ -244,7 +244,7 @@ let scheduler = {
             if (model.soundName) {
               let newPlayers = this.scheduleLoop(t, max, model)
               model.players = model.players.concat(newPlayers)
-              scheduleTime = model.players[model.players.length - 1].stopTime
+              t = model.players[model.players.length - 1].stopTime
             }
             
             if (model.collar) {
@@ -262,7 +262,7 @@ let scheduler = {
                 , offsetDur = soundPercent * model.duration + model.loopStartDur
                 , newPlayer = this.scheduleStart(t, model, offsetDur)
               model.players.push(newPlayer)
-              scheduleTime = newPlayer.stopTime
+              t = newPlayer.stopTime
               nextState.percentStarted = lastState.percentPaused
             }
             
@@ -275,10 +275,11 @@ let scheduler = {
             
           } else { // And keep pausing
             
-            scheduleTime = max
+            t = max
             
           }
         }
+        scheduleTime = t
       }
       model.lastScheduledTime = scheduleTime
     }

From 4d9bddd09c891709035daacaecb9fe1fb21eb0b2 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 12:31:11 +0200
Subject: [PATCH 56/85] collar start and play

---
 scheduler.js | 31 +++++++++++++++++++++++++------
 1 file changed, 25 insertions(+), 6 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index b0756dd..8a63e69 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -248,7 +248,14 @@ let scheduler = {
             }
             
             if (model.collar) {
-              // TODO collar play
+              while (t <= max) {
+                let length = model.beadsDurs[model.nextBead] / model.rate
+                  , beadPPT = model.subWheels[model.nextBead].playPauseTimes
+                beadPPT.push({date : t, play : true})
+                beadPPT.push({date : t + length, play : false})
+                model.nextBead = (model.nextBead + 1) % model.subWheels.length
+                t += length
+              }
             }
             
           }
@@ -256,20 +263,29 @@ let scheduler = {
         } else { // If we’re paused
           
           if (nextState && nextState.date < max) { // And should play
+            t = nextState.date
             
+            let contentPercent = clampPercent(lastState.percentPaused + model.startPercent)
+
             if (model.soundName) {
-              let soundPercent = clampPercent(lastState.percentPaused + model.startPercent)
-                , offsetDur = soundPercent * model.duration + model.loopStartDur
+              let offsetDur = contentPercent * model.duration + model.loopStartDur
                 , newPlayer = this.scheduleStart(t, model, offsetDur)
               model.players.push(newPlayer)
               t = newPlayer.stopTime
-              nextState.percentStarted = lastState.percentPaused
             }
             
             if (model.collar) {
-              // TODO collar start
+              let cumulDur = model.beadsCumulDurs[model.nextBead]
+                , offsetDur = contentPercent * model.duration
+                , length = (cumulDur - offsetDur) / model.rate
+                , beadPPT = model.subWheels[model.nextBead].playPauseTimes
+              beadPPT.push({date : t, play : true})
+              beadPPT.push({date : t + length, play : false})
+              model.nextBead = (model.nextBead + 1) % model.subWheels.length
+              t += length
             }
             
+            nextState.percentStarted = lastState.percentPaused
             advanceState()
 
             
@@ -282,7 +298,10 @@ let scheduler = {
         scheduleTime = t
       }
       model.lastScheduledTime = scheduleTime
-    }
+
+      if (model.collar) {
+        model.subWheels.forEach(v => this.schedule(v, now, max))
+      }
   }
   , scheduleLoop(t, maxT, model) {
     return [

From f845a981dd8a4115d057a33a4503d4d83caddd72 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 12:31:43 +0200
Subject: [PATCH 57/85] handle desync in draw

---
 scheduler.js | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 8a63e69..afc49c5 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -340,10 +340,13 @@ let scheduler = {
     for (let model of this.modelsToDraw) {
       let now = scheduler.getTime()
         , lastState = model.lastPlayPauseAt(now)
+        , percent = 0
       
-      let percent = clampPercent(lastState.play ?
-          lastState.percentStarted + (now - lastState.date) / model.length :
-          lastState.percentPaused)
+      if (lastState && lastState.done) {
+        percent = clampPercent(lastState.play ?
+            lastState.percentStarted + (now - lastState.date) / model.length :
+            lastState.percentPaused)
+      } else console.error("lastState was not done in draw :", lastState, "time is", now)
       
       model.view.moveTo(percent)
     }

From 9902974e94417229a4045e6cb021939211b27350 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 12:34:12 +0200
Subject: [PATCH 58/85] indent

---
 scheduler.js | 246 +++++++++++++++++++++++++--------------------------
 1 file changed, 123 insertions(+), 123 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index afc49c5..37adeb3 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -155,153 +155,153 @@ let scheduler = {
   }
       
   , schedule(model, now, max) {
-      let ppt = model.playPauseTimes
-      // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
-      // This is the assumption of user play and pause
-      // collar or another source of play pause should manage their specificities
-      
-      // Clean play pause events before last
-      ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduledTime)) - 1)
-      
-      let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
-        , nextState = ppt[nextStateIndex]
-        , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
-        , scheduleTime = model.lastScheduledTime
-        , advanceState = () => {
-          nextState.done = true
-          lastState = nextState
-          nextState = ppt[++nextStateIndex]
-        }
-      if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
-        scheduleTime = nextState.date // Bring back the scheduler
-        
-        if (!nextState.play) { // If we should’ve pause
-          
-          if (model.soundName) { // If sound, undo players
-            for (let pl of model.players) {
-              if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
-                pl.node.stop(this.toCtxTime(scheduleTime))
-                nextState.percentPaused = clampPercent((scheduleTime - pl.startTime) / model.length - model.startPercent)
-              }
-              if (pl.startTime > scheduleTime) pl.node.stop()
+    let ppt = model.playPauseTimes
+    // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
+    // This is the assumption of user play and pause
+    // collar or another source of play pause should manage their specificities
+
+    // Clean play pause events before last
+    ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduledTime)) - 1)
+
+    let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
+      , nextState = ppt[nextStateIndex]
+      , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
+      , scheduleTime = model.lastScheduledTime
+      , advanceState = () => {
+        nextState.done = true
+        lastState = nextState
+        nextState = ppt[++nextStateIndex]
+      }
+    if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
+      scheduleTime = nextState.date // Bring back the scheduler
+
+      if (!nextState.play) { // If we should’ve pause
+
+        if (model.soundName) { // If sound, undo players
+          for (let pl of model.players) {
+            if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
+              pl.node.stop(this.toCtxTime(scheduleTime))
+              nextState.percentPaused = clampPercent((scheduleTime - pl.startTime) / model.length - model.startPercent)
             }
+            if (pl.startTime > scheduleTime) pl.node.stop()
           }
-          
-          if (model.collar) { // If collar, undo playPause of subWheels
-            // TODO collar undo
-          }
-          
-          advanceState()
         }
+
+        if (model.collar) { // If collar, undo playPause of subWheels
+          // TODO collar undo
+        }
+
+        advanceState()
       }
-      
-      if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + scheduleTime)
-      
-      while (scheduleTime < max) {
-        
-        let t = scheduleTime
-        
-        if (lastState.play) { // If we’re playing
-          
-          if (nextState && nextState.date < max) { // And should pause
-            
-            if (model.soundName) {
-              if (nextState.date <= t) { // No need to play more, even partially
+    }
 
-                nextState.percentPaused = clampPercent(0 - model.startPercent)
+    if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + scheduleTime)
 
-              } else {
-                let newPlayers = []
-                  , startTime
+    while (scheduleTime < max) {
 
-                if (nextState.date > t + model.length) { // At least one full play
-                  newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
-                  startTime = newPlayers[newPlayers.length - 1].stopTime
-                } else { // Just a partial play
-                  startTime = t
-                }
-                let length = nextState.date - startTime
-                  , duration = length * model.rate
+      let t = scheduleTime
 
-                newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+      if (lastState.play) { // If we’re playing
 
-                model.players = model.players.concat(newPlayers)
+        if (nextState && nextState.date < max) { // And should pause
 
-                nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+          if (model.soundName) {
+            if (nextState.date <= t) { // No need to play more, even partially
+              
+              nextState.percentPaused = clampPercent(0 - model.startPercent)
+              
+            } else {
+              let newPlayers = []
+                , startTime
+              
+              if (nextState.date > t + model.length) { // At least one full play
+                newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+                startTime = newPlayers[newPlayers.length - 1].stopTime
+              } else { // Just a partial play
+                startTime = t
               }
-            }
-            
-            if (model.collar) {
-              // TODO collar pause
-            }
-            
-            t = nextState.date
-            
-            advanceState()
-            
-          } else { // And keep playing
-            
-            if (model.soundName) {
-              let newPlayers = this.scheduleLoop(t, max, model)
+              let length = nextState.date - startTime
+                , duration = length * model.rate
+
+              newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+
               model.players = model.players.concat(newPlayers)
-              t = model.players[model.players.length - 1].stopTime
-            }
-            
-            if (model.collar) {
-              while (t <= max) {
-                let length = model.beadsDurs[model.nextBead] / model.rate
-                  , beadPPT = model.subWheels[model.nextBead].playPauseTimes
-                beadPPT.push({date : t, play : true})
-                beadPPT.push({date : t + length, play : false})
-                model.nextBead = (model.nextBead + 1) % model.subWheels.length
-                t += length
-              }
+
+              nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
             }
-            
           }
-          
-        } else { // If we’re paused
-          
-          if (nextState && nextState.date < max) { // And should play
-            t = nextState.date
-            
-            let contentPercent = clampPercent(lastState.percentPaused + model.startPercent)
-
-            if (model.soundName) {
-              let offsetDur = contentPercent * model.duration + model.loopStartDur
-                , newPlayer = this.scheduleStart(t, model, offsetDur)
-              model.players.push(newPlayer)
-              t = newPlayer.stopTime
-            }
-            
-            if (model.collar) {
-              let cumulDur = model.beadsCumulDurs[model.nextBead]
-                , offsetDur = contentPercent * model.duration
-                , length = (cumulDur - offsetDur) / model.rate
+
+          if (model.collar) {
+            // TODO collar pause
+          }
+
+          t = nextState.date
+
+          advanceState()
+
+        } else { // And keep playing
+
+          if (model.soundName) {
+            let newPlayers = this.scheduleLoop(t, max, model)
+            model.players = model.players.concat(newPlayers)
+            t = model.players[model.players.length - 1].stopTime
+          }
+
+          if (model.collar) {
+            while (t <= max) {
+              let length = model.beadsDurs[model.nextBead] / model.rate
                 , beadPPT = model.subWheels[model.nextBead].playPauseTimes
               beadPPT.push({date : t, play : true})
               beadPPT.push({date : t + length, play : false})
               model.nextBead = (model.nextBead + 1) % model.subWheels.length
               t += length
             }
-            
-            nextState.percentStarted = lastState.percentPaused
-            advanceState()
-
-            
-          } else { // And keep pausing
-            
-            t = max
-            
           }
+
         }
-        scheduleTime = t
-      }
-      model.lastScheduledTime = scheduleTime
 
-      if (model.collar) {
-        model.subWheels.forEach(v => this.schedule(v, now, max))
+      } else { // If we’re paused
+
+        if (nextState && nextState.date < max) { // And should play
+          t = nextState.date
+          
+          let contentPercent = clampPercent(lastState.percentPaused + model.startPercent)
+
+          if (model.soundName) {
+            let offsetDur = contentPercent * model.duration + model.loopStartDur
+              , newPlayer = this.scheduleStart(t, model, offsetDur)
+            model.players.push(newPlayer)
+            t = newPlayer.stopTime
+          }
+
+          if (model.collar) {
+            let cumulDur = model.beadsCumulDurs[model.nextBead]
+              , offsetDur = contentPercent * model.duration
+              , length = (cumulDur - offsetDur) / model.rate
+              , beadPPT = model.subWheels[model.nextBead].playPauseTimes
+            beadPPT.push({date : t, play : true})
+            beadPPT.push({date : t + length, play : false})
+            model.nextBead = (model.nextBead + 1) % model.subWheels.length
+            t += length
+          }
+
+          nextState.percentStarted = lastState.percentPaused
+          advanceState()
+
+
+        } else { // And keep pausing
+
+          t = max
+
+        }
       }
+      scheduleTime = t
+    }
+    model.lastScheduledTime = scheduleTime
+
+    if (model.collar) {
+      model.subWheels.forEach(v => this.schedule(v, now, max))
+    }
   }
   , scheduleLoop(t, maxT, model) {
     return [

From 6fb1e4c94827d0c3207fc3a0b250ac59929d64c5 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 13:04:27 +0200
Subject: [PATCH 59/85] moved undo into schedule loop

---
 scheduler.js | 96 ++++++++++++++++++++++++++--------------------------
 1 file changed, 48 insertions(+), 48 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 37adeb3..320632b 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -172,71 +172,70 @@ let scheduler = {
         lastState = nextState
         nextState = ppt[++nextStateIndex]
       }
-    if (nextState && nextState.date < scheduleTime) { // If we sheduled ahead of next
-      scheduleTime = nextState.date // Bring back the scheduler
-
-      if (!nextState.play) { // If we should’ve pause
-
-        if (model.soundName) { // If sound, undo players
-          for (let pl of model.players) {
-            if (pl.startTime <= scheduleTime && scheduleTime < pl.stopTime) {
-              pl.node.stop(this.toCtxTime(scheduleTime))
-              nextState.percentPaused = clampPercent((scheduleTime - pl.startTime) / model.length - model.startPercent)
-            }
-            if (pl.startTime > scheduleTime) pl.node.stop()
-          }
-        }
-
-        if (model.collar) { // If collar, undo playPause of subWheels
-          // TODO collar undo
-        }
-
-        advanceState()
-      }
-    }
-
-    if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + scheduleTime)
 
     while (scheduleTime < max) {
 
       let t = scheduleTime
+      if (now > scheduleTime) console.error("scheduler is late, now : " + now + " scheduler : " + t)
 
       if (lastState.play) { // If we’re playing
 
         if (nextState && nextState.date < max) { // And should pause
 
-          if (model.soundName) {
-            if (nextState.date <= t) { // No need to play more, even partially
-              
-              nextState.percentPaused = clampPercent(0 - model.startPercent)
-              
-            } else {
-              let newPlayers = []
-                , startTime
-              
-              if (nextState.date > t + model.length) { // At least one full play
-                newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
-                startTime = newPlayers[newPlayers.length - 1].stopTime
-              } else { // Just a partial play
-                startTime = t
+          if (nextState.date < t) { // If we sheduled ahead of next
+            t = nextState.date // Bring back the time and undo
+            if (t <= now) console.error("undoing the past, now : " + now + " scheduler : " + t)
+
+            if (model.soundName) {
+              for (let pl of model.players) {
+                if (pl.startTime <= t && t < pl.stopTime) {
+                  pl.node.stop(this.toCtxTime(t))
+                  nextState.percentPaused = clampPercent((t - pl.startTime) / model.length - model.startPercent)
+                }
+                if (pl.startTime > t) pl.node.stop()
               }
-              let length = nextState.date - startTime
-                , duration = length * model.rate
+            }
+
+            if (model.collar) { // If collar, undo playPause of subWheels
+              // TODO collar undo
+            }
+
+          } else { // Normal pause
+          
+            if (model.soundName) {
+              if (nextState.date <= t) { // No need to play more, even partially
+
+                nextState.percentPaused = clampPercent(0 - model.startPercent)
 
-              newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+              } else {
+                let newPlayers = []
+                  , startTime
 
-              model.players = model.players.concat(newPlayers)
+                if (nextState.date > t + model.length) { // At least one full play
+                  newPlayers = this.scheduleLoop(t, nextState.date - model.length, model)
+                  startTime = newPlayers[newPlayers.length - 1].stopTime
+                } else { // Just a partial play
+                  startTime = t
+                }
+                let length = nextState.date - startTime
+                  , duration = length * model.rate
 
-              nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+                newPlayers.push(this.schedulePlayer(startTime, model, model.loopStartDur, duration, length))
+
+                model.players = model.players.concat(newPlayers)
+
+                nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+              }
             }
-          }
 
-          if (model.collar) {
-            // TODO collar pause
-          }
+            if (model.collar) {
+              // TODO collar pause
+            }
 
-          t = nextState.date
+            t = nextState.date
 
+          }
+          
           advanceState()
 
         } else { // And keep playing
@@ -264,6 +263,7 @@ let scheduler = {
 
         if (nextState && nextState.date < max) { // And should play
           t = nextState.date
+          if (t <= now) console.error("starting in the past, now : " + now + " scheduler : " + t)
           
           let contentPercent = clampPercent(lastState.percentPaused + model.startPercent)
 

From e0a80da1ad42776d0bc9ba2c8e2a4e5fded07fab Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:08:20 +0200
Subject: [PATCH 60/85] move sound thingy from port to scheduler

---
 ports.js     | 10 +++++-----
 scheduler.js |  6 ++++++
 2 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/ports.js b/ports.js
index 7a6fc35..fa2f158 100644
--- a/ports.js
+++ b/ports.js
@@ -10,8 +10,8 @@ if (app.ports.requestCutSample) app.ports.requestCutSample.subscribe(cutSample)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
-    , ctx = new AudioContext()
-ctx.suspend()
+//    , ctx = new AudioContext()
+//ctx.suspend()
 //    , ctx = new AudioContext()
 //    , nodeToRecord = Tone.context._context.createGain()
 //    , recorder = new Recorder(nodeToRecord)
@@ -112,9 +112,9 @@ function cutSample(infos) {
     app.ports.gotNewSample.send(new File([audioBufferToWav(newBuf)], infos.newFileName + ".wav", {type: "audio/wav"}))
 }
 
-let playPauseLatency = .1
-  , masterGain = ctx.createGain()
-masterGain.connect(ctx.destination)
+//let playPauseLatency = .1
+//  , masterGain = ctx.createGain()
+//masterGain.connect(ctx.destination)
 function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
   let model = null
   switch ( o.action ) {
diff --git a/scheduler.js b/scheduler.js
index 320632b..7ce4b9e 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -1,3 +1,9 @@
+const playPauseLatency = .1
+    , ctx = new AudioContext()
+    , masterGain = ctx.createGain()
+ctx.suspend()
+masterGain.connect(ctx.destination)
+
 let scheduler = {
     interval : 50
   , lookAhead : 2000

From f5ed4614badcacc770bfc04aee992dda8641f9f6 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:10:43 +0200
Subject: [PATCH 61/85] interval depends on playPauseLatency

---
 scheduler.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/scheduler.js b/scheduler.js
index 7ce4b9e..ab1da98 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -5,7 +5,7 @@ ctx.suspend()
 masterGain.connect(ctx.destination)
 
 let scheduler = {
-    interval : 50
+    interval : playPauseLatency * 250
   , lookAhead : 2000
   , running : false
   , intervalId : -1

From 1654d63f4d6ab7bc509defb8ac52b16a3f41727a Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:11:15 +0200
Subject: [PATCH 62/85] wait lookAhead time before cleaning players

---
 scheduler.js | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/scheduler.js b/scheduler.js
index ab1da98..fe959bc 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -85,7 +85,10 @@ let scheduler = {
     if (model.soundName) {
       model.players = []
       model.freePlayer = function(startTime) {
-        this.players = this.players.filter(v => v.startTime != startTime)
+        setTimeout(
+          () => this.players = this.players.filter(v => v.startTime != startTime)
+          , scheduler.lookAhead
+        )
       }
       model.buffer = buffers[model.soundName]
       // TODO beware, buffer duration could differ from saved duration in Elm model (due to resampling)

From 348f366f1abf0aec22b3697c2beec929f93cb625 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:13:58 +0200
Subject: [PATCH 63/85] minors

change first state date in prepare
change equality test when undoing
renamed percentPaused and percentStarted to percent for duck typing states in draw
---
 scheduler.js | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index fe959bc..36440ff 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -68,8 +68,8 @@ let scheduler = {
   , prepare(model, destination, parentRate) {
     // TODO this is creating a new func instance for each method for each model
     // It’s bad!! Should be in proto ?
-    model.playPauseTimes = [{date : 0, play : false, percentPaused : 0, done : true}]
-    model.lastScheduledTime = 0
+    model.lastScheduledTime = this.getTime()
+    model.playPauseTimes = [{date : model.lastScheduledTime, play : false, percent : 0, done : true}]
     model.lastPlayPauseAt = function(now) {
       return this.playPauseTimes.slice().reverse().find(v => v.date <= now)
     }
@@ -197,11 +197,11 @@ let scheduler = {
 
             if (model.soundName) {
               for (let pl of model.players) {
-                if (pl.startTime <= t && t < pl.stopTime) {
+                if (pl.startTime < t && t <= pl.stopTime) {
                   pl.node.stop(this.toCtxTime(t))
-                  nextState.percentPaused = clampPercent((t - pl.startTime) / model.length - model.startPercent)
+                  nextState.percent = clampPercent((t - pl.startTime) / model.length - model.startPercent)
                 }
-                if (pl.startTime > t) pl.node.stop()
+                if (pl.startTime >= t) pl.node.stop()
               }
             }
 
@@ -214,7 +214,7 @@ let scheduler = {
             if (model.soundName) {
               if (nextState.date <= t) { // No need to play more, even partially
 
-                nextState.percentPaused = clampPercent(0 - model.startPercent)
+                nextState.percent = clampPercent(0 - model.startPercent)
 
               } else {
                 let newPlayers = []
@@ -233,7 +233,7 @@ let scheduler = {
 
                 model.players = model.players.concat(newPlayers)
 
-                nextState.percentPaused = clampPercent(length / model.length - model.startPercent)
+                nextState.percent = clampPercent(length / model.length - model.startPercent)
               }
             }
 
@@ -274,7 +274,7 @@ let scheduler = {
           t = nextState.date
           if (t <= now) console.error("starting in the past, now : " + now + " scheduler : " + t)
           
-          let contentPercent = clampPercent(lastState.percentPaused + model.startPercent)
+          let contentPercent = clampPercent(lastState.percent + model.startPercent)
 
           if (model.soundName) {
             let offsetDur = contentPercent * model.duration + model.loopStartDur
@@ -294,7 +294,7 @@ let scheduler = {
             t += length
           }
 
-          nextState.percentStarted = lastState.percentPaused
+          nextState.percent = lastState.percent
           advanceState()
 
 

From 53ccd6315922e7051aa67a971151f19465be7a90 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:14:37 +0200
Subject: [PATCH 64/85] better handle desync in draw

---
 scheduler.js | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 36440ff..7f3a6c1 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -70,8 +70,11 @@ let scheduler = {
     // It’s bad!! Should be in proto ?
     model.lastScheduledTime = this.getTime()
     model.playPauseTimes = [{date : model.lastScheduledTime, play : false, percent : 0, done : true}]
-    model.lastPlayPauseAt = function(now) {
-      return this.playPauseTimes.slice().reverse().find(v => v.date <= now)
+    model.lastPlayPauseIndexAt = function(now) {
+      for (let i = this.playPauseTimes.length - 1 ; i >= 0 ; i--)
+        if (this.playPauseTimes[i].date <= now)
+          return i
+      return -1
     }
 
     let gain = ctx.createGain()
@@ -348,13 +351,16 @@ let scheduler = {
     // TODO percent keeps growing, will it overflow ?
     for (let model of this.modelsToDraw) {
       let now = scheduler.getTime()
-        , lastState = model.lastPlayPauseAt(now)
+        , lastStateIndex = model.lastPlayPauseIndexAt(now)
+        , lastState = model.playPauseTimes[lastStateIndex]
         , percent = 0
       
-      if (lastState && lastState.done) {
+      if (!lastState || !lastState.done) lastState = model.playPauseTimes[--lastStateIndex]
+      
+      if (lastState && isFinite(lastState.percent)) {
         percent = clampPercent(lastState.play ?
-            lastState.percentStarted + (now - lastState.date) / model.length :
-            lastState.percentPaused)
+            lastState.percent + (now - lastState.date) / model.length :
+            lastState.percent)
       } else console.error("lastState was not done in draw :", lastState, "time is", now)
       
       model.view.moveTo(percent)

From 0363f9477c55768e0968fcb5e83ea3e46a946330 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 14:42:01 +0200
Subject: [PATCH 65/85] stop collar

---
 scheduler.js | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 7f3a6c1..9b4fd65 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -44,11 +44,16 @@ let scheduler = {
     
     this.running = false
     
-    for (let id in this.playingTopModels) { // TODO loop also inside collars and mobiles, make a map function walking all sounds in the tree to use also in work and ?
-      let model = this.playingTopModels[id]
-      for (let player of model.players) {
-        player.node.stop()
+    let stopWheel = model => {
+      if (model.soundName) {
+        model.players.forEach(pl => pl.node.stop())
       }
+      if (model.collar) {
+        model.subWheels.forEach(stopWheel)
+      }
+    }
+    for (let id in this.playingTopModels) { // TODO make a map function walking all sounds in the tree to use also in work and ?
+      stopWheel(this.playingTopModels[id])
     }
     
     for (let model of this.modelsToDraw) {

From f3f2d4aa0da468af80f2565e03ce38eb17697717 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 17:38:47 +0200
Subject: [PATCH 66/85] prepare sets first State to the play time

prevent the scheduler from thinking we schedule the past
had to leave a fake pause at 0 for draw
---
 scheduler.js | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 9b4fd65..3eed59a 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -70,11 +70,14 @@ let scheduler = {
   
   
   , playingTopModels : {}
-  , prepare(model, destination, parentRate) {
+  , prepare(t, model, destination, parentRate) {
     // TODO this is creating a new func instance for each method for each model
     // It’s bad!! Should be in proto ?
-    model.lastScheduledTime = this.getTime()
-    model.playPauseTimes = [{date : model.lastScheduledTime, play : false, percent : 0, done : true}]
+    model.lastScheduledTime = t
+    model.playPauseTimes = [
+        {date : 0, play : false, percent : 0, done : true} // used by draw
+      , {date : t, play : false, percent : 0, done : true} // and one at t to prevent past scheduling warn
+    ]
     model.lastPlayPauseIndexAt = function(now) {
       for (let i = this.playPauseTimes.length - 1 ; i >= 0 ; i--)
         if (this.playPauseTimes[i].date <= now)
@@ -121,7 +124,7 @@ let scheduler = {
         model.beadsCumulDurs.push(cumul)
       }
       model.rate = parentRate * model.duration / model.length
-      model.subWheels = model.collar.beads.map(v => this.prepare(v, model.gainNode, model.rate))
+      model.subWheels = model.collar.beads.map(v => this.prepare(t, v, model.gainNode, model.rate))
     }
     
     model.realLength = model.length / parentRate
@@ -150,7 +153,7 @@ let scheduler = {
     let t = this.getTime() + playPauseLatency
     for (let model of topGears) {
       if (!this.playingTopModels[model.id])
-        this.playingTopModels[model.id] = this.prepare(model, masterGain, 1)
+        this.playingTopModels[model.id] = this.prepare(t, model, masterGain, 1)
       model = this.playingTopModels[model.id]
 
       let running = model.playPauseTimes[model.playPauseTimes.length - 1].play

From 5b24e5373d383f9273afb500ee45dc21063ccf37 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 17:40:05 +0200
Subject: [PATCH 67/85] better edge cases handling in sound undo

---
 scheduler.js | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 3eed59a..41b977d 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -208,11 +208,15 @@ let scheduler = {
 
             if (model.soundName) {
               for (let pl of model.players) {
-                if (pl.startTime < t && t <= pl.stopTime) {
+                if (pl.startTime <= t && t <= pl.stopTime) {
                   pl.node.stop(this.toCtxTime(t))
                   nextState.percent = clampPercent((t - pl.startTime) / model.length - model.startPercent)
                 }
-                if (pl.startTime >= t) pl.node.stop()
+                if (pl.startTime > t) pl.node.stop()
+              }
+              if (!isFinite(nextState.percent)) {
+                console.error("couldn’t find current player, unknown pause percent", now, nextState)
+                nextState.percent = 0
               }
             }
 

From bf8a201f26eeb3996c2f6fc0748a225ca9bc83bf Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 19:13:55 +0200
Subject: [PATCH 68/85] minors

---
 scheduler.js | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 41b977d..22c2e3c 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -1,3 +1,6 @@
+// TODO to prevent rounding, all calculations making time progress should be in scheduler timespace
+// presently, scheduling values get sometimes incremented by values coming from durations
+
 const playPauseLatency = .1
     , ctx = new AudioContext()
     , masterGain = ctx.createGain()
@@ -28,15 +31,15 @@ let scheduler = {
 
       ctx.resume().then(() => {
         this.startTime = ctx.currentTime
+        this.playPause(topGears)
         this.intervalId = setInterval(() => this.work(), this.interval)
         this.work()
         this.nextRequestId = requestAnimationFrame(() => this.draw())
-        this.playPause(topGears)
       })
     }
   }
   
-  , stop() {
+  , stop() { // TODO presently specific to soundWheels, todo mobile
     if (!this.running) return;
     
     clearInterval(this.intervalId)
@@ -70,7 +73,7 @@ let scheduler = {
   
   
   , playingTopModels : {}
-  , prepare(t, model, destination, parentRate) {
+  , prepare(t, model, destination, parentRate) { // TODO presently specific to soundWheels, todo mobile
     // TODO this is creating a new func instance for each method for each model
     // It’s bad!! Should be in proto ?
     model.lastScheduledTime = t
@@ -166,7 +169,7 @@ let scheduler = {
     }
   }
   
-  , work() { // TODO presently specific to soundWheels, todo collar & mobile
+  , work() {
     let now = this.getTime()
       , max = now + this.lookAhead / 1000
     for (let id in this.playingTopModels) {
@@ -174,7 +177,7 @@ let scheduler = {
     }
   }
       
-  , schedule(model, now, max) {
+  , schedule(model, now, max) { // TODO presently specific to soundWheels, todo mobile
     let ppt = model.playPauseTimes
     // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
     // This is the assumption of user play and pause
@@ -215,7 +218,7 @@ let scheduler = {
                 if (pl.startTime > t) pl.node.stop()
               }
               if (!isFinite(nextState.percent)) {
-                console.error("couldn’t find current player, unknown pause percent", now, nextState)
+                console.error("couldn’t find pausing player, unknown pause percent", now, nextState)
                 nextState.percent = 0
               }
             }
@@ -361,9 +364,9 @@ let scheduler = {
   , draw() {
     // TODO keeps drawing event when paused. is it bad ?
     // TODO percent keeps growing, will it overflow ?
+    let now = scheduler.getTime()
     for (let model of this.modelsToDraw) {
-      let now = scheduler.getTime()
-        , lastStateIndex = model.lastPlayPauseIndexAt(now)
+      let lastStateIndex = model.lastPlayPauseIndexAt(now)
         , lastState = model.playPauseTimes[lastStateIndex]
         , percent = 0
       
@@ -373,7 +376,7 @@ let scheduler = {
         percent = clampPercent(lastState.play ?
             lastState.percent + (now - lastState.date) / model.length :
             lastState.percent)
-      } else console.error("lastState was not done in draw :", lastState, "time is", now)
+      } else console.error("lastState was not done in draw :", lastState, "time is", now, "model", model)
       
       model.view.moveTo(percent)
     }

From a00c0db5c5bfffabaf0ea465f1977ae03aa13a3f Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 19:14:23 +0200
Subject: [PATCH 69/85] factorize schedule bead

---
 scheduler.js | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 22c2e3c..c82b419 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -276,10 +276,7 @@ let scheduler = {
           if (model.collar) {
             while (t <= max) {
               let length = model.beadsDurs[model.nextBead] / model.rate
-                , beadPPT = model.subWheels[model.nextBead].playPauseTimes
-              beadPPT.push({date : t, play : true})
-              beadPPT.push({date : t + length, play : false})
-              model.nextBead = (model.nextBead + 1) % model.subWheels.length
+              this.scheduleBead(t, model, length)
               t += length
             }
           }
@@ -305,10 +302,7 @@ let scheduler = {
             let cumulDur = model.beadsCumulDurs[model.nextBead]
               , offsetDur = contentPercent * model.duration
               , length = (cumulDur - offsetDur) / model.rate
-              , beadPPT = model.subWheels[model.nextBead].playPauseTimes
-            beadPPT.push({date : t, play : true})
-            beadPPT.push({date : t + length, play : false})
-            model.nextBead = (model.nextBead + 1) % model.subWheels.length
+            this.scheduleBead(t, model, length)
             t += length
           }
 
@@ -330,6 +324,12 @@ let scheduler = {
       model.subWheels.forEach(v => this.schedule(v, now, max))
     }
   }
+  , scheduleBead(t, model, length, advanceBead = true) {
+    let beadPPT = model.subWheels[model.nextBead].playPauseTimes
+    beadPPT.push({date : t, play : true})
+    beadPPT.push({date : t + length, play : false})
+    if (advanceBead) model.nextBead = (model.nextBead + 1) % model.subWheels.length
+  }
   , scheduleLoop(t, maxT, model) {
     return [
       this.schedulePlayer(t, model, model.loopStartDur, model.duration, model.length)

From 1501a066c83e34466db86b60e98f3fa8cdc43dab Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 19:14:42 +0200
Subject: [PATCH 70/85] collar pause and undo

!!!
---
 scheduler.js | 40 ++++++++++++++++++++++++++++++++++++++--
 1 file changed, 38 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index c82b419..36b7a93 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -224,7 +224,31 @@ let scheduler = {
             }
 
             if (model.collar) { // If collar, undo playPause of subWheels
-              // TODO collar undo
+              let pausingBeadIndex = -1
+                , beadPlayTime
+              for (let i = 0 ; i < model.subWheels.length ; i++) {
+                let sub = model.subWheels[i]
+                  , lastStateIndex = sub.lastPlayPauseIndexAt(t)
+                  , subLastState = sub.playPauseTimes[lastStateIndex]
+                
+                sub.playPauseTimes = sub.playPauseTimes.slice(0, lastStateIndex + 1)
+                
+                if (subLastState.play) {
+                  pausingBeadIndex = i
+                  beadPlayTime = subLastState.date
+                  sub.playPauseTimes.push({date : t, play : false})
+                }
+              }
+              if (pausingBeadIndex == -1) {
+                console.error("couldn’t find pausing bead, unknown pause percent and next Bead", now, nextState)
+                nextState.percent = 0
+                model.nextBead = 0
+              } else {
+                let length = t - beadPlayTime
+                  , cumul = model.beadsCumulDurs[pausingBeadIndex - 1] / model.rate || 0
+                nextState.percent = clampPercent((cumul + length) / model.length)
+                model.nextBead = pausingBeadIndex
+              }
             }
 
           } else { // Normal pause
@@ -256,7 +280,19 @@ let scheduler = {
             }
 
             if (model.collar) {
-              // TODO collar pause
+              
+              let nextLength = model.beadsDurs[model.nextBead] / model.rate
+              while (t + nextLength <= nextState.date) {
+                this.scheduleBead(t, model, nextLength)
+                t += nextLength
+                nextLength = model.beadsDurs[model.nextBead] / model.rate
+              }
+              
+              let length = nextState.date - t
+                , cumul = model.beadsCumulDurs[model.nextBead - 1] / model.rate || 0
+              this.scheduleBead(t, model, length, false)
+              
+              nextState.percent = clampPercent((cumul + length) / model.length)
             }
 
             t = nextState.date

From a468392bfb3047e538662b3e575b72812577fc0e Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sun, 18 Oct 2020 20:15:24 +0200
Subject: [PATCH 71/85] mute and volume inside collars

---
 ports.js | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/ports.js b/ports.js
index fa2f158..d2f053c 100644
--- a/ports.js
+++ b/ports.js
@@ -131,25 +131,27 @@ function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
 //        o.gears.map(g => scheduler.playPause(g, t))
         break;
     case "mute" :
-//        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
-        model = scheduler.playingTopModels[o.id] // TODO beads inside collars
+        model = o.beadIndexes.reduce(
+            (acc, v) => {
+              if (acc && acc.subWheels) return acc.subWheels[v]
+            }
+          , scheduler.playingTopModels[o.id]
+          )
         if (model) {
           model.mute = o.value
           model.updateVolume()
-//            if (o.value) {
-//              model.setVolume(0)
-//            } else {
-//              model.setVolume(model.volume)
-//            }
         }
         break;
     case "volume" :
-//        model = o.beadIndexes.reduce((acc, v) => {if (acc && acc.players) return acc.players[v]}, playing[o.id])
-        model = scheduler.playingTopModels[o.id] // TODO beads inside collars
+        model = o.beadIndexes.reduce(
+            (acc, v) => {
+              if (acc && acc.subWheels) return acc.subWheels[v]
+            }
+          , scheduler.playingTopModels[o.id]
+          )
         if (model) {
           model.volume = o.value
           model.updateVolume()
-//            if (!model.mute) model.setVolume(o.value)
         }
         break;
     }

From 3744765a16ed055712eba9e40042e832255e9dcf Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 19 Oct 2020 00:39:10 +0200
Subject: [PATCH 72/85] mobile scheduling

---
 scheduler.js | 40 +++++++++++++++++++++++++++++++++-------
 1 file changed, 33 insertions(+), 7 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 36b7a93..5a5c1d0 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -39,7 +39,7 @@ let scheduler = {
     }
   }
   
-  , stop() { // TODO presently specific to soundWheels, todo mobile
+  , stop() {
     if (!this.running) return;
     
     clearInterval(this.intervalId)
@@ -51,11 +51,11 @@ let scheduler = {
       if (model.soundName) {
         model.players.forEach(pl => pl.node.stop())
       }
-      if (model.collar) {
+      if (model.collar || model.mobile) {
         model.subWheels.forEach(stopWheel)
       }
     }
-    for (let id in this.playingTopModels) { // TODO make a map function walking all sounds in the tree to use also in work and ?
+    for (let id in this.playingTopModels) {
       stopWheel(this.playingTopModels[id])
     }
     
@@ -73,7 +73,7 @@ let scheduler = {
   
   
   , playingTopModels : {}
-  , prepare(t, model, destination, parentRate) { // TODO presently specific to soundWheels, todo mobile
+  , prepare(t, model, destination, parentRate) {
     // TODO this is creating a new func instance for each method for each model
     // It’s bad!! Should be in proto ?
     model.lastScheduledTime = t
@@ -130,6 +130,12 @@ let scheduler = {
       model.subWheels = model.collar.beads.map(v => this.prepare(t, v, model.gainNode, model.rate))
     }
     
+    if (model.mobile) {
+      model.duration = model.mobile.duration
+      model.rate = parentRate * model.duration / model.length
+      model.subWheels = model.mobile.gears.map(v => this.prepare(t, v, model.gainNode, model.rate))
+    }
+    
     model.realLength = model.length / parentRate
     model.lengthBeforeParentRate = model.length
     model.length = model.realLength
@@ -177,7 +183,7 @@ let scheduler = {
     }
   }
       
-  , schedule(model, now, max) { // TODO presently specific to soundWheels, todo mobile
+  , schedule(model, now, max) {
     let ppt = model.playPauseTimes
     // For now, considering that playPauseTimes is filled chronologically and alternatively of play and pause
     // This is the assumption of user play and pause
@@ -294,6 +300,14 @@ let scheduler = {
               
               nextState.percent = clampPercent((cumul + length) / model.length)
             }
+            
+            if (model.mobile) {
+              model.subWheels.forEach(v => v.playPauseTimes.push({date : nextState.date, play : false}))
+              nextState.percent = clampPercent(
+                lastState.percent
+                + (nextState.date - model.lastStartTime) / model.length
+              )
+            }
 
             t = nextState.date
 
@@ -316,6 +330,10 @@ let scheduler = {
               t += length
             }
           }
+          
+          if (model.mobile) {
+            t = max
+          }
 
         }
 
@@ -341,10 +359,18 @@ let scheduler = {
             this.scheduleBead(t, model, length)
             t += length
           }
+          
+          if (model.mobile) {
+            model.lastStartTime = t
+            model.subWheels.forEach(v => v.playPauseTimes.push({date : t, play : true}))
+          }
 
           nextState.percent = lastState.percent
           advanceState()
-
+          if (model.mobile) {
+            if (nextState) t = nextState.date
+            else t = max
+          }
 
         } else { // And keep pausing
 
@@ -356,7 +382,7 @@ let scheduler = {
     }
     model.lastScheduledTime = scheduleTime
 
-    if (model.collar) {
+    if (model.collar || model.mobile) {
       model.subWheels.forEach(v => this.schedule(v, now, max))
     }
   }

From cb217998ef2560d24d1f9491cebd07b396af387d Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 19 Oct 2020 00:40:15 +0200
Subject: [PATCH 73/85] fix undoing edge case

---
 scheduler.js | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 5a5c1d0..6eed993 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -195,7 +195,7 @@ let scheduler = {
     let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
       , nextState = ppt[nextStateIndex]
       , lastState = ppt[nextStateIndex - 1] || ppt[ppt.length - 1]
-      , scheduleTime = model.lastScheduledTime
+      , scheduleTime = nextState ? Math.min(nextState.date, model.lastScheduledTime) : model.lastScheduledTime
       , advanceState = () => {
         nextState.done = true
         lastState = nextState
@@ -211,7 +211,7 @@ let scheduler = {
 
         if (nextState && nextState.date < max) { // And should pause
 
-          if (nextState.date < t) { // If we sheduled ahead of next
+          if ((nextState.date < t || nextState.date < model.lastScheduledTime) && !model.mobile) { // If we sheduled ahead of next
             t = nextState.date // Bring back the time and undo
             if (t <= now) console.error("undoing the past, now : " + now + " scheduler : " + t)
 
@@ -243,6 +243,10 @@ let scheduler = {
                   pausingBeadIndex = i
                   beadPlayTime = subLastState.date
                   sub.playPauseTimes.push({date : t, play : false})
+                } else { // WARNING hack to force the subWheel undoing
+                  // TODO this hack could be replaced generally by transmitting the undo info to subWheels
+                  sub.playPauseTimes.push({date : t, play : true})
+                  sub.playPauseTimes.push({date : t, play : false})
                 }
               }
               if (pausingBeadIndex == -1) {

From 386b2412a1e2bb393e2756ddebd620384411e637 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 24 Oct 2020 13:58:29 +0200
Subject: [PATCH 74/85] Add let _ = to all Debug.log (quasi)

---
 src/Coll.elm          |  6 +++++-
 src/Data/Common.elm   | 30 +++++++++++++++++++++++++-----
 src/Data/Content.elm  |  6 +++++-
 src/Data/Mobile.elm   |  6 +++++-
 src/Doc.elm           | 12 ++++++++++--
 src/Editor/Mobile.elm | 12 ++++++++++--
 src/Engine.elm        |  6 +++++-
 src/Harmony.elm       | 12 ++++++++++--
 src/Interact.elm      |  1 +
 src/Main.elm          | 25 ++++++++++++++++++++-----
 src/Waveform.elm      |  6 +++++-
 11 files changed, 101 insertions(+), 21 deletions(-)

diff --git a/src/Coll.elm b/src/Coll.elm
index 370b351..4f6ba86 100644
--- a/src/Coll.elm
+++ b/src/Coll.elm
@@ -90,7 +90,11 @@ get : Id item -> Coll item -> item
 get id (C coll) =
     case maybeGet id (C coll) of
         Nothing ->
-            Debug.log ("No " ++ coll.typeString ++ " for id " ++ (String.fromInt <| getIdInternal id)) coll.default
+            let
+                _ =
+                    Debug.log ("No " ++ coll.typeString ++ " for id " ++ (String.fromInt <| getIdInternal id)) coll
+            in
+            coll.default
 
         Just item ->
             item
diff --git a/src/Data/Common.elm b/src/Data/Common.elm
index 893935a..a31c9fe 100644
--- a/src/Data/Common.elm
+++ b/src/Data/Common.elm
@@ -67,7 +67,11 @@ getWheel ( id, list ) m =
                             f ll (Content.getBead i col).wheel
 
                         _ ->
-                            Debug.log ("Wrong identifier to get " ++ (String.concat <| List.map String.fromInt l)) w
+                            let
+                                _ =
+                                    Debug.log ("Wrong identifier to get " ++ (String.concat <| List.map String.fromInt l)) ( id, list, m )
+                            in
+                            w
     in
     f list (Content.getGear id m).wheel
 
@@ -92,7 +96,11 @@ deleteWheel ( id, l ) mobile gRm bRm =
                             Content.updateBead index (Wheel.setContent <| Content.C <| rec i rest subCol) col
 
                         _ ->
-                            Debug.log "Wrong identifier to delete bead" col
+                            let
+                                _ =
+                                    Debug.log "Wrong identifier to delete bead" ( id, l, mobile )
+                            in
+                            col
     in
     case l of
         [] ->
@@ -104,7 +112,11 @@ deleteWheel ( id, l ) mobile gRm bRm =
                     Content.updateGear id (Wheel.setContent <| Content.C <| bRm i col) mobile
 
                 _ ->
-                    Debug.log "Wrong identifier to delete bead" mobile
+                    let
+                        _ =
+                            Debug.log "Wrong identifier to delete bead" ( id, l, mobile )
+                    in
+                    mobile
 
         i :: rest ->
             case Wheel.getContent <| Coll.get id mobile.gears of
@@ -112,7 +124,11 @@ deleteWheel ( id, l ) mobile gRm bRm =
                     Content.updateGear id (Wheel.setContent <| Content.C <| rec i rest col) mobile
 
                 _ ->
-                    Debug.log "Wrong identifier to delete bead" mobile
+                    let
+                        _ =
+                            Debug.log "Wrong identifier to delete bead" ( id, l, mobile )
+                    in
+                    mobile
 
 
 updateWheel : Identifier -> Wheel.Msg -> Mobile Wheel -> Mobile Wheel
@@ -134,7 +150,11 @@ updateWheel ( id, list ) msg m =
                             ).wheel
 
                         _ ->
-                            Debug.log ("Wrong identifier to update " ++ (String.concat <| List.map String.fromInt l)) w
+                            let
+                                _ =
+                                    Debug.log "Wrong identifier to delete bead" ( ( id, l ), msg, m )
+                            in
+                            w
     in
     Content.updateGear id (\gear -> { gear | wheel = rec list gear.wheel }) m
 
diff --git a/src/Data/Content.elm b/src/Data/Content.elm
index 1f7adb6..4eb57d7 100644
--- a/src/Data/Content.elm
+++ b/src/Data/Content.elm
@@ -119,7 +119,11 @@ getBead i c =
             b
 
         Nothing ->
-            Debug.log ("Cannot get Bead " ++ String.fromInt i) <| c.head
+            let
+                _ =
+                    Debug.log ("Cannot get Bead " ++ String.fromInt i) ( i, c )
+            in
+            c.head
 
 
 updateBead : Int -> (Bead item -> Bead item) -> Collar item -> Collar item
diff --git a/src/Data/Mobile.elm b/src/Data/Mobile.elm
index 65f9bd3..4eca0cb 100644
--- a/src/Data/Mobile.elm
+++ b/src/Data/Mobile.elm
@@ -101,7 +101,11 @@ rm id m =
         -- TODO check and use harmo clean
         if Harmo.hasHarmonics harmo then
             -- TODO delete base ?
-            Debug.log "TODO delete base" m
+            let
+                _ =
+                    Debug.log "TODO delete base" []
+            in
+            m
 
         else
             case Harmo.getBaseId harmo of
diff --git a/src/Doc.elm b/src/Doc.elm
index 55ece0f..c58b790 100644
--- a/src/Doc.elm
+++ b/src/Doc.elm
@@ -478,7 +478,11 @@ getViewingHelper l mob =
                     ViewRes mobile (Common.toUid next ++ parentUid) <| ( str, next ) :: cleanedView
 
                 _ ->
-                    Debug.log ("No mobile to view in " ++ str) <| ViewRes mob "" []
+                    let
+                        _ =
+                            Debug.log ("No mobile to view in " ++ str) mob
+                    in
+                    ViewRes mob "" []
 
         _ ->
             ViewRes mob "" []
@@ -495,7 +499,11 @@ updateViewing l f mobile =
                         mobile
 
                 _ ->
-                    Debug.log "IMPOSSIBLE View isn’t correct, should’ve been cleaned" mobile
+                    let
+                        _ =
+                            Debug.log "IMPOSSIBLE View isn’t correct, should’ve been cleaned" ( l, mobile )
+                    in
+                    mobile
 
         _ ->
             f mobile
diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index ee5a4d2..ad940ad 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -337,7 +337,11 @@ update msg ( model, mobile ) =
                     { return | cmd = DL.url url }
 
                 Err err ->
-                    Debug.log (D.errorToString err) return
+                    let
+                        _ =
+                            Debug.log (D.errorToString err) res
+                    in
+                    return
 
         PlayGear ->
             case model.tool of
@@ -874,7 +878,11 @@ update msg ( model, mobile ) =
         SVGSize res ->
             case res of
                 Result.Err e ->
-                    Debug.log (D.errorToString e) return
+                    let
+                        _ =
+                            Debug.log (D.errorToString e) res
+                    in
+                    return
 
                 Result.Ok s ->
                     let
diff --git a/src/Engine.elm b/src/Engine.elm
index 867a9e3..d91397a 100644
--- a/src/Engine.elm
+++ b/src/Engine.elm
@@ -135,7 +135,11 @@ encodeGear hasView parentUid coll id =
             parentUid ++ Gear.toUID id
     in
     if length == 0 then
-        Debug.log (uid ++ "’s length is 0") E.null
+        let
+            _ =
+                Debug.log (uid ++ "’s length is 0") g
+        in
+        E.null
 
     else
         E.object
diff --git a/src/Harmony.elm b/src/Harmony.elm
index f6dd259..5cee6be 100644
--- a/src/Harmony.elm
+++ b/src/Harmony.elm
@@ -134,7 +134,11 @@ getLength harmo coll =
                     unit * Fract.toFloat harmo.fract
 
                 Other _ ->
-                    Debug.log "IMPOSSIBLE Ref isn’t a base" 0
+                    let
+                        _ =
+                            Debug.log "IMPOSSIBLE Ref isn’t a base" ( harmo, coll )
+                    in
+                    0
 
 
 newSelf : Float -> Harmony
@@ -236,7 +240,11 @@ isActiveLink : Link (Harmonized g) -> Harmony -> Bool
 isActiveLink l h =
     case h.ref of
         Other _ ->
-            Debug.log "Can’t check active links if not base" False
+            let
+                _ =
+                    Debug.log "Can’t check active links if not base" h
+            in
+            False
 
         Self { links } ->
             List.any (Link.equal <| Link.map l) links
diff --git a/src/Interact.elm b/src/Interact.elm
index f3913e2..ea6a028 100644
--- a/src/Interact.elm
+++ b/src/Interact.elm
@@ -256,6 +256,7 @@ subs (S { click }) =
             [ BE.onMouseUp <| D.succeed <| EndClick
             , BE.onVisibilityChange
                 (\v ->
+                    -- TODO check bug visibility hidden not emitted on window change but on tab change
                     Debug.log (Debug.toString v) <|
                         case v of
                             BE.Hidden ->
diff --git a/src/Main.elm b/src/Main.elm
index 1d534f8..43ba792 100644
--- a/src/Main.elm
+++ b/src/Main.elm
@@ -55,7 +55,6 @@ port gotNewSample : (D.Value -> msg) -> Sub msg
 
 
 -- TODO refactor existing Debug.log with "key" value
--- TODO check bug visibility hidden not emitted on window change but on tab change
 -- TODO check msg or Msg in types, if unused, maybe replace by x
 -- TODO clean all module exposings decl
 -- TODO is "No error handling in update, everything comes Checked before" is a good pattern ?
@@ -432,10 +431,18 @@ update msg model =
                             ( { mod | soundList = newSL }, Cmd.batch <| cmd :: cmds )
 
                         _ ->
-                            Debug.log "Cannot load, sound not found" ( model, Cmd.none )
+                            let
+                                _ =
+                                    Debug.log "Cannot load, sound not found" m
+                            in
+                            ( model, Cmd.none )
 
                 Err (Http.BadBody err) ->
-                    Debug.log err ( model, Cmd.none )
+                    let
+                        _ =
+                            Debug.log ("Error loading " ++ name ++ " : " ++ err) result
+                    in
+                    ( model, Cmd.none )
 
                 Err _ ->
                     ( { model | connected = False }, Cmd.none )
@@ -486,7 +493,11 @@ update msg model =
         SoundLoaded res ->
             case res of
                 Err e ->
-                    Debug.log (D.errorToString e) ( model, Cmd.none )
+                    let
+                        _ =
+                            Debug.log (D.errorToString e) res
+                    in
+                    ( model, Cmd.none )
 
                 Ok s ->
                     ( { model | loadedSoundList = s :: model.loadedSoundList }, Cmd.none )
@@ -542,7 +553,11 @@ update msg model =
                     update (UploadSounds file []) model
 
                 Err err ->
-                    Debug.log (D.errorToString err) ( model, Cmd.none )
+                    let
+                        _ =
+                            Debug.log (D.errorToString err) res
+                    in
+                    ( model, Cmd.none )
 
         ClickedUploadSave ->
             ( model, Select.files [] UploadSaves )
diff --git a/src/Waveform.elm b/src/Waveform.elm
index f31b8fc..4e1cdfe 100644
--- a/src/Waveform.elm
+++ b/src/Waveform.elm
@@ -106,7 +106,11 @@ update msg wave =
                             ( wave, Cmd.none )
 
                 Err err ->
-                    Debug.log ("Error while drawing " ++ D.errorToString err) ( wave, Cmd.none )
+                    let
+                        _ =
+                            Debug.log ("Error while drawing " ++ D.errorToString err) wave
+                    in
+                    ( wave, Cmd.none )
 
         Select ( centerPx, percentLength ) ->
             let

From 979fe1189216874367deec2b68803a02444e2226 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 24 Oct 2020 20:40:47 +0200
Subject: [PATCH 75/85] fixed long sounds play n pause

---
 scheduler.js | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 6eed993..f1d318d 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -190,7 +190,13 @@ let scheduler = {
     // collar or another source of play pause should manage their specificities
 
     // Clean play pause events before last
-    ppt.splice(0, ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduledTime)) - 1)
+    ppt.splice(
+      0,
+      Math.min(
+        ppt.findIndex(v => !v.done),
+        ppt.findIndex(v => v.date >= Math.min(now, model.lastScheduledTime))
+      ) - 1
+    )
 
     let nextStateIndex = ppt.findIndex(v => !v.done) // Next is first not done
       , nextState = ppt[nextStateIndex]
@@ -219,7 +225,7 @@ let scheduler = {
               for (let pl of model.players) {
                 if (pl.startTime <= t && t <= pl.stopTime) {
                   pl.node.stop(this.toCtxTime(t))
-                  nextState.percent = clampPercent((t - pl.startTime) / model.length - model.startPercent)
+                  nextState.percent = clampPercent((t - pl.startTime) / model.length + pl.startOffsetDur / model.duration - model.startPercent)
                 }
                 if (pl.startTime > t) pl.node.stop()
               }
@@ -420,6 +426,7 @@ let scheduler = {
         node : player
       , startTime : t
       , stopTime : t + length
+      , startOffsetDur : startOffset
     }
   }
   

From 10e0acfc0e2a2c10284908299fcfce330a99dcca Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 24 Oct 2020 21:59:56 +0200
Subject: [PATCH 76/85] reenable both recordings

---
 ports.js     | 55 +++++++++++++++++++++++++++++-----------------------
 scheduler.js |  3 ++-
 2 files changed, 33 insertions(+), 25 deletions(-)

diff --git a/ports.js b/ports.js
index d2f053c..e8ee3ea 100644
--- a/ports.js
+++ b/ports.js
@@ -5,21 +5,15 @@ if (app.ports.toEngine) app.ports.toEngine.subscribe(engine)
 if (app.ports.toggleRecord) app.ports.toggleRecord.subscribe(toggleRecord)
 if (app.ports.requestSoundDraw) app.ports.requestSoundDraw.subscribe(drawSound)
 if (app.ports.requestCutSample) app.ports.requestCutSample.subscribe(cutSample)
-//if (app.ports.openMic) app.ports.openMic.subscribe(openMic)
-//if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
+if (app.ports.openMic) app.ports.openMic.subscribe(openMic)
+if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
 //    , ctx = new AudioContext()
 //ctx.suspend()
 //    , ctx = new AudioContext()
-//    , nodeToRecord = Tone.context._context.createGain()
-//    , recorder = new Recorder(nodeToRecord)
-//    , mic = new Tone.UserMedia()
-//    , micToRecord = Tone.context.createGain()
-//    , micRecorder = new Recorder(micToRecord)
-//Tone.Master.connect(nodeToRecord)
-//mic.connect(micToRecord)
+    , recorder = new Recorder(masterGain)
 ro.observe(document.getElementById('svgResizeObserver'))
 
 //let playing = {}
@@ -76,21 +70,34 @@ function toggleRecord(bool) {
     }
 }
 
-//function openMic() {
-//  Tone.start()
-//  mic.open().then(
-//    () => app.ports.micOpened.send(null)
-//  ).catch(console.error)
-//}
-//
-//function inputRec(name) {
-//  if (name) {
-//    micRecorder.stop()
-//    micRecorder.exportWAV(bl => app.ports.gotNewSample.send(new File([bl], name + ".wav", {type: "audio/wav"})))
-//    micRecorder.clear()
-//  } else if (mic.state == "started") micRecorder.record()
-//  else console.error("won’t record mic if it ain’t opened !")
-//}
+let mic
+  , micToRecord
+  , micRecorder
+  , recording
+function openMic() {
+  navigator.mediaDevices.getUserMedia({audio : true}).then(stream => {
+    mic = stream
+    micToRecord = ctx.createMediaStreamSource(mic)
+    micRecorder = new Recorder(micToRecord)
+    app.ports.micOpened.send(null)
+  }).catch(console.error)
+}
+
+function inputRec(name) {
+  if (name) {
+    micRecorder.stop()
+    micRecorder.exportWAV(bl => app.ports.gotNewSample.send(new File([bl], name + ".wav", {type: "audio/wav"})))
+    micRecorder.clear()
+    recording = false
+    if (!scheduler.running) ctx.suspend()
+  } else {
+    if (mic) {
+      ctx.resume()
+      micRecorder.record()
+      recording = true
+    } else console.error("won’t record mic if it ain’t opened !")
+  }
+}
 
 function cutSample(infos) {
     if (!buffers[infos.fromFileName]) {console.error(infos.fromFileName + " ain’t loaded, cannot cut");return;}
diff --git a/scheduler.js b/scheduler.js
index f1d318d..de15d08 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -63,7 +63,8 @@ let scheduler = {
       model.view.moveTo(0)
     }
     
-    ctx.suspend()
+    if (!recording) ctx.suspend()
+    
     this.intervalId = -1
     this.nextRequestId = -1
     this.startTime = -1

From b46c29f23b47912e8671fef9f394a2a29442b32d Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 24 Oct 2020 22:13:28 +0200
Subject: [PATCH 77/85] clean

---
 lib/Tone.js     |   22 -
 lib/howler.js   | 3157 ---------------
 lib/interact.js | 9932 -----------------------------------------------
 lib/svg.js      | 5601 --------------------------
 playable.js     |  134 -
 ports.html      |    2 -
 ports.js        |   28 +-
 scheduler.js    |    2 +-
 8 files changed, 2 insertions(+), 18876 deletions(-)
 delete mode 100644 lib/Tone.js
 delete mode 100644 lib/howler.js
 delete mode 100644 lib/interact.js
 delete mode 100644 lib/svg.js
 delete mode 100644 playable.js

diff --git a/lib/Tone.js b/lib/Tone.js
deleted file mode 100644
index 7f8f33d..0000000
--- a/lib/Tone.js
+++ /dev/null
@@ -1,22 +0,0 @@
-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Tone=e():t.Tone=e()}("undefined"!=typeof self?self:this,(function(){return function(t){var e={};function n(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return t[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,s){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:s})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(s,i,function(e){return t[e]}.bind(null,i));return s},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=684)}([function(t,e,n){"use strict";n.d(e,"a",(function(){return s})),n.d(e,"b",(function(){return i})),n.d(e,"c",(function(){return o})),n.d(e,"d",(function(){return r})),n.d(e,"e",(function(){return a})),n.d(e,"f",(function(){return c})),n.d(e,"g",(function(){return u})),n.d(e,"i",(function(){return h})),n.d(e,"h",(function(){return l})),n.d(e,"j",(function(){return d})),n.d(e,"k",(function(){return p}));const s=new WeakSet,i=new WeakMap,o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,u=new WeakMap,h=new WeakMap,l=new WeakMap,d=new WeakMap,p=new WeakMap},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(4);const i=(t,e)=>{Object(s.a)(t,e,"channelCount"),Object(s.a)(t,e,"channelCountMode"),Object(s.a)(t,e,"channelInterpretation")}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s})),n.d(e,"b",(function(){return i}));const s=-34028234663852886e22,i=-s},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>t.context===e},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n]&&(t[n]=s)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>{const s=e[n];void 0!==s&&s!==t[n].value&&(t[n].value=s)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.c,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","InvalidStateError")}catch(t){return t.code=11,t.name="InvalidStateError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.b,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>{const n=t.get(e);if(void 0===n)throw new Error("A value with the given key could not be found.");return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","NotSupportedError")}catch(t){return t.code=9,t.name="NotSupportedError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(t.connect=e.connect.bind(e),t.disconnect=e.disconnect.bind(e),t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"inputs"in t},function(t,e,n){"use strict";n.d(e,"AudioContext",(function(){return Oi})),n.d(e,"AudioWorkletNode",(function(){return qi})),n.d(e,"OfflineAudioContext",(function(){return Vi})),n.d(e,"isAnyAudioContext",(function(){return Ni})),n.d(e,"isAnyAudioNode",(function(){return Pi})),n.d(e,"isAnyAudioParam",(function(){return Li})),n.d(e,"isAnyOfflineAudioContext",(function(){return zi})),n.d(e,"isSupported",(function(){return Bi}));var s=n(18),i=n(516),o=n(517),r=n(518),a=n(667),c=n(519),u=n(520),h=n(521),l=n(522),d=n(523),p=n(524),f=n(525),_=n(526),m=n(527),g=n(528),v=n(529),y=n(665),b=n(530),x=n(531),w=n(532),T=n(670),O=n(533),S=n(534),C=n(535),k=n(536),A=n(537),D=n(538),M=n(539),j=n(540),E=n(541),R=n(542),q=n(543),I=n(544),F=n(545),V=n(546),N=n(547),P=n(548),L=n(549),z=n(550),B=n(671),W=n(551),U=n(552),G=n(553),Y=n(554),Q=n(672),Z=n(555),X=n(556),H=n(557),$=n(558),J=n(559),K=n(560),tt=n(561),et=n(562),nt=n(563),st=n(564),it=n(565),ot=n(566),rt=n(567),at=n(568),ct=n(569),ut=n(673),ht=n(570),lt=n(571),dt=n(15),pt=n(37),ft=n(7),_t=n(572),mt=n(573),gt=n(574),vt=n(575),yt=n(576),bt=n(577),xt=n(578),wt=n(579),Tt=n(580),Ot=n(581),St=n(582),Ct=n(583),kt=n(584),At=n(585),Dt=n(586),Mt=n(587),jt=n(588),Et=n(589),Rt=n(590),qt=n(668),It=n(591),Ft=n(669),Vt=n(592),Nt=n(593),Pt=n(594),Lt=n(595),zt=n(674),Bt=n(666),Wt=n(596),Ut=n(597),Gt=n(675),Yt=n(598),Qt=n(599),Zt=n(600),Xt=n(601),Ht=n(602),$t=n(603),Jt=n(604),Kt=n(605),te=n(606),ee=n(607),ne=n(608),se=n(609),ie=n(610),oe=n(611),re=n(612),ae=n(613),ce=n(614),ue=n(615),he=n(616),le=n(617),de=n(618),pe=n(619),fe=n(620),_e=n(10),me=n(621),ge=n(622),ve=n(623),ye=n(624),be=n(625),xe=n(626),we=n(627),Te=n(628),Oe=n(629),Se=n(630),Ce=n(631),ke=n(632),Ae=n(633),De=n(634),Me=n(635),je=n(636),Ee=n(637),Re=n(638),qe=n(639),Ie=n(640),Fe=n(641),Ve=n(642),Ne=n(643),Pe=n(644),Le=n(645),ze=n(646),Be=n(647),We=n(648),Ue=n(649),Ge=n(650),Ye=n(651),Qe=n(652),Ze=n(653),Xe=n(654),He=n(44),$e=n(655),Je=n(656),Ke=n(657),tn=n(658),en=n(659),nn=n(660),sn=n(661),on=n(662),rn=n(0),an=n(33),cn=n(34),un=n(8),hn=n(26),ln=n(6),dn=n(27),pn=n(9),fn=n(16),_n=n(23),mn=n(45),gn=n(19),vn=n(38),yn=n(32),bn=n(14),xn=n(663),wn=n(664),Tn=n(28);n(46),n(130);const On=Object(k.a)(new Map,new WeakMap),Sn=Object(Ke.a)(),Cn=Object(oe.a)(Sn),kn=Object(Tt.a)(Cn),An=Object(Vt.a)(Sn),Dn=Object(rt.a)(kn,An,Cn),Mn=Object(Pt.a)(Dn),jn=Object(qt.a)(On,dt.a,Mn),En=Object(it.a)(un.a),Rn=Object(Te.a)(un.a,En,gn.a),qn=Object(l.a)(jn,ln.a,Rn),In=new WeakMap,Fn=Object(at.a)(rn.g),Vn=new WeakMap,Nn=Object(K.a)(Tn.a),Pn=Object(yt.a)(An),Ln=Object(bt.a)(Sn),zn=Object(xt.a)(Sn),Bn=Object(y.a)(Object(o.a)(rn.b),In,On,Object(lt.a)(rn.h,cn.a,un.a,ln.a,dn.a,_n.a),dt.a,pt.a,_e.a,Object(W.a)(an.a,rn.h,un.a,ln.a,dn.a,Fn,_n.a,kn),Object(Q.a)(Vn,un.a,pn.a),Nn,Fn,Pn,Ln,zn,kn),Wn=Object(h.a)(Bn,qn,dt.a,jn,Fn,kn),Un=new WeakSet,Gn=Object(It.a)(Sn),Yn=Object(V.a)(new Uint32Array(1)),Qn=Object(tn.a)(Yn,dt.a),Zn=Object(en.a)(Yn),Xn=Object(d.a)(Un,On,_e.a,Gn,Cn,Object(De.a)(Gn),Qn,Zn),Hn=Object(Jt.a)(Mn),$n=Object(c.a)(Hn),Jn=Object(Pe.a)(Mn),Kn=Object(Le.a)(Mn),ts=Object(ze.a)(Mn),es=Object(sn.a)(Mn),ns=Object(Oe.a)(En,hn.a,gn.a),ss=Object(E.a)(ns),is=Object(Ft.a)($n,On,Mn,Object(je.a)(Mn),Object(Ee.a)(Cn),Object(Re.a)(Mn),Object(qe.a)(Mn),Jn,Kn,ts,wn.a,Object(nn.a)(vn.a),es),os=Object(we.a)(Object(ot.a)(hn.a),ns),rs=Object(f.a)(ss,is,ln.a,os,Rn),as=Object(b.a)(Object(r.a)(rn.d),Vn,rn.e,x.a,s.createCancelAndHoldAutomationEvent,s.createCancelScheduledValuesAutomationEvent,s.createExponentialRampToValueAutomationEvent,s.createLinearRampToValueAutomationEvent,s.createSetTargetAutomationEvent,s.createSetValueAutomationEvent,s.createSetValueCurveAutomationEvent,An),cs=Object(p.a)(Bn,rs,as,ft.a,is,Fn,kn,Tn.a),us=Object(m.a)(Bn,g.a,dt.a,ft.a,Object(Nt.a)(Hn,vn.a),Fn,kn,Rn),hs=Object(Wt.a)(Mn),ls=Object(C.a)(ss,hs,ln.a,os,Rn),ds=Object(S.a)(Bn,as,ls,pt.a,hs,Fn,kn),ps=Object(Rt.a)(fn.a,Ln),fs=Object(on.a)(ft.a,Mn,ps),_s=Object(Ut.a)(Mn,fs),ms=Object(D.a)(_s,ln.a,Rn),gs=Object(A.a)(Bn,ms,_s,Fn,kn),vs=Object(Gt.a)(Mn),ys=Object(j.a)(vs,ln.a,Rn),bs=Object(M.a)(Bn,ys,vs,Fn,kn),xs=Object(Qt.a)($n,is,Hn,ps),ws=Object(Yt.a)($n,On,Mn,xs,Jn,ts),Ts=Object(F.a)(ss,ws,ln.a,os,Rn),Os=Object(I.a)(Bn,as,Ts,ws,Fn,kn,Tn.a),Ss=Object(Xt.a)(Mn,Hn,ps),Cs=Object(Zt.a)(Mn,Ss,_e.a,vn.a),ks=Object(P.a)(Cs,ln.a,Rn),As=Object(N.a)(Bn,ks,Cs,Fn,kn),Ds=Object(Ht.a)(Mn),Ms=Object(G.a)(ss,Ds,ln.a,os,Rn),js=Object(U.a)(Bn,as,Ms,Ds,Fn,kn),Es=Object($t.a)(Mn,_e.a),Rs=Object(H.a)(ss,Es,ln.a,os,Rn),qs=Object(X.a)(Bn,as,Rs,Es,_e.a,Fn,kn),Is=Object(st.a)(ss,Hn,ln.a,os,Rn),Fs=Object(nt.a)(Bn,as,Is,Hn,Fn,kn),Vs=Object(he.a)(Mn),Ns=Object(te.a)(pt.a,ft.a,Vs,_e.a),Ps=Object(Se.a)(On,Hn,Vs,Object(Ze.a)(Hn,Cn)),Ls=Object(ht.a)(is,Mn,ln.a,Cn,Rn,Ps),zs=Object(Kt.a)(Mn,Ns),Bs=Object(ut.a)(Bn,zs,Ls,Fn,kn),Ws=Object(v.a)(as,_s,ws,Vs,kn),Us=new WeakMap,Gs=Object(jt.a)(us,Ws,Nn,kn,Us,Tn.a),Ys=Object(re.a)($n,On,Mn,Jn,Kn,ts,es),Qs=Object(ve.a)(ss,Ys,ln.a,os,Rn),Zs=Object(ge.a)(Bn,as,ft.a,Ys,Qs,Fn,kn,Tn.a),Xs=Object(q.a)(is),Hs=Object(fe.a)(Xs,ft.a,Mn,Hn,mn.a,ps),$s=Object(pe.a)(Xs,ft.a,Mn,Hs,mn.a,ps,vn.a),Js=Object(ce.a)(an.a,ft.a,Mn,_s,Hn,Vs,$s,_e.a,cn.a,ps),Ks=Object(ae.a)(Mn,Js),ti=Object(be.a)(ss,_s,ws,Hn,Ks,ln.a,Cn,os,Rn,Ps),ei=Object(ye.a)(Bn,as,Ks,ti,Fn,kn),ni=Object(ue.a)(Dn),si=Object(xe.a)(ni,Fn,new WeakSet),ii=Object(de.a)(_s,vs,Hn,$s,_e.a,ps),oi=Object(le.a)(Mn,ii,_e.a),ri=Object(Ae.a)(ss,oi,ln.a,os,Rn),ai=Object(ke.a)(Bn,as,oi,ri,Fn,kn),ci=Object(Je.a)($s,ln.a,Rn),ui=Object($e.a)(Bn,ft.a,$s,ci,Fn,kn),hi=Object(Ot.a)(Sn),li=Object(tt.a)(Sn),di=hi?Object(a.a)(_e.a,Object(J.a)(Sn),li,Object(et.a)(i.a),Dn,Fn,new WeakMap,new WeakMap,Sn):void 0,pi=Object(wt.a)(Pn,kn),fi=Object(B.a)(Un,On,z.a,$.a,new WeakSet,Fn,pi,kn,Cn,yn.a,bn.a,Qn,Zn),_i=Object(O.a)(di,Wn,Xn,cs,ds,gs,bs,Os,As,fi,js,qs,Fs,Bs,Gs,Zs,ei,si,ai,ui),mi=Object(ee.a)(Mn),gi=Object(Ct.a)(Bn,mi,Fn,kn),vi=Object(ne.a)(Mn,_e.a),yi=Object(kt.a)(Bn,vi,Fn,kn),bi=Object(se.a)(Mn),xi=Object(At.a)(Bn,bi,Fn,kn),wi=Object(ie.a)(ft.a,Mn,kn),Ti=Object(Dt.a)(Bn,wi,Fn),Oi=Object(_.a)(_i,ft.a,_e.a,He.a,gi,yi,xi,Ti,An),Si=Object(ct.a)(Us),Ci=Object(u.a)(Si),ki=Object(R.a)(dt.a),Ai=Object(Y.a)(Si),Di=Object(Z.a)(dt.a),Mi=Object(Bt.a)(In,ki,dt.a,ft.a,_s,vs,ws,Hn,Vs,_e.a,Di,li,ps),ji=Object(zt.a)(ft.a,Mn,Mi,Hn,_e.a,ps),Ei=Object(Lt.a)(Sn),Ri=Object(T.a)(ss,ki,is,_s,vs,ws,Hn,Ai,Di,li,ln.a,Ei,Cn,os,Rn,Ps),qi=hi?Object(w.a)(Ci,Bn,as,Ri,ji,Fn,kn,Ei,Tn.a):void 0,Ii=(Object(Mt.a)(ft.a,_e.a,He.a,Gs,An),Object(L.a)(_e.a,Cn)),Fi=Object(Ce.a)(Un,On,En,Si,Ps,yn.a,Qn,Zn),Vi=(Object(Et.a)(On,ft.a,Ii,Gs,Fi),Object(me.a)(_i,On,ft.a,Ii,Fi)),Ni=Object(_t.a)(rn.g,Pn),Pi=Object(mt.a)(rn.c,Ln),Li=Object(gt.a)(rn.e,zn),zi=Object(vt.a)(rn.g,kn),Bi=()=>Object(St.a)(On,Object(Me.a)(Cn),Object(Ie.a)(An),Object(Fe.a)(Cn),Object(Ve.a)(An),Object(Ne.a)(Cn),Object(Be.a)(Ei,Cn),Object(We.a)(Mn,Cn),Object(Ue.a)(Mn,Cn),Object(Ge.a)(Cn),Object(Ye.a)(Sn),Object(Qe.a)(An),Object(Xe.a)(Cn),xn.a)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{const e=new Uint32Array([1179011410,40,1163280727,544501094,16,131073,44100,176400,1048580,1635017060,4,0]);try{const n=t.decodeAudioData(e.buffer,()=>{});return void 0!==n&&(n.catch(()=>{}),!0)}catch{}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","IndexSizeError")}catch(t){return t.code=1,t.name="IndexSizeError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>{for(const e of t)if(n(e)){if(s)return!1;throw Error("The set contains at least one similar element.")}return t.add(e),!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(20);const o=t=>{if(s.a.has(t))throw new Error("The AudioNode is already stored.");s.a.add(t),Object(i.a)(t).forEach(t=>t(!0))}},function(t,e,n){!function(t,e,n,s){"use strict";e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e,n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n,s=s&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s;var i=function(t,e,n){return{endTime:e,insertTime:n,type:"exponentialRampToValue",value:t}},o=function(t,e,n){return{endTime:e,insertTime:n,type:"linearRampToValue",value:t}},r=function(t,e){return{startTime:e,type:"setValue",value:t}},a=function(t,e,n){return{duration:n,startTime:e,type:"setValueCurve",values:t}},c=function(t,e,n){var s=n.startTime,i=n.target,o=n.timeConstant;return i+(e-i)*Math.exp((s-t)/o)},u=function(t){return"exponentialRampToValue"===t.type},h=function(t){return"linearRampToValue"===t.type},l=function(t){return u(t)||h(t)},d=function(t){return"setValue"===t.type},p=function(t){return"setValueCurve"===t.type},f=function t(e,n,s,i){var o=e[n];return void 0===o?i:l(o)||d(o)?o.value:p(o)?o.values[o.values.length-1]:c(s,t(e,n-1,o.startTime,i),o)},_=function(t,e,n,s,i){return void 0===n?[s.insertTime,i]:l(n)?[n.endTime,n.value]:d(n)?[n.startTime,n.value]:p(n)?[n.startTime+n.duration,n.values[n.values.length-1]]:[n.startTime,f(t,e-1,n.startTime,i)]},m=function(t){return"cancelAndHold"===t.type},g=function(t){return"cancelScheduledValues"===t.type},v=function(t){return m(t)||g(t)?t.cancelTime:u(t)||h(t)?t.endTime:t.startTime},y=function(t,e,n,s){var i=s.endTime,o=s.value;return n===o?o:0=e})),s=this._automationEvents[n];if(-1!==n&&(this._automationEvents=this._automationEvents.slice(0,n)),m(t)){var c=this._automationEvents[this._automationEvents.length-1];if(void 0!==s&&l(s)){if(w(c))throw new Error("The internal list is malformed.");var d=p(c)?c.startTime+c.duration:v(c),f=p(c)?c.values[c.values.length-1]:c.value,_=u(s)?y(e,d,f,s):b(e,d,f,s),x=u(s)?i(_,e,this._currenTime):o(_,e,this._currenTime);this._automationEvents.push(x)}void 0!==c&&w(c)&&this._automationEvents.push(r(this.getValue(e),e)),void 0!==c&&p(c)&&c.startTime+c.duration>e&&(this._automationEvents[this._automationEvents.length-1]=a(new Float32Array([6,7]),c.startTime,e-c.startTime))}}else{var T=this._automationEvents.findIndex((function(t){return v(t)>e})),O=-1===T?this._automationEvents[this._automationEvents.length-1]:this._automationEvents[T-1];if(void 0!==O&&p(O)&&v(O)+O.duration>e)return!1;var S=u(t)?i(t.value,t.endTime,this._currenTime):h(t)?o(t.value,e,this._currenTime):t;if(-1===T)this._automationEvents.push(S);else{if(p(t)&&e+t.duration>v(this._automationEvents[T]))return!1;this._automationEvents.splice(T,0,S)}}return!0}},{key:"flush",value:function(t){var e=this._automationEvents.findIndex((function(e){return v(e)>t}));if(e>1){var n=this._automationEvents.slice(e-1),s=n[0];w(s)&&n.unshift(r(f(this._automationEvents,e-2,s.startTime,this._defaultValue),s.startTime)),this._automationEvents=n}}},{key:"getValue",value:function(t){if(0===this._automationEvents.length)return this._defaultValue;var n=this._automationEvents[this._automationEvents.length-1],s=this._automationEvents.findIndex((function(e){return v(e)>t})),i=this._automationEvents[s],o=v(n)<=t?n:this._automationEvents[s-1];if(void 0!==o&&w(o)&&(void 0===i||!l(i)||i.insertTime>t))return c(t,f(this._automationEvents,s-2,o.startTime,this._defaultValue),o);if(void 0!==o&&d(o)&&(void 0===i||!l(i)))return o.value;if(void 0!==o&&p(o)&&(void 0===i||!l(i)||o.startTime+o.duration>t))return ts.h.has(t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.i,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(20);const o=t=>{if(!s.a.has(t))throw new Error("The AudioNode is not stored.");s.a.delete(t),Object(i.a)(t).forEach(t=>t(!1))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(24);const i=t=>Object(s.a)(t[0])},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=t=>s.a.has(t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"context"in t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>"context"in t},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.d,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(0),i=n(9);const o=t=>Object(i.a)(s.e,t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s={value:t};return Object.defineProperties(n,{currentTarget:s,target:s}),"function"==typeof e?e.call(t,n):e.handleEvent.call(t,n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(15);const i=t=>{var e;t.getChannelData=(e=t.getChannelData,n=>{try{return e.call(t,n)}catch(t){if(12===t.code)throw Object(s.a)();throw t}})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.start=(e=t.start,(n=0,s=0,i)=>{if("number"==typeof i&&i<0||s<0||n<0)throw new RangeError("The parameters can't be negative.");e.call(t,n,s,i)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.stop=(e=t.stop,(n=0)=>{if(n<0)throw new RangeError("The parameter can't be negative.");e.call(t,n)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{try{t.copyToChannel(new Float32Array(1),0,-1)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(12);const i=(t,e,n,i)=>{if(Object(s.a)(e)){const s=e.inputs[i];return t.connect(s,n,0),[s,n,0]}return t.connect(e,n,i),[e,n,i]}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(12);const i=(t,e,n,i)=>{Object(s.a)(e)?t.disconnect(e.inputs[i],n,0):t.disconnect(e,n,i)}},function(t,e,n){"use strict";function s(t,e,n,s,i){if("function"==typeof t.copyFromChannel)0===e[n].byteLength&&(e[n]=new Float32Array(128)),t.copyFromChannel(e[n],s,i);else{const o=t.getChannelData(s);if(0===e[n].byteLength)e[n]=o.slice(i,i+128);else{const t=new Float32Array(o.buffer,i*Float32Array.BYTES_PER_ELEMENT,128);e[n].set(t)}}}n.d(e,"a",(function(){return s}))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>{const n=[];for(let s=0;s{try{return new DOMException("","InvalidAccessError")}catch(t){return t.code=15,t.name="InvalidAccessError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>{let i=Object.getPrototypeOf(t);for(;!i.hasOwnProperty(e);)i=Object.getPrototypeOf(i);const{get:o,set:r}=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,{get:n(o),set:s(r)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>void 0===t||"number"==typeof t||"string"==typeof t&&("balanced"===t||"interactive"===t||"playback"===t)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));class s{constructor(t){this._map=new Map(t)}get size(){return this._map.size}entries(){return this._map.entries()}forEach(t,e=null){return this._map.forEach((n,s)=>t.call(e,n,s,this))}get(t){return this._map.get(t)}has(t){return this._map.has(t)}keys(){return this._map.keys()}values(){return this._map.values()}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i)=>{"function"==typeof t.copyToChannel?0!==e[n].byteLength&&t.copyToChannel(e[n],s,i):0!==e[n].byteLength&&t.getChannelData(s).set(e[n],i)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a,c,u,h)=>{const l=u.length;let d=a;for(let a=0;anull===t?512:Math.max(512,Math.min(16384,Math.pow(2,Math.round(Math.log2(t*e)))))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","UnknownError")}catch(t){return t.name="UnknownError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{if(null===t)return!1;const e=t.length;return e%2!=0?0!==t[Math.floor(e/2)]:t[e/2-1]+t[e/2]!==0}},function(t,e,n){"use strict";n(47),n(48),n(49),n(50),n(51),n(52),n(53),n(54),n(55),n(56),n(57),n(58),n(59),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(67),n(68),n(69),n(70),n(71),n(72),n(73),n(74),n(75),n(76),n(77),n(78),n(79),n(80),n(81),n(82),n(83),n(84),n(85),n(86),n(87),n(88),n(89),n(90),n(91),n(92),n(93),n(94),n(95),n(96),n(97),n(98),n(99),n(100),n(101),n(102),n(103),n(104),n(105),n(106),n(107),n(108),n(109),n(110),n(111),n(112),n(113),n(114),n(115),n(116),n(117),n(118),n(119),n(120),n(121),n(122),n(123),n(124),n(125),n(126),n(127),n(128),n(129)},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";n(131),n(132),n(133),n(134),n(135),n(136),n(137),n(138),n(139),n(140),n(141),n(142),n(143),n(144),n(145),n(146),n(147),n(148),n(149),n(150),n(151),n(152),n(153),n(154),n(155),n(156),n(157),n(158),n(159),n(160),n(161),n(162),n(163),n(164),n(165),n(166),n(167),n(168),n(169),n(170),n(171),n(172),n(173),n(174),n(175),n(176),n(177),n(178),n(179),n(180),n(181),n(182),n(183),n(184),n(185),n(186),n(187),n(188),n(189),n(190),n(191),n(192),n(193),n(194),n(195),n(196),n(197),n(198),n(199),n(200),n(201),n(202),n(203),n(204),n(205),n(206),n(207),n(208),n(209),n(210),n(211),n(212),n(213),n(214),n(215),n(216),n(217),n(218),n(219),n(220),n(221),n(222),n(223),n(224),n(225),n(226),n(227),n(228),n(229),n(230),n(231),n(232),n(233),n(234),n(235),n(236),n(237),n(238),n(239),n(240),n(241),n(242),n(243),n(244),n(245),n(246),n(247),n(248),n(249),n(250),n(251),n(252),n(253),n(254),n(255),n(256),n(257),n(258),n(259),n(260),n(261),n(262),n(263),n(264),n(265),n(266),n(267),n(268),n(269),n(270),n(271),n(272),n(273),n(274),n(275),n(276),n(277),n(278),n(279),n(280),n(281),n(282),n(283),n(284),n(285),n(286),n(287),n(288),n(289),n(290),n(291),n(292),n(293),n(294),n(295),n(296),n(297),n(298),n(299),n(300),n(301),n(302),n(303),n(304),n(305),n(306),n(307),n(308),n(309),n(310),n(311),n(312),n(313),n(314),n(315),n(316),n(317),n(318),n(319),n(320),n(321),n(322),n(323),n(324),n(325),n(326),n(327),n(328),n(329),n(330),n(331),n(332),n(333),n(334),n(335),n(336),n(337),n(338),n(339),n(340),n(341),n(342),n(343),n(344),n(345),n(346),n(347),n(348),n(349),n(350),n(351),n(352),n(353),n(354),n(355),n(356),n(357),n(358),n(359),n(360),n(361),n(362),n(363),n(364),n(365),n(366),n(367),n(368),n(369),n(370),n(371),n(372),n(373),n(374),n(375),n(376),n(377),n(378),n(379),n(380),n(381),n(382),n(383),n(384),n(385),n(386),n(387),n(388),n(389),n(390),n(391),n(392),n(393),n(394),n(395),n(396),n(397),n(398),n(399),n(400),n(401),n(402),n(403),n(404),n(405),n(406),n(407),n(408),n(409),n(410),n(411),n(412),n(413),n(414),n(415),n(416),n(417),n(418),n(419),n(420),n(421),n(422),n(423),n(424),n(425),n(426),n(427),n(428),n(429),n(430),n(431),n(432),n(433),n(434),n(435),n(436),n(437),n(438),n(439),n(440),n(441),n(442),n(443),n(444),n(445),n(446),n(447),n(448),n(449),n(450),n(451),n(452),n(453),n(454),n(455),n(456),n(457),n(458),n(459),n(460),n(461),n(462),n(463),n(464),n(465),n(466),n(467),n(468),n(469),n(470),n(471),n(472),n(473),n(474),n(475),n(476),n(477),n(478),n(479),n(480),n(481),n(482),n(483),n(484),n(485),n(486),n(487),n(488),n(489),n(490),n(491),n(492),n(493),n(494),n(495),n(496),n(497),n(498),n(499),n(500),n(501),n(502),n(503),n(504),n(505),n(506),n(507),n(508),n(509),n(510),n(511),n(512),n(513),n(514)},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","AbortError")}catch(t){return t.code=20,t.name="AbortError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s)=>{const i=[];for(let t=0;t(e,n)=>{t.set(e,{activeInputs:new Set,passiveInputs:new WeakMap,renderer:n})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});n.connect(s).connect(s.context.destination);const i=()=>{n.removeEventListener("ended",i),n.disconnect(s),s.disconnect()};n.addEventListener("ended",i)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{t(e).add(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",fftSize:2048,maxDecibels:-30,minDecibels:-100,smoothingTimeConstant:.8},i=(t,e,n,i,o,r)=>class extends t{constructor(t,n=s){const a=o(t),c={...s,...n},u=i(a,c);super(t,!1,u,r(a)?e():null),this._nativeAnalyserNode=u}get fftSize(){return this._nativeAnalyserNode.fftSize}set fftSize(t){this._nativeAnalyserNode.fftSize=t}get frequencyBinCount(){return this._nativeAnalyserNode.frequencyBinCount}get maxDecibels(){return this._nativeAnalyserNode.maxDecibels}set maxDecibels(t){const e=this._nativeAnalyserNode.maxDecibels;if(this._nativeAnalyserNode.maxDecibels=t,!(t>this._nativeAnalyserNode.minDecibels))throw this._nativeAnalyserNode.maxDecibels=e,n()}get minDecibels(){return this._nativeAnalyserNode.minDecibels}set minDecibels(t){const e=this._nativeAnalyserNode.minDecibels;if(this._nativeAnalyserNode.minDecibels=t,!(this._nativeAnalyserNode.maxDecibels>t))throw this._nativeAnalyserNode.minDecibels=e,n()}get smoothingTimeConstant(){return this._nativeAnalyserNode.smoothingTimeConstant}set smoothingTimeConstant(t){this._nativeAnalyserNode.smoothingTimeConstant=t}getByteFrequencyData(t){this._nativeAnalyserNode.getByteFrequencyData(t)}getByteTimeDomainData(t){this._nativeAnalyserNode.getByteTimeDomainData(t)}getFloatFrequencyData(t){this._nativeAnalyserNode.getFloatFrequencyData(t)}getFloatTimeDomainData(t){this._nativeAnalyserNode.getFloatTimeDomainData(t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,fftSize:c.fftSize,maxDecibels:c.maxDecibels,minDecibels:c.minDecibels,smoothingTimeConstant:c.smoothingTimeConstant};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(32),i=n(29);const o={numberOfChannels:1},r=(t,e,n,r,a,c,u,h)=>{let l=null;return class d{constructor(d){if(null===a)throw new Error("Missing the native OfflineAudioContext constructor.");const{length:p,numberOfChannels:f,sampleRate:_}={...o,...d};null===l&&(l=new a(1,1,44100));const m=null!==r&&e(c,c)?new r({length:p,numberOfChannels:f,sampleRate:_}):l.createBuffer(f,p,_);if(0===m.numberOfChannels)throw n();return"function"!=typeof m.copyFromChannel?(u(m),Object(i.a)(m)):e(s.a,()=>Object(s.a)(m))||h(m),t.add(m),m}static[Symbol.hasInstance](e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===d.prototype||t.has(e)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(2),i=n(17),o=n(21);const r={buffer:null,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",loop:!1,loopEnd:0,loopStart:0,playbackRate:1},a=(t,e,n,a,c,u,h,l)=>class extends t{constructor(t,i=r){const o=u(t),a={...r,...i},l=c(o,a),d=h(o),p=d?e():null;super(t,!1,l,p),this._audioBufferSourceNodeRenderer=p,this._isBufferNullified=!1,this._isBufferSet=null!==i.buffer&&void 0!==i.buffer,this._nativeAudioBufferSourceNode=l,this._onended=null,this._playbackRate=n(this,d,l.playbackRate,s.b,s.a)}get buffer(){return this._isBufferNullified?null:this._nativeAudioBufferSourceNode.buffer}set buffer(t){try{this._nativeAudioBufferSourceNode.buffer=t}catch(e){if(null!==t||17!==e.code)throw e;if(null!==this._nativeAudioBufferSourceNode.buffer){const t=this._nativeAudioBufferSourceNode.buffer,e=t.numberOfChannels;for(let n=0;n{this._nativeAudioBufferSourceNode.removeEventListener("ended",t),setTimeout(()=>Object(o.a)(this),1e3)};this._nativeAudioBufferSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeAudioBufferSourceNode.stop(t),null!==this._audioBufferSourceNodeRenderer&&(this._audioBufferSourceNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null;return{set start(t){a=t},set stop(t){c=t},render(u,h,l){const d=r.get(h);return void 0!==d?Promise.resolve(d):(async(u,h,l)=>{let d=n(u);const p=Object(s.a)(d,h);if(!p){const t={buffer:d.buffer,channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,loop:d.loop,loopEnd:d.loopEnd,loopStart:d.loopStart,playbackRate:d.playbackRate.value};d=e(h,t),null!==a&&d.start(...a),null!==c&&d.stop(c)}return r.set(h,d),p?await t(h,u.playbackRate,d.playbackRate,l):await i(h,u.playbackRate,d.playbackRate,l),await o(u,h,d,l),d})(u,h,l)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(39);const i=(t,e,n,i,o,r,a,c,u)=>class extends t{constructor(t={}){if(null===u)throw new Error("Missing the native AudioContext constructor.");const e=new u(t);if(null===e)throw i();if(!Object(s.a)(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&e.sampleRate!==t.sampleRate)throw n();super(e,2);const{latencyHint:o}=t,{sampleRate:r}=e;if(this._baseLatency="number"==typeof e.baseLatency?e.baseLatency:"balanced"===o?512/r:"interactive"===o||void 0===o?256/r:"playback"===o?1024/r:128*Math.max(2,Math.min(128,Math.round(o*r/128)))/r,this._nativeAudioContext=e,this._state=null,"running"===e.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),e.removeEventListener("statechange",t)};e.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw e()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close())}createMediaElementSource(t){return new o(this,{mediaElement:t})}createMediaStreamDestination(){return new r(this)}createMediaStreamSource(t){return new a(this,{mediaStream:t})}createMediaStreamTrackSource(t){return new c(this,{mediaStreamTrack:t})}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(t=>{if(void 0===t||15===t.code)throw e();throw t})}suspend(){return this._nativeAudioContext.suspend().catch(t=>{if(void 0===t)throw e();throw t})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a)=>class extends t{constructor(t,n){const s=o(t),c=r(s),u=i(s,n,c);super(t,!1,u,c?e(a):null),this._isNodeOfNativeOfflineAudioContext=c,this._nativeAudioDestinationNode=u}get channelCount(){return this._nativeAudioDestinationNode.channelCount}set channelCount(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();if(t>this._nativeAudioDestinationNode.maxChannelCount)throw n();this._nativeAudioDestinationNode.channelCount=t}get channelCountMode(){return this._nativeAudioDestinationNode.channelCountMode}set channelCountMode(t){if(this._isNodeOfNativeOfflineAudioContext)throw s();this._nativeAudioDestinationNode.channelCountMode=t}get maxChannelCount(){return this._nativeAudioDestinationNode.maxChannelCount}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{let e=null;return{render:(n,s,i)=>(null===e&&(e=(async(e,n,s)=>{const i=n.destination;return await t(e,n,i,s),i})(n,s,i)),e)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(2);const i=(t,e,n,i,o)=>(r,a)=>{const c=a.listener,{forwardX:u,forwardY:h,forwardZ:l,positionX:d,positionY:p,positionZ:f,upX:_,upY:m,upZ:g}=void 0===c.forwardX?(()=>{const u=e(a,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:9}),h=o(a),l=i(a,256,9,0),d=(e,i)=>{const o=n(a,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:i});return o.connect(u,0,e),o.start(),Object.defineProperty(o.offset,"defaultValue",{get:()=>i}),t({context:r},h,o.offset,s.b,s.a)};let p=[0,0,-1,0,1,0],f=[0,0,0];return l.onaudioprocess=({inputBuffer:t})=>{const e=[t.getChannelData(0)[0],t.getChannelData(1)[0],t.getChannelData(2)[0],t.getChannelData(3)[0],t.getChannelData(4)[0],t.getChannelData(5)[0]];e.some((t,e)=>t!==p[e])&&(c.setOrientation(...e),p=e);const n=[t.getChannelData(6)[0],t.getChannelData(7)[0],t.getChannelData(8)[0]];n.some((t,e)=>t!==f[e])&&(c.setPosition(...n),f=n)},u.connect(l),{forwardX:d(0,0),forwardY:d(1,0),forwardZ:d(2,-1),positionX:d(6,0),positionY:d(7,0),positionZ:d(8,0),upX:d(3,0),upY:d(4,1),upZ:d(5,0)}})():c;return{get forwardX(){return u},get forwardY(){return h},get forwardZ(){return l},get positionX(){return d},get positionY(){return p},get positionZ(){return f},get upX(){return _},get upY(){return m},get upZ(){return g}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(18);const i=(t,e,n,i,o,r,a,c,u,h,l,d)=>(p,f,_,m=null,g=null)=>{const v=new s.AutomationEventList(_.defaultValue),y=f?i(v):null,b={get defaultValue(){return _.defaultValue},get maxValue(){return null===m?_.maxValue:m},get minValue(){return null===g?_.minValue:g},get value(){return _.value},set value(t){_.value=t,b.setValueAtTime(t,p.context.currentTime)},cancelAndHoldAtTime(t){if("function"==typeof _.cancelAndHoldAtTime)null===y&&v.flush(p.context.currentTime),v.add(o(t)),_.cancelAndHoldAtTime(t);else{const e=Array.from(v).pop();null===y&&v.flush(p.context.currentTime),v.add(o(t));const n=Array.from(v).pop();_.cancelScheduledValues(t),e!==n&&void 0!==n&&("exponentialRampToValue"===n.type?_.exponentialRampToValueAtTime(n.value,n.endTime):"linearRampToValue"===n.type?_.linearRampToValueAtTime(n.value,n.endTime):"setValue"===n.type?_.setValueAtTime(n.value,n.startTime):"setValueCurve"===n.type&&_.setValueCurveAtTime(n.values,n.startTime,n.duration))}return b},cancelScheduledValues:t=>(null===y&&v.flush(p.context.currentTime),v.add(r(t)),_.cancelScheduledValues(t),b),exponentialRampToValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(a(t,e)),_.exponentialRampToValueAtTime(t,e),b),linearRampToValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(c(t,e)),_.linearRampToValueAtTime(t,e),b),setTargetAtTime:(t,e,n)=>(null===y&&v.flush(p.context.currentTime),v.add(u(t,e,n)),_.setTargetAtTime(t,e,n),b),setValueAtTime:(t,e)=>(null===y&&v.flush(p.context.currentTime),v.add(h(t,e)),_.setValueAtTime(t,e),b),setValueCurveAtTime(t,e,n){if(null!==d&&"webkitAudioContext"===d.name){const s=e+n,i=p.context.sampleRate,o=Math.ceil(e*i),r=Math.floor(s*i),a=r-o,c=new Float32Array(a);for(let s=0;s({replay(e){for(const n of t)if("exponentialRampToValue"===n.type){const{endTime:t,value:s}=n;e.exponentialRampToValueAtTime(s,t)}else if("linearRampToValue"===n.type){const{endTime:t,value:s}=n;e.linearRampToValueAtTime(s,t)}else if("setTarget"===n.type){const{startTime:t,target:s,timeConstant:i}=n;e.setTargetAtTime(s,t,i)}else if("setValue"===n.type){const{startTime:t,value:s}=n;e.setValueAtTime(s,t)}else{if("setValueCurve"!==n.type)throw new Error("Can't apply an unknown automation.");{const{duration:t,startTime:s,values:i}=n;e.setValueCurveAtTime(i,s,t)}}}})},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(0),i=n(40);const o={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:void 0,parameterData:{},processorOptions:{}},r=t=>{const e=[];for(let n=0;nclass extends e{constructor(e,d,p=o){const f=u(e),_=h(f),m=(t=>({...t,outputChannelCount:void 0!==t.outputChannelCount?t.outputChannelCount:1===t.numberOfInputs&&1===t.numberOfOutputs?[t.channelCount]:r(t.numberOfOutputs)}))({...o,...p}),g=s.j.get(f),v=void 0===g?void 0:g.get(d),y=c(f,_?null:e.baseLatency,l,d,v,m);super(e,!0,y,_?a(d,m,v):null);const b=[];y.parameters.forEach((t,e)=>{const s=n(this,_,t);b.push([e,s])}),this._nativeAudioWorkletNode=y,this._onprocessorerror=null,this._parameters=new i.a(b),_&&t(f,this)}get onprocessorerror(){return this._onprocessorerror}set onprocessorerror(t){const e="function"==typeof t?d(this,t):null;this._nativeAudioWorkletNode.onprocessorerror=e;const n=this._nativeAudioWorkletNode.onprocessorerror;this._onprocessorerror=null!==n&&n===e?t:n}get parameters(){return null===this._parameters?this._nativeAudioWorkletNode.parameters:this._parameters}get port(){return this._nativeAudioWorkletNode.port}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o,r,a,c,u,h,l,d,p,f,_,m,g,v,y)=>class extends f{constructor(e,n){super(e,n),this._nativeContext=e,this._audioWorklet=void 0===t?void 0:{addModule:(e,n)=>t(this,e,n)}}get audioWorklet(){return this._audioWorklet}createAnalyser(){return new e(this)}createBiquadFilter(){return new i(this)}createBuffer(t,e,s){return new n({length:e,numberOfChannels:t,sampleRate:s})}createBufferSource(){return new s(this)}createChannelMerger(t=6){return new o(this,{numberOfInputs:t})}createChannelSplitter(t=6){return new r(this,{numberOfOutputs:t})}createConstantSource(){return new a(this)}createConvolver(){return new c(this)}createDelay(t=1){return new h(this,{maxDelayTime:t})}createDynamicsCompressor(){return new l(this)}createGain(){return new d(this)}createIIRFilter(t,e){return new p(this,{feedback:e,feedforward:t})}createOscillator(){return new _(this)}createPanner(){return new m(this)}createPeriodicWave(t,e,n={disableNormalization:!1}){return new g(this,{...n,imag:e,real:t})}createStereoPanner(){return new v(this)}createWaveShaper(){return new y(this)}decodeAudioData(t,e,n){return u(this._nativeContext,t).then(t=>("function"==typeof e&&e(t),t)).catch(t=>{throw"function"==typeof n&&n(t),t})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={Q:1,channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:350,gain:0,type:"lowpass"},o=(t,e,n,o,r,a,c)=>class extends t{constructor(t,o=i){const u=a(t),h={...i,...o},l=r(u,h),d=c(u);super(t,!1,l,d?n():null),this._Q=e(this,d,l.Q,s.b,s.a),this._detune=e(this,d,l.detune,1200*Math.log2(s.b),-1200*Math.log2(s.b)),this._frequency=e(this,d,l.frequency,t.sampleRate/2,0),this._gain=e(this,d,l.gain,40*Math.log10(s.b),s.a),this._nativeBiquadFilterNode=l}get detune(){return this._detune}get frequency(){return this._frequency}get gain(){return this._gain}get Q(){return this._Q}get type(){return this._nativeBiquadFilterNode.type}set type(t){this._nativeBiquadFilterNode.type=t}getFrequencyResponse(t,e,n){if(this._nativeBiquadFilterNode.getFrequencyResponse(t,e,n),t.length!==e.length||e.length!==n.length)throw o()}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={Q:h.Q.value,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,detune:h.detune.value,frequency:h.frequency.value,gain:h.gain.value,type:h.type};h=e(c,t)}return r.set(c,h),l?(await t(c,a.Q,h.Q,u),await t(c,a.detune,h.detune,u),await t(c,a.frequency,h.frequency,u),await t(c,a.gain,h.gain,u)):(await i(c,a.Q,h.Q,u),await i(c,a.detune,h.detune,u),await i(c,a.frequency,h.frequency,u),await i(c,a.gain,h.gain,u)),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s)=>{const i=e.get(n);if(void 0!==i)return i;const o=t.get(n);if(void 0!==o)return o;try{const i=s();return i instanceof Promise?(t.set(n,i),i.catch(()=>!1).then(s=>(t.delete(n),e.set(n,s),s))):(e.set(n,i),i)}catch{return e.set(n,!1),!1}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c={...s,...r};super(t,!1,n(a,c),o(a)?e():null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,numberOfInputs:c.numberOfInputs};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:6,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:6},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c=(t=>({...t,channelCount:t.numberOfOutputs}))({...s,...r});super(t,!1,n(a,c),o(a)?e():null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n)=>()=>{const i=new WeakMap;return{render(o,r,a){const c=i.get(r);return void 0!==c?Promise.resolve(c):(async(o,r,a)=>{let c=e(o);if(!Object(s.a)(c,r)){const e={channelCount:c.channelCount,channelCountMode:c.channelCountMode,channelInterpretation:c.channelInterpretation,numberOfOutputs:c.numberOfOutputs};c=t(r,e)}return i.set(r,c),await n(o,r,c,a),c})(o,r,a)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s,i)=>t(n,e,s,i)},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(25);const i=t=>(e,n,i=0,o=0)=>{const r=e[i];if(void 0===r)throw t();return Object(s.a)(n)?r.connect(n,0,o):r.connect(n,0)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e),i=e.createBuffer(1,2,e.sampleRate);return s.buffer=i,s.loop=!0,s.connect(n),s.start(),()=>{s.stop(),s.disconnect(n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(2),i=n(17),o=n(21);const r={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",offset:1},a=(t,e,n,a,c,u,h)=>class extends t{constructor(t,i=r){const o=c(t),h={...r,...i},l=a(o,h),d=u(o),p=d?n():null;super(t,!1,l,p),this._constantSourceNodeRenderer=p,this._nativeConstantSourceNode=l,this._offset=e(this,d,l.offset,s.b,s.a),this._onended=null}get offset(){return this._offset}get onended(){return this._onended}set onended(t){const e="function"==typeof t?h(this,t):null;this._nativeConstantSourceNode.onended=e;const n=this._nativeConstantSourceNode.onended;this._onended=null!==n&&n===e?t:n}start(t=0){if(this._nativeConstantSourceNode.start(t),null!==this._constantSourceNodeRenderer)this._constantSourceNodeRenderer.start=t;else{Object(i.a)(this);const t=()=>{this._nativeConstantSourceNode.removeEventListener("ended",t),setTimeout(()=>Object(o.a)(this),1e3)};this._nativeConstantSourceNode.addEventListener("ended",t)}}stop(t=0){this._nativeConstantSourceNode.stop(t),null!==this._constantSourceNodeRenderer&&(this._constantSourceNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null;return{set start(t){a=t},set stop(t){c=t},render(u,h,l){const d=r.get(h);return void 0!==d?Promise.resolve(d):(async(u,h,l)=>{let d=n(u);const p=Object(s.a)(d,h);if(!p){const t={channelCount:d.channelCount,channelCountMode:d.channelCountMode,channelInterpretation:d.channelInterpretation,offset:d.offset.value};d=e(h,t),null!==a&&d.start(a),null!==c&&d.stop(c)}return r.set(h,d),p?await t(h,u.offset,d.offset,l):await i(h,u.offset,d.offset,l),await o(u,h,d,l),d})(u,h,l)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>(t[0]=e,t[0])},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={buffer:null,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",disableNormalization:!1},i=(t,e,n,i,o)=>class extends t{constructor(t,r=s){const a=i(t),c={...s,...r},u=n(a,c);super(t,!1,u,o(a)?e():null),this._isBufferNullified=!1,this._nativeConvolverNode=u}get buffer(){return this._isBufferNullified?null:this._nativeConvolverNode.buffer}set buffer(t){if(this._nativeConvolverNode.buffer=t,null===t&&null!==this._nativeConvolverNode.buffer){const t=this._nativeConvolverNode.context;this._nativeConvolverNode.buffer=t.createBuffer(1,1,t.sampleRate),this._isBufferNullified=!0}else this._isBufferNullified=!1}get normalize(){return this._nativeConvolverNode.normalize}set normalize(t){this._nativeConvolverNode.normalize=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n)=>()=>{const o=new WeakMap;return{render(r,a,c){const u=o.get(a);return void 0!==u?Promise.resolve(u):(async(r,a,c)=>{let u=e(r);if(!Object(i.a)(u,a)){const e={buffer:u.buffer,channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,disableNormalization:!u.normalize};u=t(a,e)}return o.set(a,u),Object(s.a)(u)?await n(r,a,u.inputs[0],c):await n(r,a,u,c),u})(r,a,c)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{if(null===e)throw new Error("Missing the native OfflineAudioContext constructor.");try{return new e(n,s,i)}catch(e){if("IndexSizeError"===e.name||"SyntaxError"===e.name)throw t();throw e}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","DataCloneError")}catch(t){return t.code=25,t.name="DataCloneError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(22);const i=(t,e,n,i,o,r,a,c)=>(u,h)=>{const l=e.get(u);if(void 0===l)throw new Error("Missing the expected cycle count.");const d=r(u.context),p=c(d);if(l===h){if(e.delete(u),!p&&a(u)){const e=i(u),{outputs:r}=n(u);for(const n of r)if(Object(s.a)(n)){const s=i(n[0]);t(e,s,n[1],n[2])}else{const t=o(n[0]);e.connect(t,n[1])}}}else e.set(u,l-h)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",delayTime:0,maxDelayTime:1},i=(t,e,n,i,o,r)=>class extends t{constructor(t,a=s){const c=o(t),u={...s,...a},h=i(c,u),l=r(c);super(t,!1,h,l?n(u.maxDelayTime):null),this._delayTime=e(this,l,h.delayTime,u.maxDelayTime,0)}get delayTime(){return this._delayTime}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>r=>{const a=new WeakMap;return{render(c,u,h){const l=a.get(u);return void 0!==l?Promise.resolve(l):(async(c,u,h)=>{let l=n(c);const d=Object(s.a)(l,u);if(!d){const t={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,delayTime:l.delayTime.value,maxDelayTime:r};l=e(u,t)}return a.set(u,l),d?await t(u,c.delayTime,l.delayTime,h):await i(u,c.delayTime,l.delayTime,h),await o(c,u,l,h),l})(c,u,h)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{t(e).delete(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(25);const i=(t,e,n)=>{const s=e[n];if(void 0===s)throw t();return s},o=t=>(e,n,o,r=0)=>void 0===n?e.forEach(t=>t.disconnect()):"number"==typeof n?i(t,e,n).disconnect():Object(s.a)(n)?void 0===o?e.forEach(t=>t.disconnect(n)):void 0===r?i(t,e,o).disconnect(n,0):i(t,e,o).disconnect(n,0,r):void 0===o?e.forEach(t=>t.disconnect(n)):i(t,e,o).disconnect(n,0)},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={attack:.003,channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",knee:30,ratio:12,release:.25,threshold:-24},i=(t,e,n,i,o,r,a)=>class extends t{constructor(t,o=s){const c=r(t),u={...s,...o},h=i(c,u),l=a(c);super(t,!1,h,l?n():null),this._attack=e(this,l,h.attack,1,0),this._knee=e(this,l,h.knee,40,0),this._nativeDynamicsCompressorNode=h,this._ratio=e(this,l,h.ratio,20,1),this._release=e(this,l,h.release,1,0),this._threshold=e(this,l,h.threshold,0,-100)}get attack(){return this._attack}get channelCount(){return this._nativeDynamicsCompressorNode.channelCount}set channelCount(t){const e=this._nativeDynamicsCompressorNode.channelCount;if(this._nativeDynamicsCompressorNode.channelCount=t,t>2)throw this._nativeDynamicsCompressorNode.channelCount=e,o()}get channelCountMode(){return this._nativeDynamicsCompressorNode.channelCountMode}set channelCountMode(t){const e=this._nativeDynamicsCompressorNode.channelCountMode;if(this._nativeDynamicsCompressorNode.channelCountMode=t,"max"===t)throw this._nativeDynamicsCompressorNode.channelCountMode=e,o()}get knee(){return this._knee}get ratio(){return this._ratio}get reduction(){return"number"==typeof this._nativeDynamicsCompressorNode.reduction.value?this._nativeDynamicsCompressorNode.reduction.value:this._nativeDynamicsCompressorNode.reduction}get release(){return this._release}get threshold(){return this._threshold}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={attack:h.attack.value,channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,knee:h.knee.value,ratio:h.ratio.value,release:h.release.value,threshold:h.threshold.value};h=e(c,t)}return r.set(c,h),l?(await t(c,a.attack,h.attack,u),await t(c,a.knee,h.knee,u),await t(c,a.ratio,h.ratio,u),await t(c,a.release,h.release,u),await t(c,a.threshold,h.threshold,u)):(await i(c,a.attack,h.attack,u),await i(c,a.knee,h.knee,u),await i(c,a.ratio,h.ratio,u),await i(c,a.release,h.release,u),await i(c,a.threshold,h.threshold,u)),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>{try{return new DOMException("","EncodingError")}catch(t){return t.code=0,t.name="EncodingError",t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>new Promise((n,s)=>{if(null===t)return void s(new SyntaxError);const i=t.document.head;if(null===i)s(new SyntaxError);else{const o=t.document.createElement("script"),r=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(r),c=t.onerror,u=()=>{t.onerror=c,URL.revokeObjectURL(a)};t.onerror=(e,n,i,o,r)=>n===a||n===t.location.href&&1===i&&1===o?(u(),s(r),!1):null!==c?c(e,n,i,o,r):void 0,o.onerror=()=>{u(),s(new SyntaxError)},o.onload=()=>{u(),n()},o.src=a,o.type="module",i.appendChild(o)}})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>class{constructor(t){this._nativeEventTarget=t,this._listeners=new WeakMap}addEventListener(e,n,s){if(null!==n){let i=this._listeners.get(n);void 0===i&&(i=t(this,n),"function"==typeof n&&this._listeners.set(n,i)),this._nativeEventTarget.addEventListener(e,i,s)}}dispatchEvent(t){return this._nativeEventTarget.dispatchEvent(t)}removeEventListener(t,e,n){const s=null===e?void 0:this._listeners.get(e);this._nativeEventTarget.removeEventListener(t,void 0===s?null:s,n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s)=>{Object.defineProperties(t,{currentFrame:{configurable:!0,get:()=>Math.round(e*n)},currentTime:{configurable:!0,get:()=>e}});try{return s()}finally{null!==t&&(delete t.currentFrame,delete t.currentTime)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>async e=>{try{const t=await fetch(e);if(t.ok)return t.text()}catch{}throw t()}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",gain:1},o=(t,e,n,o,r,a)=>class extends t{constructor(t,c=i){const u=r(t),h={...i,...c},l=o(u,h),d=a(u);super(t,!1,l,d?n():null),this._gain=e(this,d,l.gain,s.b,s.a)}get gain(){return this._gain}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;return{render(a,c,u){const h=r.get(c);return void 0!==h?Promise.resolve(h):(async(a,c,u)=>{let h=n(a);const l=Object(s.a)(h,c);if(!l){const t={channelCount:h.channelCount,channelCountMode:h.channelCountMode,channelInterpretation:h.channelInterpretation,gain:h.gain.value};h=e(c,t)}return r.set(c,h),l?await t(c,a.gain,h.gain,u):await i(c,a.gain,h.gain,u),await o(a,c,h,u),h})(a,c,u)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioNode in the audio graph.");return n.renderer}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e);if(null===n.renderer)throw new Error("Missing the renderer of the given AudioParam in the audio graph.");return n.renderer}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=(t,e,n)=>i=>{if("closed"===i.state&&null!==e&&"webkitAudioContext"!==e.name){if(!t(i)){const t=s.f.get(i);if(void 0!==t)return t;const n=new e;return s.f.set(i,n),n}{const t=s.f.get(i);if(void 0!==t)return t;if(null!==n){const t=new n(1,1,44100);return s.f.set(i,t),t}}}return null}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(7);const i=t=>e=>{const n=t.get(e);if(void 0===n)throw Object(s.a)();return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t.get(e);if(void 0===n)throw new Error("The context has no set of AudioWorkletNodes.");return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(42),i=n(3);const o=(t,e,n,o,r,a)=>(c,u)=>{const h=new WeakMap;let l=null;const d=async(d,p,f)=>{let _=null,m=n(d);const g=Object(i.a)(m,p);if(void 0===p.createIIRFilter?_=t(p):g||(m=e(p,t=>t.createIIRFilter(u,c))),h.set(p,null===_?m:_),null!==_){if(null===l){if(null===o)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new o(d.context.destination.channelCount,d.context.length,p.sampleRate);l=(async()=>(await r(d,t,t.destination,f),((t,e,n,i)=>{const o=n.length,r=i.length,a=Math.min(o,r);if(1!==n[0]){for(let t=0;ta=>(c,u)=>{const h=t.get(c);if(void 0===h){if(!a&&r(c)){const t=i(c),{outputs:r}=n(c);for(const n of r)if(Object(s.a)(n)){const s=i(n[0]);e(t,s,n[1],n[2])}else{const e=o(n[0]);t.disconnect(e,n[1])}}t.set(c,u)}else t.set(c,h+u)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t.has(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t.has(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{const s=t.get(n);return e(s)||e(n)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&e instanceof t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&"function"==typeof t.AudioNode&&e instanceof t.AudioNode},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&"function"==typeof t.AudioParam&&e instanceof t.AudioParam},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>t(n)||e(n)},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>null!==t&&e instanceof t},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null!==t&&t.isSecureContext},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=async(t,e,n,s,i,o,r,a,c,u,h,l,d,p)=>{if(t(e,e)&&t(n,n)&&t(i,i)&&t(o,o)&&t(a,a)&&t(c,c)&&t(u,u)&&t(h,h)&&t(l,l)){return(await Promise.all([t(s,s),t(r,r),t(d,d),t(p,p)])).every(t=>t)}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>class extends t{constructor(t,i){const o=n(t),r=e(o,i);if(s(o))throw TypeError();super(t,!0,r,null),this._mediaElement=i.mediaElement,this._nativeMediaElementAudioSourceNode=r}get mediaElement(){return void 0===this._nativeMediaElementAudioSourceNode.mediaElement?this._mediaElement:this._nativeMediaElementAudioSourceNode.mediaElement}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers"},i=(t,e,n,i)=>class extends t{constructor(t,o=s){const r=n(t);if(i(r))throw new TypeError;const a={...s,...o},c=e(r,a);super(t,!1,c,null),this._nativeMediaStreamAudioDestinationNode=c}get stream(){return this._nativeMediaStreamAudioDestinationNode.stream}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s)=>class extends t{constructor(t,i){const o=n(t),r=e(o,i);if(s(o))throw new TypeError;super(t,!0,r,null),this._nativeMediaStreamAudioSourceNode=r}get mediaStream(){return this._nativeMediaStreamAudioSourceNode.mediaStream}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>class extends t{constructor(t,s){const i=n(t);super(t,!0,e(i,s),null)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(39);const i=(t,e,n,i,o)=>class extends i{constructor(t={}){if(null===o)throw new Error("Missing the native AudioContext constructor.");const i=new o(t);if(null===i)throw n();if(!Object(s.a)(t.latencyHint))throw new TypeError(`The provided value '${t.latencyHint}' is not a valid enum value of type AudioContextLatencyCategory.`);if(void 0!==t.sampleRate&&i.sampleRate!==t.sampleRate)throw e();super(i,2);const{latencyHint:r}=t,{sampleRate:a}=i;if(this._baseLatency="number"==typeof i.baseLatency?i.baseLatency:"balanced"===r?512/a:"interactive"===r||void 0===r?256/a:"playback"===r?1024/a:128*Math.max(2,Math.min(128,Math.round(r*a/128)))/a,this._nativeAudioContext=i,this._state=null,"running"===i.state){this._state="suspended";const t=()=>{"suspended"===this._state&&(this._state=null),i.removeEventListener("statechange",t)};i.addEventListener("statechange",t)}}get baseLatency(){return this._baseLatency}get state(){return null!==this._state?this._state:this._nativeAudioContext.state}close(){return"closed"===this.state?this._nativeAudioContext.close().then(()=>{throw t()}):("suspended"===this._state&&(this._state=null),this._nativeAudioContext.close())}resume(){return"suspended"===this._state?new Promise((t,e)=>{const n=()=>{this._nativeAudioContext.removeEventListener("statechange",n),"running"===this._nativeAudioContext.state?t():this.resume().then(t,e)};this._nativeAudioContext.addEventListener("statechange",n)}):this._nativeAudioContext.resume().catch(e=>{if(void 0===e||15===e.code)throw t();throw e})}suspend(){return this._nativeAudioContext.suspend().catch(e=>{if(void 0===e)throw t();throw e})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(0);const i=(t,e,n,i,o,r)=>class extends n{constructor(n,r){super(n),this._nativeContext=n,s.g.set(this,n);const a=n.sampleRate;Object.defineProperty(n,"sampleRate",{get:()=>a}),i(n)&&o.set(n,new Set),this._destination=new t(this,r),this._listener=e(this,n),this._onstatechange=null}get currentTime(){return this._nativeContext.currentTime}get destination(){return this._destination}get listener(){return this._listener}get onstatechange(){return this._onstatechange}set onstatechange(t){const e="function"==typeof t?r(this,t):null;this._nativeContext.onstatechange=e;const n=this._nativeContext.onstatechange;this._onstatechange=null!==n&&n===e?t:n}get sampleRate(){return this._nativeContext.sampleRate}get state(){return this._nativeContext.state}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(14);const i={numberOfChannels:1},o=(t,e,n,o,r)=>class extends o{constructor(e){const{length:o,numberOfChannels:r,sampleRate:a}={...i,...e},c=n(r,o,a);t(s.a,()=>Object(s.a)(c))||c.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(c.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(c,r),this._length=o,this._nativeOfflineAudioContext=c,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(e()):(this._state="running",r(this.destination,this._nativeOfflineAudioContext).then(t=>(this._state=null,t)).catch(t=>{throw this._state=null,t}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{const o=new Set;var r,a;return n.connect=(r=n.connect,(i,a=0,c=0)=>{const u=0===o.size;if(e(i))return r.call(n,i,a,c),t(o,[i,a,c],t=>t[0]===i&&t[1]===a&&t[2]===c,!0),u&&s(),i;r.call(n,i,a),t(o,[i,a],t=>t[0]===i&&t[1]===a,!0),u&&s()}),n.disconnect=(a=n.disconnect,(t,s,r)=>{const c=o.size>0;if(void 0===t)a.apply(n),o.clear();else if("number"==typeof t){a.call(n,t);for(const e of o)e[1]===t&&o.delete(e)}else{e(t)?a.call(n,t,s,r):a.call(n,t,s);for(const e of o)e[0]!==t||void 0!==s&&e[1]!==s||void 0!==r&&e[2]!==r||o.delete(e)}const u=0===o.size;c&&u&&i()}),n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioBuffer")?t.AudioBuffer:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioContext")?t.AudioContext:t.hasOwnProperty("webkitAudioContext")?t.webkitAudioContext:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i)=>{const o=n.destination;if(o.channelCount!==s)try{o.channelCount=s}catch{}i&&"explicit"!==o.channelCountMode&&(o.channelCountMode="explicit"),0===o.maxChannelCount&&Object.defineProperty(o,"maxChannelCount",{value:s});const r=t(n,{channelCount:s,channelCountMode:o.channelCountMode,channelInterpretation:o.channelInterpretation,gain:1});return e(r,"channelCount",t=>()=>t.call(r),t=>e=>{t.call(r,e);try{o.channelCount=e}catch(t){if(e>o.maxChannelCount)throw t}}),e(r,"channelCountMode",t=>()=>t.call(r),t=>e=>{t.call(r,e),o.channelCountMode=e}),e(r,"channelInterpretation",t=>()=>t.call(r),t=>e=>{t.call(r,e),o.channelInterpretation=e}),Object.defineProperty(r,"maxChannelCount",{get:()=>o.maxChannelCount}),r.connect(o),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>{const s=t(e);return n(null!==s?s:e)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("AudioWorkletNode")?t.AudioWorkletNode:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(5),i=n(4),o=n(1);const r=t=>(e,n)=>{const r=t(e,t=>t.createBiquadFilter());return Object(o.a)(r,n),Object(s.a)(r,n,"Q"),Object(s.a)(r,n,"detune"),Object(s.a)(r,n,"frequency"),Object(s.a)(r,n,"gain"),Object(i.a)(r,n,"type"),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i)=>{const o=t(n,t=>t.createChannelMerger(i.numberOfInputs));return 1!==o.channelCount&&"explicit"!==o.channelCountMode&&e(n,o),Object(s.a)(o,i),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return a}));var s=n(5),i=n(1),o=n(30),r=n(31);const a=(t,e,n,a,c,u)=>(h,l)=>{if(void 0===h.createConstantSource)return a(h,l);const d=n(h,t=>t.createConstantSource());return Object(i.a)(d,l),Object(s.a)(d,l,"offset"),e(c,()=>c(h))||Object(o.a)(d),e(u,()=>u(h))||Object(r.a)(d),t(h,d),d}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=(t,e,n,i)=>(o,{offset:r,...a})=>{const c=o.createBuffer(1,2,o.sampleRate),u=e(o),h=n(o,{...a,gain:r}),l=c.getChannelData(0);l[0]=1,l[1]=1,u.buffer=c,u.loop=!0;const d={get bufferSize(){},get channelCount(){return h.channelCount},set channelCount(t){h.channelCount=t},get channelCountMode(){return h.channelCountMode},set channelCountMode(t){h.channelCountMode=t},get channelInterpretation(){return h.channelInterpretation},set channelInterpretation(t){h.channelInterpretation=t},get context(){return h.context},get inputs(){return[]},get numberOfInputs(){return u.numberOfInputs},get numberOfOutputs(){return h.numberOfOutputs},get offset(){return h.gain},get onended(){return u.onended},set onended(t){u.onended=t},addEventListener:(...t)=>u.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>u.dispatchEvent(t[0]),removeEventListener:(...t)=>u.removeEventListener(t[0],t[1],t[2]),start(t=0){u.start.call(u,t)},stop(t=0){u.stop.call(u,t)}};return t(o,u),i(Object(s.a)(d,h),()=>u.connect(h),()=>u.disconnect(h))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(4),i=n(1);const o=(t,e,n,o)=>(r,a)=>{const c=t(r,t=>t.createConvolver());try{c.channelCount=1}catch(t){return e(r,a)}if(Object(i.a)(c,a),a.disableNormalization===c.normalize&&(c.normalize=!a.disableNormalization),Object(s.a)(c,a,"buffer"),a.channelCount>2)throw n();if(o(c,"channelCount",t=>()=>t.call(c),t=>e=>{if(e>2)throw n();return t.call(c,e)}),"max"===a.channelCountMode)throw n();return o(c,"channelCountMode",t=>()=>t.call(c),t=>e=>{if("max"===e)throw n();return t.call(c,e)}),c}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n)=>(o,{buffer:r,channelCount:a,channelCountMode:c,channelInterpretation:u,disableNormalization:h})=>{const l=t(o,t=>t.createConvolver());Object(s.a)(l,{channelCount:Math.max(a,2),channelCountMode:"max"===c?c:"clamped-max",channelInterpretation:u});const d=e(o,{channelCount:a,channelCountMode:c,channelInterpretation:u,gain:1}),p={get buffer(){return l.buffer},set buffer(t){l.buffer=t},get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){t>2&&(l.channelCount=t),d.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){"max"===t&&(l.channelCountMode=t),d.channelCountMode=t},get channelInterpretation(){return l.channelInterpretation},set channelInterpretation(t){l.channelInterpretation=t,d.channelInterpretation=t},get context(){return l.context},get inputs(){return[l]},get numberOfInputs(){return l.numberOfInputs},get numberOfOutputs(){return l.numberOfOutputs},get normalize(){return l.normalize},set normalize(t){l.normalize=t},addEventListener:(...t)=>l.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>l.dispatchEvent(t[0]),removeEventListener:(...t)=>l.removeEventListener(t[0],t[1],t[2])};h===p.normalize&&(p.normalize=!h),r!==p.buffer&&(p.buffer=r);return n(Object(i.a)(p,d),()=>l.connect(d),()=>l.disconnect(d))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=t=>(e,n)=>{const o=t(e,t=>t.createDelay(n.maxDelayTime));return Object(i.a)(o,n),Object(s.a)(o,n,"delayTime"),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=(t,e)=>(n,o)=>{const r=t(n,t=>t.createDynamicsCompressor());if(Object(i.a)(r,o),o.channelCount>2)throw e();if("max"===o.channelCountMode)throw e();return Object(s.a)(r,o,"attack"),Object(s.a)(r,o,"knee"),Object(s.a)(r,o,"ratio"),Object(s.a)(r,o,"release"),Object(s.a)(r,o,"threshold"),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=t=>(e,n)=>{const o=t(e,t=>t.createGain());return Object(i.a)(o,n),Object(s.a)(o,n,"gain"),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i,o)=>{if(void 0===n.createIIRFilter)return e(n,i,o);const r=t(n,t=>t.createIIRFilter(o.feedforward,o.feedback));return Object(s.a)(r,o),r}},function(t,e,n){"use strict";n.d(e,"a",(function(){return c}));var s=n(43),i=n(42),o=n(11);function r(t,e){const n=e[0]*e[0]+e[1]*e[1];return[(t[0]*e[0]+t[1]*e[1])/n,(t[1]*e[0]-t[0]*e[1])/n]}function a(t,e){let n=[0,0];for(let o=t.length-1;o>=0;o-=1)i=e,n=[(s=n)[0]*i[0]-s[1]*i[1],s[0]*i[1]+s[1]*i[0]],n[0]+=t[o];var s,i;return n}const c=(t,e,n,c)=>(u,h,{channelCount:l,channelCountMode:d,channelInterpretation:p,feedback:f,feedforward:_})=>{const m=Object(s.a)(h,u.sampleRate),g=f.length,v=_.length,y=Math.min(g,v);if(0===f.length||f.length>20)throw c();if(0===f[0])throw e();if(0===_.length||_.length>20)throw c();if(0===_[0])throw e();if(1!==f[0]){for(let t=0;t{const e=t.inputBuffer,n=t.outputBuffer,s=e.numberOfChannels;for(let t=0;tb.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>b.dispatchEvent(t[0]),getFrequencyResponse(e,n,s){if(e.length!==n.length||n.length!==s.length)throw t();const i=e.length;for(let t=0;tb.removeEventListener(t[0],t[1],t[2])};return Object(o.a)(S,b)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n)=>t(e,t=>t.createMediaElementSource(n.mediaElement))},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(1);const i=(t,e)=>(n,i)=>{if(void 0===n.createMediaStreamDestination)throw e();const o=t(n,t=>t.createMediaStreamDestination());return Object(s.a)(o,i),1===o.numberOfOutputs&&Object.defineProperty(o,"numberOfOutputs",{get:()=>0}),o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,{mediaStream:n})=>{const s=n.getAudioTracks(),i=t(e,t=>{const e=s.sort((t,e)=>t.ide.id?1:0).slice(0,1);return t.createMediaStreamSource(new MediaStream(e))});return Object.defineProperty(i,"mediaStream",{value:n}),i}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>(s,{mediaStreamTrack:i})=>"function"==typeof s.createMediaStreamTrackSource?e(s,t=>t.createMediaStreamTrackSource(i)):e(s,e=>{const s=new MediaStream([i]),o=e.createMediaStreamSource(s);if("audio"!==i.kind)throw t();if(n(e))throw new TypeError;return o})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>null===t?null:t.hasOwnProperty("OfflineAudioContext")?t.OfflineAudioContext:t.hasOwnProperty("webkitOfflineAudioContext")?t.webkitOfflineAudioContext:null},function(t,e,n){"use strict";n.d(e,"a",(function(){return c}));var s=n(5),i=n(4),o=n(1),r=n(30),a=n(31);const c=(t,e,n,c,u,h,l)=>(d,p)=>{const f=n(d,t=>t.createOscillator());return Object(o.a)(f,p),Object(s.a)(f,p,"detune"),Object(s.a)(f,p,"frequency"),void 0!==p.periodicWave?f.setPeriodicWave(p.periodicWave):Object(i.a)(f,p,"type"),e(c,()=>c(d))||Object(r.a)(f),e(u,()=>u(d))||l(f,d),e(h,()=>h(d))||Object(a.a)(f),t(d,f),f}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(5),i=n(4),o=n(1);const r=(t,e)=>(n,r)=>{const a=t(n,t=>t.createPanner());return void 0===a.orientationX?e(n,r):(Object(o.a)(a,r),Object(s.a)(a,r,"orientationX"),Object(s.a)(a,r,"orientationY"),Object(s.a)(a,r,"orientationZ"),Object(s.a)(a,r,"positionX"),Object(s.a)(a,r,"positionY"),Object(s.a)(a,r,"positionZ"),Object(i.a)(a,r,"coneInnerAngle"),Object(i.a)(a,r,"coneOuterAngle"),Object(i.a)(a,r,"coneOuterGain"),Object(i.a)(a,r,"distanceModel"),Object(i.a)(a,r,"maxDistance"),Object(i.a)(a,r,"panningModel"),Object(i.a)(a,r,"refDistance"),Object(i.a)(a,r,"rolloffFactor"),a)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n,o,r,a,c,u,h,l)=>(d,{coneInnerAngle:p,coneOuterAngle:f,coneOuterGain:_,distanceModel:m,maxDistance:g,orientationX:v,orientationY:y,orientationZ:b,panningModel:x,positionX:w,positionY:T,positionZ:O,refDistance:S,rolloffFactor:C,...k})=>{const A=n(d,t=>t.createPanner());if(k.channelCount>2)throw u();if("max"===k.channelCountMode)throw u();Object(s.a)(A,k);const D={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},M=o(d,{...D,channelInterpretation:"speakers",numberOfInputs:6}),j=r(d,{...k,gain:1}),E=r(d,{...D,gain:1}),R=r(d,{...D,gain:0}),q=r(d,{...D,gain:0}),I=r(d,{...D,gain:0}),F=r(d,{...D,gain:0}),V=r(d,{...D,gain:0}),N=a(d,256,6,1),P=c(d,{...D,curve:new Float32Array([1,1]),oversample:"none"});let L=[v,y,b],z=[w,T,O];N.onaudioprocess=({inputBuffer:t})=>{const e=[t.getChannelData(0)[0],t.getChannelData(1)[0],t.getChannelData(2)[0]];e.some((t,e)=>t!==L[e])&&(A.setOrientation(...e),L=e);const n=[t.getChannelData(3)[0],t.getChannelData(4)[0],t.getChannelData(5)[0]];n.some((t,e)=>t!==z[e])&&(A.setPosition(...n),z=n)},Object.defineProperty(R.gain,"defaultValue",{get:()=>0}),Object.defineProperty(q.gain,"defaultValue",{get:()=>0}),Object.defineProperty(I.gain,"defaultValue",{get:()=>0}),Object.defineProperty(F.gain,"defaultValue",{get:()=>0}),Object.defineProperty(V.gain,"defaultValue",{get:()=>0});const B={get bufferSize(){},get channelCount(){return A.channelCount},set channelCount(t){if(t>2)throw u();j.channelCount=t,A.channelCount=t},get channelCountMode(){return A.channelCountMode},set channelCountMode(t){if("max"===t)throw u();j.channelCountMode=t,A.channelCountMode=t},get channelInterpretation(){return A.channelInterpretation},set channelInterpretation(t){j.channelInterpretation=t,A.channelInterpretation=t},get coneInnerAngle(){return A.coneInnerAngle},set coneInnerAngle(t){A.coneInnerAngle=t},get coneOuterAngle(){return A.coneOuterAngle},set coneOuterAngle(t){A.coneOuterAngle=t},get coneOuterGain(){return A.coneOuterGain},set coneOuterGain(t){if(t<0||t>1)throw e();A.coneOuterGain=t},get context(){return A.context},get distanceModel(){return A.distanceModel},set distanceModel(t){A.distanceModel=t},get inputs(){return[j]},get maxDistance(){return A.maxDistance},set maxDistance(t){if(t<0)throw new RangeError;A.maxDistance=t},get numberOfInputs(){return A.numberOfInputs},get numberOfOutputs(){return A.numberOfOutputs},get orientationX(){return E.gain},get orientationY(){return R.gain},get orientationZ(){return q.gain},get panningModel(){return A.panningModel},set panningModel(t){if(A.panningModel=t,A.panningModel!==t&&"HRTF"===t)throw u()},get positionX(){return I.gain},get positionY(){return F.gain},get positionZ(){return V.gain},get refDistance(){return A.refDistance},set refDistance(t){if(t<0)throw new RangeError;A.refDistance=t},get rolloffFactor(){return A.rolloffFactor},set rolloffFactor(t){if(t<0)throw new RangeError;A.rolloffFactor=t},addEventListener:(...t)=>j.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>j.dispatchEvent(t[0]),removeEventListener:(...t)=>j.removeEventListener(t[0],t[1],t[2])};p!==B.coneInnerAngle&&(B.coneInnerAngle=p),f!==B.coneOuterAngle&&(B.coneOuterAngle=f),_!==B.coneOuterGain&&(B.coneOuterGain=_),m!==B.distanceModel&&(B.distanceModel=m),g!==B.maxDistance&&(B.maxDistance=g),v!==B.orientationX.value&&(B.orientationX.value=v),y!==B.orientationY.value&&(B.orientationY.value=y),b!==B.orientationZ.value&&(B.orientationZ.value=b),x!==B.panningModel&&(B.panningModel=x),w!==B.positionX.value&&(B.positionX.value=w),T!==B.positionY.value&&(B.positionY.value=T),O!==B.positionZ.value&&(B.positionZ.value=O),S!==B.refDistance&&(B.refDistance=S),C!==B.rolloffFactor&&(B.rolloffFactor=C),1===L[0]&&0===L[1]&&0===L[2]||A.setOrientation(...L),0===z[0]&&0===z[1]&&0===z[2]||A.setPosition(...z);return l(Object(i.a)(B,A),()=>{j.connect(A),t(j,P,0,0),P.connect(E).connect(M,0,0),P.connect(R).connect(M,0,1),P.connect(q).connect(M,0,2),P.connect(I).connect(M,0,3),P.connect(F).connect(M,0,4),P.connect(V).connect(M,0,5),M.connect(N).connect(d.destination)},()=>{j.disconnect(A),h(j,P,0,0),P.disconnect(E),E.disconnect(M),P.disconnect(R),R.disconnect(M),P.disconnect(q),q.disconnect(M),P.disconnect(I),I.disconnect(M),P.disconnect(F),F.disconnect(M),P.disconnect(V),V.disconnect(M),M.disconnect(N),N.disconnect(d.destination)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,{disableNormalization:n,imag:s,real:i})=>{const o=t(e),r=new Float32Array(s),a=new Float32Array(i);return null!==o?o.createPeriodicWave(a,r,{disableNormalization:n}):e.createPeriodicWave(a,r,{disableNormalization:n})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>(e,n,s,i)=>t(e,t=>t.createScriptProcessor(n,s,i))},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(5),i=n(1);const o=(t,e,n)=>(o,r)=>t(o,t=>{const a=r.channelCountMode;if("clamped-max"===a)throw n();if(void 0===o.createStereoPanner)return e(o,r);const c=t.createStereoPanner();return Object(i.a)(c,r),Object(s.a)(c,r,"pan"),Object.defineProperty(c,"channelCountMode",{get:()=>a,set:t=>{if(t!==a)throw n()}}),c})},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=(t,e,n,i,o,r)=>{const a=new Float32Array([1,1]),c=Math.PI/2,u={channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete"},h={...u,oversample:"none"},l=(t,s,r,l,d)=>{if(1===s)return((t,e,s,o)=>{const r=new Float32Array(16385),l=new Float32Array(16385);for(let t=0;t<16385;t+=1){const e=t/16384*c;r[t]=Math.cos(e),l[t]=Math.sin(e)}const d=n(t,{...u,gain:0}),p=i(t,{...h,curve:r}),f=i(t,{...h,curve:a}),_=n(t,{...u,gain:0}),m=i(t,{...h,curve:l});return{connectGraph(){e.connect(d),e.connect(f.inputs[0]),e.connect(_),f.connect(s),s.connect(p.inputs[0]),s.connect(m.inputs[0]),p.connect(d.gain),m.connect(_.gain),d.connect(o,0,0),_.connect(o,0,1)},disconnectGraph(){e.disconnect(d),e.disconnect(f.inputs[0]),e.disconnect(_),f.disconnect(s),s.disconnect(p.inputs[0]),s.disconnect(m.inputs[0]),p.disconnect(d.gain),m.disconnect(_.gain),d.disconnect(o,0,0),_.disconnect(o,0,1)}}})(t,r,l,d);if(2===s)return((t,s,o,r)=>{const l=new Float32Array(16385),d=new Float32Array(16385),p=new Float32Array(16385),f=new Float32Array(16385),_=Math.floor(8192.5);for(let t=0;t<16385;t+=1)if(t>_){const e=(t-_)/(16384-_)*c;l[t]=Math.cos(e),d[t]=Math.sin(e),p[t]=0,f[t]=1}else{const e=t/(16384-_)*c;l[t]=1,d[t]=0,p[t]=Math.cos(e),f[t]=Math.sin(e)}const m=e(t,{channelCount:2,channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:2}),g=n(t,{...u,gain:0}),v=i(t,{...h,curve:l}),y=n(t,{...u,gain:0}),b=i(t,{...h,curve:d}),x=i(t,{...h,curve:a}),w=n(t,{...u,gain:0}),T=i(t,{...h,curve:p}),O=n(t,{...u,gain:0}),S=i(t,{...h,curve:f});return{connectGraph(){s.connect(m),s.connect(x.inputs[0]),m.connect(g,1),m.connect(y,1),m.connect(w,1),m.connect(O,1),x.connect(o),o.connect(v.inputs[0]),o.connect(b.inputs[0]),o.connect(T.inputs[0]),o.connect(S.inputs[0]),v.connect(g.gain),b.connect(y.gain),T.connect(w.gain),S.connect(O.gain),g.connect(r,0,0),w.connect(r,0,0),y.connect(r,0,1),O.connect(r,0,1)},disconnectGraph(){s.disconnect(m),s.disconnect(x.inputs[0]),m.disconnect(g,1),m.disconnect(y,1),m.disconnect(w,1),m.disconnect(O,1),x.disconnect(o),o.disconnect(v.inputs[0]),o.disconnect(b.inputs[0]),o.disconnect(T.inputs[0]),o.disconnect(S.inputs[0]),v.disconnect(g.gain),b.disconnect(y.gain),T.disconnect(w.gain),S.disconnect(O.gain),g.disconnect(r,0,0),w.disconnect(r,0,0),y.disconnect(r,0,1),O.disconnect(r,0,1)}}})(t,r,l,d);throw o()};return(e,{channelCount:i,channelCountMode:a,pan:c,...u})=>{if("max"===a)throw o();const h=t(e,{...u,channelCount:1,channelCountMode:a,numberOfInputs:2}),d=n(e,{...u,channelCount:i,channelCountMode:a,gain:1}),p=n(e,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:c});let{connectGraph:f,disconnectGraph:_}=l(e,i,d,p,h);Object.defineProperty(p.gain,"defaultValue",{get:()=>0});const m={get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){d.channelCount!==t&&(g&&_(),({connectGraph:f,disconnectGraph:_}=l(e,t,d,p,h)),g&&f()),d.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){if("clamped-max"===t||"max"===t)throw o();d.channelCountMode=t},get channelInterpretation(){return d.channelInterpretation},set channelInterpretation(t){d.channelInterpretation=t},get context(){return d.context},get inputs(){return[d]},get numberOfInputs(){return d.numberOfInputs},get numberOfOutputs(){return d.numberOfOutputs},get pan(){return p.gain},addEventListener:(...t)=>d.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>d.dispatchEvent(t[0]),removeEventListener:(...t)=>d.removeEventListener(t[0],t[1],t[2])};let g=!1;return r(Object(s.a)(m,h),()=>{f(),g=!0},()=>{_(),g=!1})}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(4),i=n(1);const o=(t,e,n,o,r,a,c)=>(u,h)=>{const l=n(u,t=>t.createWaveShaper());try{return l.curve=new Float32Array([1]),o(u,h)}catch{}Object(i.a)(l,h);const d=h.curve;if(null!==d&&d.length<2)throw e();Object(s.a)(l,h,"curve"),Object(s.a)(l,h,"oversample");let p=null,f=!1;c(l,"curve",t=>()=>t.call(l),e=>n=>(e.call(l,n),f&&(r(n)&&null===p?p=t(u,l):r(n)||null===p||(p(),p=null)),n));return a(l,()=>{f=!0,r(l.curve)&&(p=t(u,l))},()=>{f=!1,null!==p&&(p(),p=null)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(11);const o=(t,e,n,o,r,a)=>(c,{curve:u,oversample:h,...l})=>{const d=n(c,t=>t.createWaveShaper()),p=n(c,t=>t.createWaveShaper());Object(s.a)(d,l),Object(s.a)(p,l);const f=o(c,{...l,gain:1}),_=o(c,{...l,gain:-1}),m=o(c,{...l,gain:1}),g=o(c,{...l,gain:-1});let v=null,y=!1,b=null;const x={get bufferSize(){},get channelCount(){return d.channelCount},set channelCount(t){f.channelCount=t,_.channelCount=t,d.channelCount=t,m.channelCount=t,p.channelCount=t,g.channelCount=t},get channelCountMode(){return d.channelCountMode},set channelCountMode(t){f.channelCountMode=t,_.channelCountMode=t,d.channelCountMode=t,m.channelCountMode=t,p.channelCountMode=t,g.channelCountMode=t},get channelInterpretation(){return d.channelInterpretation},set channelInterpretation(t){f.channelInterpretation=t,_.channelInterpretation=t,d.channelInterpretation=t,m.channelInterpretation=t,p.channelInterpretation=t,g.channelInterpretation=t},get context(){return d.context},get curve(){return b},set curve(n){if(null!==u&&u.length<2)throw e();if(null===n)d.curve=n,p.curve=n;else{const t=n.length,e=new Float32Array(t+2-t%2),s=new Float32Array(t+2-t%2);e[0]=n[0],s[0]=-n[t-1];const i=Math.ceil((t+1)/2),o=(t+1)/2-1;for(let r=1;rf.addEventListener(t[0],t[1],t[2]),dispatchEvent:(...t)=>f.dispatchEvent(t[0]),removeEventListener:(...t)=>f.removeEventListener(t[0],t[1],t[2])};u!==x.curve&&(x.curve=u),h!==x.oversample&&(x.oversample=h);return a(Object(i.a)(x,m),()=>{f.connect(d).connect(m),f.connect(_).connect(p).connect(g).connect(m),y=!0,r(b)&&(v=t(c,f))},()=>{f.disconnect(d),d.disconnect(m),f.disconnect(_),_.disconnect(p),p.disconnect(g),g.disconnect(m),y=!1,null!==v&&(v(),v=null)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(14);const i={numberOfChannels:1},o=(t,e,n,o,r)=>class extends t{constructor(t,n,r){let a;if("number"==typeof t&&void 0!==n&&void 0!==r)a={length:n,numberOfChannels:t,sampleRate:r};else{if("object"!=typeof t)throw new Error("The given parameters are not valid.");a=t}const{length:c,numberOfChannels:u,sampleRate:h}={...i,...a},l=o(u,c,h);e(s.a,()=>Object(s.a)(l))||l.addEventListener("statechange",(()=>{let t=0;const e=n=>{"running"===this._state&&(t>0?(l.removeEventListener("statechange",e),n.stopImmediatePropagation(),this._waitForThePromiseToSettle(n)):t+=1)};return e})()),super(l,u),this._length=c,this._nativeOfflineAudioContext=l,this._state=null}get length(){return void 0===this._nativeOfflineAudioContext.length?this._length:this._nativeOfflineAudioContext.length}get state(){return null===this._state?this._nativeOfflineAudioContext.state:this._state}startRendering(){return"running"===this._state?Promise.reject(n()):(this._state="running",r(this.destination,this._nativeOfflineAudioContext).then(t=>(this._state=null,t)).catch(t=>{throw this._state=null,t}))}_waitForThePromiseToSettle(t){null===this._state?this._nativeOfflineAudioContext.dispatchEvent(t):setTimeout(()=>this._waitForThePromiseToSettle(t))}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(17),i=n(21);const o={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",detune:0,frequency:440,type:"sine"},r=(t,e,n,r,a,c,u,h)=>class extends t{constructor(t,n=o){const s=c(t),i={...o,...n},h=r(s,i),l=u(s),d=l?a():null,p=t.sampleRate/2;super(t,!1,h,d),this._detune=e(this,l,h.detune,153600,-153600),this._frequency=e(this,l,h.frequency,p,-p),this._nativeOscillatorNode=h,this._onended=null,this._oscillatorNodeRenderer=d,null!==this._oscillatorNodeRenderer&&void 0!==i.periodicWave&&(this._oscillatorNodeRenderer.periodicWave=i.periodicWave)}get detune(){return this._detune}get frequency(){return this._frequency}get onended(){return this._onended}set onended(t){const e="function"==typeof t?h(this,t):null;this._nativeOscillatorNode.onended=e;const n=this._nativeOscillatorNode.onended;this._onended=null!==n&&n===e?t:n}get type(){return this._nativeOscillatorNode.type}set type(t){if(this._nativeOscillatorNode.type=t,"custom"===t)throw n();null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=null)}setPeriodicWave(t){this._nativeOscillatorNode.setPeriodicWave(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.periodicWave=t)}start(t=0){if(this._nativeOscillatorNode.start(t),null!==this._oscillatorNodeRenderer)this._oscillatorNodeRenderer.start=t;else{Object(s.a)(this);const t=()=>{this._nativeOscillatorNode.removeEventListener("ended",t),setTimeout(()=>Object(i.a)(this),1e3)};this._nativeOscillatorNode.addEventListener("ended",t)}}stop(t=0){this._nativeOscillatorNode.stop(t),null!==this._oscillatorNodeRenderer&&(this._oscillatorNodeRenderer.stop=t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(3);const i=(t,e,n,i,o)=>()=>{const r=new WeakMap;let a=null,c=null,u=null;return{set periodicWave(t){a=t},set start(t){c=t},set stop(t){u=t},render(h,l,d){const p=r.get(l);return void 0!==p?Promise.resolve(p):(async(h,l,d)=>{let p=n(h);const f=Object(s.a)(p,l);if(!f){const t={channelCount:p.channelCount,channelCountMode:p.channelCountMode,channelInterpretation:p.channelInterpretation,detune:p.detune.value,frequency:p.frequency.value,periodicWave:null===a?void 0:a,type:p.type};p=e(l,t),null!==c&&p.start(c),null!==u&&p.stop(u)}return r.set(l,p),f?(await t(l,h.detune,p.detune,d),await t(l,h.frequency,p.frequency,d)):(await i(l,h.detune,p.detune,d),await i(l,h.frequency,p.frequency,d)),await o(h,l,p,d),p})(h,l,d)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(2);const i={channelCount:2,channelCountMode:"clamped-max",channelInterpretation:"speakers",coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:1,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1},o=(t,e,n,o,r,a)=>class extends t{constructor(t,c=i){const u=r(t),h={...i,...c},l=n(u,h),d=a(u);super(t,!1,l,d?o():null),this._nativePannerNode=l,this._orientationX=e(this,d,l.orientationX,s.b,s.a),this._orientationY=e(this,d,l.orientationY,s.b,s.a),this._orientationZ=e(this,d,l.orientationZ,s.b,s.a),this._positionX=e(this,d,l.positionX,s.b,s.a),this._positionY=e(this,d,l.positionY,s.b,s.a),this._positionZ=e(this,d,l.positionZ,s.b,s.a)}get coneInnerAngle(){return this._nativePannerNode.coneInnerAngle}set coneInnerAngle(t){this._nativePannerNode.coneInnerAngle=t}get coneOuterAngle(){return this._nativePannerNode.coneOuterAngle}set coneOuterAngle(t){this._nativePannerNode.coneOuterAngle=t}get coneOuterGain(){return this._nativePannerNode.coneOuterGain}set coneOuterGain(t){this._nativePannerNode.coneOuterGain=t}get distanceModel(){return this._nativePannerNode.distanceModel}set distanceModel(t){this._nativePannerNode.distanceModel=t}get maxDistance(){return this._nativePannerNode.maxDistance}set maxDistance(t){this._nativePannerNode.maxDistance=t}get orientationX(){return this._orientationX}get orientationY(){return this._orientationY}get orientationZ(){return this._orientationZ}get panningModel(){return this._nativePannerNode.panningModel}set panningModel(t){this._nativePannerNode.panningModel=t}get positionX(){return this._positionX}get positionY(){return this._positionY}get positionZ(){return this._positionZ}get refDistance(){return this._nativePannerNode.refDistance}set refDistance(t){this._nativePannerNode.refDistance=t}get rolloffFactor(){return this._nativePannerNode.rolloffFactor}set rolloffFactor(t){this._nativePannerNode.rolloffFactor=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n,o,r,a,c,u,h,l)=>()=>{const d=new WeakMap;let p=null;return{render(f,_,m){const g=d.get(_);return void 0!==g?Promise.resolve(g):(async(f,_,m)=>{let g=null,v=a(f);const y={channelCount:v.channelCount,channelCountMode:v.channelCountMode,channelInterpretation:v.channelInterpretation},b={...y,coneInnerAngle:v.coneInnerAngle,coneOuterAngle:v.coneOuterAngle,coneOuterGain:v.coneOuterGain,distanceModel:v.distanceModel,maxDistance:v.maxDistance,panningModel:v.panningModel,refDistance:v.refDistance,rolloffFactor:v.rolloffFactor},x=Object(i.a)(v,_);if("bufferSize"in v)g=o(_,{...y,gain:1});else if(!x){const t={...b,orientationX:v.orientationX.value,orientationY:v.orientationY.value,orientationZ:v.orientationZ.value,positionX:v.positionX.value,positionY:v.positionY.value,positionZ:v.positionZ.value};v=r(_,t)}if(d.set(_,null===g?v:g),null!==g){if(null===p){if(null===c)throw new Error("Missing the native OfflineAudioContext constructor.");const t=new c(6,f.context.length,_.sampleRate),s=e(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:6});s.connect(t.destination),p=(async()=>{const e=await Promise.all([f.orientationX,f.orientationY,f.orientationZ,f.positionX,f.positionY,f.positionZ].map(async(e,s)=>{const i=n(t,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:0===s?1:0});return await u(t,e,i.offset,m),i}));for(let t=0;t<6;t+=1)e[t].connect(s,0,t),e[t].start(0);return l(t)})()}const t=await p,s=o(_,{...y,gain:1});await h(f,_,s,m);const i=[];for(let e=0;et!==a[e])||n.some((t,e)=>t!==d[e])){a=t,d=n;const i=e/_.sampleRate;v.gain.setValueAtTime(0,i),v=o(_,{...y,gain:0}),x=r(_,{...b,orientationX:a[0],orientationY:a[1],orientationZ:a[2],positionX:d[0],positionY:d[1],positionZ:d[2]}),v.gain.setValueAtTime(1,i),s.connect(v).connect(x.inputs[0]),x.connect(g)}}return g}return x?(await t(_,f.orientationX,v.orientationX,m),await t(_,f.orientationY,v.orientationY,m),await t(_,f.orientationZ,v.orientationZ,m),await t(_,f.positionX,v.positionX,m),await t(_,f.positionY,v.positionY,m),await t(_,f.positionZ,v.positionZ,m)):(await u(_,f.orientationX,v.orientationX,m),await u(_,f.orientationY,v.orientationY,m),await u(_,f.orientationZ,v.orientationZ,m),await u(_,f.positionX,v.positionX,m),await u(_,f.positionY,v.positionY,m),await u(_,f.positionZ,v.positionZ,m)),Object(s.a)(v)?await h(f,_,v.inputs[0],m):await h(f,_,v,m),v})(f,_,m)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={disableNormalization:!1},i=(t,e,n)=>class i{constructor(i,o){const r=e(i),a={...s,...o},c=t(r,a);return n.add(c),c}static[Symbol.hasInstance](t){return null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===i.prototype||n.has(t)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>(n,s,i,o)=>(t(s).replay(i),e(s,n,i,o))},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>async(s,i,o,r)=>{const a=t(s),c=[...r,s];await Promise.all(a.activeInputs.map((t,r)=>Array.from(t).filter(([t])=>!c.includes(t)).map(async([t,a])=>{const u=e(t),h=await u.render(t,i,c),l=s.context.destination;n(t)||s===l&&n(s)||h.connect(o,a,r)})).reduce((t,e)=>[...t,...e],[]))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>async(s,i,o,r)=>{const a=e(s);await Promise.all(Array.from(a.activeInputs).map(async([e,s])=>{const a=t(e),c=await a.render(e,i,r);n(e)||c.connect(o,s)}))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(14);const i=(t,e,n,i)=>o=>t(s.a,()=>Object(s.a)(o))?Promise.resolve(t(i,i)).then(t=>{if(!t){const t=n(o,512,0,1);o.oncomplete=()=>{t.onaudioprocess=null,t.disconnect()},t.onaudioprocess=()=>o.currentTime,t.connect(o.destination)}return o.startRendering()}):new Promise(t=>{const n=e(o,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});o.oncomplete=e=>{n.disconnect(),t(e.renderedBuffer)},n.connect(o.destination),o.startRendering()})},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(29);const i=(t,e,n,i,o,r,a,c)=>{const u=[];return(h,l)=>n(h).render(h,l,u).then(()=>Promise.all(Array.from(i(l)).map(t=>n(t).render(t,l,u)))).then(()=>o(l)).then(n=>("function"!=typeof n.copyFromChannel?(a(n),Object(s.a)(n)):e(r,()=>r(n))||c(n),t.add(n),n))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"explicit",channelInterpretation:"speakers",pan:0},i=(t,e,n,i,o,r)=>class extends t{constructor(t,a=s){const c=o(t),u={...s,...a},h=n(c,u),l=r(c);super(t,!1,h,l?i():null),this._pan=e(this,l,h.pan,1,-1)}get pan(){return this._pan}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n,o,r)=>()=>{const a=new WeakMap;return{render(c,u,h){const l=a.get(u);return void 0!==l?Promise.resolve(l):(async(c,u,h)=>{let l=n(c);const d=Object(i.a)(l,u);if(!d){const t={channelCount:l.channelCount,channelCountMode:l.channelCountMode,channelInterpretation:l.channelInterpretation,pan:l.pan.value};l=e(u,t)}return a.set(u,l),d?await t(u,c.pan,l.pan,h):await o(u,c.pan,l.pan,h),Object(s.a)(l)?await r(c,u,l.inputs[0],h):await r(c,u,l,h),l})(c,u,h)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;try{new t({length:1,sampleRate:44100})}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100).createBuffer(1,1,44100);if(void 0===e.copyToChannel)return!0;const n=new Float32Array(2);try{e.copyFromChannel(n,0,0)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource());n.start();try{n.start()}catch{return!0}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100),n=e.createBuffer(1,1,e.sampleRate),s=e.createBufferSource();return n.getChannelData(0)[0]=1,s.buffer=n,s.start(0,0,0),s.connect(e.destination),new Promise(t=>{e.oncomplete=({renderedBuffer:e})=>{t(0===e.getChannelData(0)[0])},e.startRendering()})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource()),s=e.createBuffer(1,1,44100);n.buffer=s;try{n.start(0,1)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createBufferSource());n.start();try{n.stop()}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;if(void 0!==t.prototype&&void 0!==t.prototype.close)return!0;const e=new t,n=void 0!==e.close;try{e.close()}catch{}return n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100);return new Promise(t=>{let n=!0;const s=s=>{n&&(n=!1,e.startRendering(),t(s instanceof TypeError))};let i;try{i=e.decodeAudioData(null,()=>{},s)}catch(t){s(t)}void 0!==i&&i.catch(s)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;let e;try{e=new t({latencyHint:"balanced"})}catch{return!1}return e.close(),!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100).createGain(),n=e.connect(e)===e;return e.disconnect(e),n}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createOscillator());try{n.start(-1)}catch(t){return t instanceof RangeError}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=e.createBuffer(1,1,44100),s=t(e,t=>t.createBufferSource());s.buffer=n,s.start(),s.stop();try{return s.stop(),!0}catch{return!1}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>e=>{const n=t(e,t=>t.createOscillator());try{n.stop(-1)}catch(t){return t instanceof RangeError}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>async()=>{if(null===t)return!0;if(null===e)return!1;const n=new Blob(['class A extends AudioWorkletProcessor{process(){this.port.postMessage(0)}}registerProcessor("a",A)'],{type:"application/javascript; charset=utf-8"}),s=new e(1,128,3200),i=URL.createObjectURL(n);let o=!1;try{await s.audioWorklet.addModule(i);const e=s.createGain(),n=new t(s,"a",{numberOfOutputs:0});n.port.onmessage=()=>o=!0,e.connect(n),await s.startRendering()}catch{}finally{URL.revokeObjectURL(i)}return o}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return!1;const n=new e(1,1,44100),s=t(n,t=>t.createChannelMerger());try{s.channelCount=2}catch{return!0}return!1}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return!1;const n=new e(1,1,44100);return void 0===n.createConstantSource||t(n,t=>t.createConstantSource()).offset.maxValue!==Number.POSITIVE_INFINITY}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t(1,1,44100),n=e.createConvolver();n.buffer=e.createBuffer(1,1,e.sampleRate);try{n.buffer=e.createBuffer(1,1,e.sampleRate)}catch{return!1}return!0}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>null!==t&&t.hasOwnProperty("isSecureContext")},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return!1;const e=new t;try{return e.createMediaStreamSource(new MediaStream),!1}catch(t){return!0}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>()=>{if(null===e)return Promise.resolve(!1);const n=new e(1,1,44100),s=t(n,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return new Promise(t=>{n.oncomplete=()=>{s.disconnect(),t(0!==n.currentTime)},n.startRendering()})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>()=>{if(null===t)return Promise.resolve(!1);const e=new t(1,1,44100);if(void 0===e.createStereoPanner)return Promise.resolve(!0);if(void 0===e.createConstantSource)return Promise.resolve(!0);const n=e.createConstantSource(),s=e.createStereoPanner();return n.channelCount=1,n.offset.value=1,s.channelCount=1,n.start(),n.connect(s).connect(e.destination),e.startRendering().then(t=>1!==t.getChannelData(0)[0])}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));const s={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers",curve:null,oversample:"none"},i=(t,e,n,i,o,r)=>class extends t{constructor(t,e=s){const a=o(t),c={...s,...e},u=n(a,c);super(t,!0,u,r(a)?i():null),this._isCurveNullified=!1,this._nativeWaveShaperNode=u}get curve(){return this._isCurveNullified?null:this._nativeWaveShaperNode.curve}set curve(t){if(null===t)this._isCurveNullified=!0,this._nativeWaveShaperNode.curve=new Float32Array([0,0]);else{if(t.length<2)throw e();this._isCurveNullified=!1,this._nativeWaveShaperNode.curve=t}}get oversample(){return this._nativeWaveShaperNode.oversample}set oversample(t){this._nativeWaveShaperNode.oversample=t}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(12),i=n(3);const o=(t,e,n)=>()=>{const o=new WeakMap;return{render(r,a,c){const u=o.get(a);return void 0!==u?Promise.resolve(u):(async(r,a,c)=>{let u=e(r);if(!Object(i.a)(u,a)){const e={channelCount:u.channelCount,channelCountMode:u.channelCountMode,channelInterpretation:u.channelInterpretation,curve:u.curve,oversample:u.oversample};u=t(a,e)}return o.set(a,u),Object(s.a)(u)?await n(r,a,u.inputs[0],c):await n(r,a,u,c),u})(r,a,c)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>"undefined"==typeof window?null:window},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e)=>n=>{n.copyFromChannel=(s,i,o=0)=>{const r=t(o),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),h=s.length;for(let t=r<0?-r:0;t+r{const r=t(o),a=t(i);if(a>=n.numberOfChannels)throw e();const c=n.length,u=n.getChannelData(a),h=s.length;for(let t=r<0?-r:0;t+re=>{var n,s;e.copyFromChannel=(n=e.copyFromChannel,(s,i,o=0)=>{const r=t(o),a=t(i);if(r{const r=t(o),a=t(i);if(r(e,n)=>{const s=n.createBuffer(1,1,n.sampleRate);null===e.buffer&&(e.buffer=s),t(e,"buffer",t=>()=>{const n=t.call(e);return n===s?null:n},t=>n=>t.call(e,null===n?s:n))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(11);const i=t=>(e,n)=>{const i=t(n,t=>t.createGain());e.connect(i);const o=(r=e.disconnect,()=>{r.call(e,i),e.removeEventListener("ended",o)});var r;e.addEventListener("ended",o),Object(s.a)(e,i),e.stop=(t=>{let n=!1;return(s=0)=>{if(n)try{t.call(e,s)}catch{i.gain.setValueAtTime(0,s)}else t.call(e,s),n=!0}})(e.stop)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n)=>(s,i)=>{i.channelCount=1,i.channelCountMode="explicit",Object.defineProperty(i,"channelCount",{get:()=>1,set:()=>{throw t()}}),Object.defineProperty(i,"channelCountMode",{get:()=>"explicit",set:()=>{throw t()}});const o=e(s,t=>t.createBufferSource());n(i,()=>{const t=i.numberOfInputs;for(let e=0;eo.disconnect(i))}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=()=>new Promise(t=>{const e=new ArrayBuffer(0),{port1:n,port2:s}=new MessageChannel;n.onmessage=({data:e})=>t(null!==e),s.postMessage(e,[e])})},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=t=>{var e;t.start=(e=t.start,(n=0,s=0,i)=>{const o=t.buffer,r=null===o?s:Math.min(o.duration,s);null!==o&&r>o.duration-.5/t.context.sampleRate?e.call(t,n,0,0):e.call(t,n,r,i)})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return N}));var s=n(0),i=n(24),o=n(22);const r=t=>"port"in t;var a=n(33),c=n(20);const u=(t,e)=>{if(!Object(c.a)(t).delete(e))throw new Error("Missing the expected event listener.")};var h=n(34),l=n(8),d=n(26),p=n(6),f=n(27),_=n(9),m=n(16),g=n(23),v=n(19);const y=t=>!s.a.has(t),b=(t,e)=>{const n=Array.from(t).filter(e);if(n.length>1)throw Error("More than one element was found.");if(0===n.length)throw Error("No element was found.");const[s]=n;return t.delete(s),s};var x=n(17),w=n(21);const T=(t,e)=>{!r(t)&&e.every(t=>0===t.size)&&Object(w.a)(t)},O=t=>new Promise(e=>{const n=t.createScriptProcessor(256,1,1),s=t.createGain(),i=t.createBuffer(1,2,44100),o=i.getChannelData(0);o[0]=1,o[1]=1;const r=t.createBufferSource();r.buffer=i,r.loop=!0,r.connect(n).connect(t.destination),r.connect(s),r.disconnect(s),n.onaudioprocess=s=>{const i=s.inputBuffer.getChannelData(0);Array.prototype.some.call(i,t=>1===t)?e(!0):e(!1),r.stop(),n.onaudioprocess=null,r.disconnect(n),n.disconnect(t.destination)},r.start()}),S=(t,e)=>{const n=new Map;for(const e of t)for(const t of e){const e=n.get(t);n.set(t,void 0===e?1:e+1)}n.forEach((t,n)=>e(n,t))};var C=n(25);const k=(t,e,[n,s,i],o)=>{Object(m.a)(t[s],[e,n,i],t=>t[0]===e&&t[1]===n,o)},A=(t,e,[n,s],i)=>{Object(m.a)(t,[e,n,s],t=>t[0]===e&&t[1]===n,i)},D=(t,e,[n,s,i],o)=>{const r=t.get(n);void 0===r?t.set(n,new Set([[s,e,i]])):Object(m.a)(r,[s,e,i],t=>t[0]===s&&t[1]===e,o)},M=(t,[e,n,s],i)=>{const o=t.get(e);void 0===o?t.set(e,new Set([[n,s]])):Object(m.a)(o,[n,s],t=>t[0]===n,i)},j=(t,e,n,s)=>{const i=Object(_.a)(t,e),o=b(i,t=>t[0]===n&&t[1]===s);return 0===i.size&&t.delete(e),o},E=(t,e,n)=>{const s=Object(_.a)(t,e),i=b(s,t=>t[0]===n);return 0===s.size&&t.delete(e),i},R=(t,e,n,s)=>{const{activeInputs:i,passiveInputs:o}=Object(l.a)(e),{outputs:r}=Object(l.a)(t),u=Object(c.a)(t),d=r=>{const c=Object(p.a)(e),u=Object(p.a)(t);if(r){const r=j(o,t,n,s);k(i,t,r,!1),Object(v.a)(t)||Object(a.a)(u,c,n,s),y(e)&&Object(x.a)(e)}else{const r=((t,e,n,s)=>b(t[s],t=>t[0]===e&&t[1]===n))(i,t,n,s);D(o,s,r,!1),Object(v.a)(t)||Object(h.a)(u,c,n,s),Object(g.a)(e)&&T(e,i)}};return!!Object(m.a)(r,[e,n,s],t=>t[0]===e&&t[1]===n&&t[2]===s,!0)&&(u.add(d),Object(g.a)(t)?k(i,t,[n,s,d],!0):D(o,s,[t,n,d],!0),!0)},q=(t,e,n)=>{const{activeInputs:s,passiveInputs:i}=Object(d.a)(e),{outputs:o}=Object(l.a)(t),r=Object(c.a)(t),a=o=>{const r=Object(p.a)(t),a=Object(f.a)(e);if(o){const e=E(i,t,n);A(s,t,e,!1),Object(v.a)(t)||r.connect(a,n)}else{const e=((t,e,n)=>b(t,t=>t[0]===e&&t[1]===n))(s,t,n);M(i,e,!1),Object(v.a)(t)||r.disconnect(a,n)}};return!!Object(m.a)(o,[e,n],t=>t[0]===e&&t[1]===n,!0)&&(r.add(a),Object(g.a)(t)?A(s,t,[n,a],!0):M(i,[t,n,a],!0),!0)},I=(t,e,n)=>{for(const s of t)if(s[0]===e&&s[1]===n)return t.delete(s),s;return null},F=(t,e,n,s)=>{const[i,o]=((t,e,n,s)=>{const{activeInputs:i,passiveInputs:o}=Object(l.a)(e),r=I(i[s],t,n);if(null===r){return[j(o,t,n,s)[2],!1]}return[r[2],!0]})(t,e,n,s);if(null!==i&&(u(t,i),o&&!Object(v.a)(t)&&Object(h.a)(Object(p.a)(t),Object(p.a)(e),n,s)),Object(g.a)(e)){const{activeInputs:t}=Object(l.a)(e);T(e,t)}},V=(t,e,n)=>{const[s,i]=((t,e,n)=>{const{activeInputs:s,passiveInputs:i}=Object(d.a)(e),o=I(s,t,n);if(null===o){return[E(i,t,n)[1],!1]}return[o[2],!0]})(t,e,n);null!==s&&(u(t,s),i&&!Object(v.a)(t)&&Object(p.a)(t).disconnect(Object(f.a)(e),n))},N=(t,e,n,c,u,h,_,g,v,b,w,T,D,M,j)=>class extends b{constructor(e,i,o,r){super(o),this._context=e,this._nativeAudioNode=o;const a=w(e);T(a)&&!0!==n(O,()=>O(a))&&(t=>{const e=new Map;var n,s;t.connect=(n=t.connect.bind(t),(t,s=0,i=0)=>{const o=Object(C.a)(t)?n(t,s,i):n(t,s),r=e.get(t);return void 0===r?e.set(t,[{input:i,output:s}]):r.every(t=>t.input!==i||t.output!==s)&&r.push({input:i,output:s}),o}),t.disconnect=(s=t.disconnect,(n,i,o)=>{if(s.apply(t),void 0===n)e.clear();else if("number"==typeof n)for(const[t,s]of e){const i=s.filter(t=>t.output!==n);0===i.length?e.delete(t):e.set(t,i)}else if(e.has(n))if(void 0===i)e.delete(n);else{const t=e.get(n);if(void 0!==t){const s=t.filter(t=>t.output!==i&&(t.input!==o||void 0===o));0===s.length?e.delete(n):e.set(n,s)}}for(const[n,s]of e)s.forEach(e=>{Object(C.a)(n)?t.connect(n,e.output,e.input):t.connect(n,e.output)})})})(o),s.c.set(this,o),s.i.set(this,new Set),i&&Object(x.a)(this),t(this,r,o)}get channelCount(){return this._nativeAudioNode.channelCount}set channelCount(t){this._nativeAudioNode.channelCount=t}get channelCountMode(){return this._nativeAudioNode.channelCountMode}set channelCountMode(t){this._nativeAudioNode.channelCountMode=t}get channelInterpretation(){return this._nativeAudioNode.channelInterpretation}set channelInterpretation(t){this._nativeAudioNode.channelInterpretation=t}get context(){return this._context}get numberOfInputs(){return this._nativeAudioNode.numberOfInputs}get numberOfOutputs(){return this._nativeAudioNode.numberOfOutputs}connect(t,n=0,s=0){if(n<0||n>=this._nativeAudioNode.numberOfOutputs)throw u();const o=w(this._context),g=j(o);if(D(t)||M(t))throw h();if(Object(i.a)(t)){const i=Object(p.a)(t);try{const c=Object(a.a)(this._nativeAudioNode,i,n,s);if(g||y(this)?this._nativeAudioNode.disconnect(...c):y(t)&&Object(x.a)(t),r(t)){const t=e.get(i);if(void 0===t){const t=o.createGain();t.connect(c[0],0,c[2]),e.set(i,new Map([[s,t]]))}else if(void 0===t.get(s)){const e=o.createGain();e.connect(c[0],0,c[2]),t.set(s,e)}}}catch(t){if(12===t.code)throw h();throw t}if(g?((t,e,n,s)=>{const{outputs:i}=Object(l.a)(t);if(Object(m.a)(i,[e,n,s],t=>t[0]===e&&t[1]===n&&t[2]===s,!0)){const{activeInputs:i}=Object(l.a)(e);return k(i,t,[n,s,null],!0),!0}return!1})(this,t,n,s):R(this,t,n,s)){const e=v([this],t);S(e,c(g))}return t}const b=Object(f.a)(t);if("playbackRate"===b.name)throw _();try{this._nativeAudioNode.connect(b,n),(g||y(this))&&this._nativeAudioNode.disconnect(b,n)}catch(t){if(12===t.code)throw h();throw t}if(g?((t,e,n)=>{const{outputs:s}=Object(l.a)(t);if(Object(m.a)(s,[e,n],t=>t[0]===e&&t[1]===n,!0)){const{activeInputs:s}=Object(d.a)(e);return A(s,t,[n,null],!0),!0}return!1})(this,t,n):q(this,t,n)){const e=v([this],t);S(e,c(g))}}disconnect(t,e,n){let s;if(void 0===t)s=(t=>{const e=Object(l.a)(t),n=[];for(const s of e.outputs)Object(o.a)(s)?F(t,...s):V(t,...s),n.push(s[0]);return e.outputs.clear(),n})(this);else if("number"==typeof t){if(t<0||t>=this.numberOfOutputs)throw u();s=((t,e)=>{const n=Object(l.a)(t),s=[];for(const i of n.outputs)i[1]===e&&(Object(o.a)(i)?F(t,...i):V(t,...i),s.push(i[0]),n.outputs.delete(i));return s})(this,t)}else{if(void 0!==e&&(e<0||e>=this.numberOfOutputs))throw u();if(Object(i.a)(t)&&void 0!==n&&(n<0||n>=t.numberOfInputs))throw u();if(s=((t,e,n,s)=>{const i=Object(l.a)(t);return Array.from(i.outputs).filter(t=>!(t[0]!==e||void 0!==n&&t[1]!==n||void 0!==s&&t[2]!==s)).map(e=>(Object(o.a)(e)?F(t,...e):V(t,...e),i.outputs.delete(e),e[0]))})(this,t,e,n),0===s.length)throw h()}for(const t of s){const e=v([this],t);S(e,g)}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return l}));var s=n(2),i=n(43),o=n(35),r=n(41),a=n(0);const c=async(t,e)=>new t(await(t=>new Promise((e,n)=>{const{port1:s,port2:i}=new MessageChannel;s.onmessage=({data:t})=>{s.close(),i.close(),e(t)},s.onmessageerror=({data:t})=>{s.close(),i.close(),n(t)},i.postMessage(t)}))(e));var u=n(36),h=n(40);const l=(t,e,n,l,d,p,f,_,m,g,v,y,b)=>(x,w,T,O)=>{if(0===O.numberOfInputs&&0===O.numberOfOutputs)throw g();if(void 0!==O.outputChannelCount){if(O.outputChannelCount.some(t=>t<1))throw g();if(O.outputChannelCount.length!==O.numberOfOutputs)throw n()}if("explicit"!==O.channelCountMode)throw g();const S=O.channelCount*O.numberOfInputs,C=O.outputChannelCount.reduce((t,e)=>t+e,0),k=void 0===T.parameterDescriptors?0:T.parameterDescriptors.length;if(S+k>6||C>6)throw g();const A=new MessageChannel,D=[],M=[];for(let t=0;tvoid 0===t?0:t},maxValue:{get:()=>void 0===e?s.b:e},minValue:{get:()=>void 0===n?s.a:n}}),j.push(o)}const E=d(x,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,S+k)}),R=Object(i.a)(w,x.sampleRate),q=m(x,R,S+k,Math.max(1,C)),I=p(x,{channelCount:Math.max(1,C),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,C)}),F=[];for(let t=0;t{const n=j[e];return n.connect(E,0,S+e),n.start(0),[t,n.offset]}));E.connect(q);let N=O.channelInterpretation,P=null;const L=0===O.numberOfOutputs?[q]:F,z={get bufferSize(){return R},get channelCount(){return O.channelCount},set channelCount(t){throw l()},get channelCountMode(){return O.channelCountMode},set channelCountMode(t){throw l()},get channelInterpretation(){return N},set channelInterpretation(t){for(const e of D)e.channelInterpretation=t;N=t},get context(){return q.context},get inputs(){return D},get numberOfInputs(){return O.numberOfInputs},get numberOfOutputs(){return O.numberOfOutputs},get onprocessorerror(){return P},set onprocessorerror(t){"function"==typeof P&&z.removeEventListener("processorerror",P),P="function"==typeof t?t:null,"function"==typeof P&&z.addEventListener("processorerror",P)},get parameters(){return V},get port(){return A.port2},addEventListener:(...t)=>q.addEventListener(t[0],t[1],t[2]),connect:e.bind(null,L),disconnect:v.bind(null,L),dispatchEvent:(...t)=>q.dispatchEvent(t[0]),removeEventListener:(...t)=>q.removeEventListener(t[0],t[1],t[2])},B=new Map;var W,U;A.port1.addEventListener=(W=A.port1.addEventListener,(...t)=>{if("message"===t[0]){const e="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;if(null!==e){const n=B.get(t[1]);void 0!==n?t[1]=n:(t[1]=t=>{y(x.currentTime,x.sampleRate,()=>e(t))},B.set(e,t[1]))}}return W.call(A.port1,t[0],t[1],t[2])}),A.port1.removeEventListener=(U=A.port1.removeEventListener,(...t)=>{if("message"===t[0]){const e=B.get(t[1]);void 0!==e&&(B.delete(t[1]),t[1]=e)}return U.call(A.port1,t[0],t[1],t[2])});let G=null;Object.defineProperty(A.port1,"onmessage",{get:()=>G,set:t=>{"function"==typeof G&&A.port1.removeEventListener("message",G),G="function"==typeof t?t:null,"function"==typeof G&&(A.port1.addEventListener("message",G),A.port1.start())}}),T.prototype.port=A.port1;let Y=null;((t,e,n,s)=>{let i=a.k.get(t);void 0===i&&(i=new WeakMap,a.k.set(t,i));const o=c(n,s);return i.set(e,o),o})(x,z,T,O).then(t=>Y=t);const Q=Object(u.a)(O.numberOfInputs,O.channelCount),Z=Object(u.a)(O.numberOfOutputs,O.outputChannelCount),X=void 0===T.parameterDescriptors?[]:T.parameterDescriptors.reduce((t,{name:e})=>({...t,[e]:new Float32Array(128)}),{});let H=!0;const $=()=>{O.numberOfOutputs>0&&q.disconnect(I);for(let t=0,e=0;t{if(null!==Y)for(let s=0;s{Object(o.a)(e,X,t,S+n,s)});for(let t=0;t{const s=t.get(z);return void 0===s||void 0===s.get(n)?[]:e}),i=y(x.currentTime+s/x.sampleRate,x.sampleRate,()=>Y.process(e,Z,X));H=i;for(let t=0,e=0;tq.connect(K).connect(K.context.destination),et=()=>{q.disconnect(K),K.disconnect()};return tt(),b(z,()=>{if(H){et(),O.numberOfOutputs>0&&q.connect(I);for(let t=0,e=0;t{H&&(tt(),$()),J=!1})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return u}));var s=n(0);const i={construct:()=>i},o=/^import(?:(?:[\s]+[\w]+|(?:[\s]+[\w]+[\s]*,)?[\s]*\{[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?(?:[\s]*,[\s]*[\w]+(?:[\s]+as[\s]+[\w]+)?)*[\s]*}|(?:[\s]+[\w]+[\s]*,)?[\s]*\*[\s]+as[\s]+[\w]+)[\s]+from)?(?:[\s]*)("([^"\\]|\\.)+"|'([^'\\]|\\.)+')(?:[\s]*);?/,r=(t,e)=>{const n=[];let s=t.replace(/^[\s]+/,""),i=s.match(o);for(;null!==i;){const t=i[1].slice(1,-1),r=i[0].replace(/([\s]+)?;?$/,"").replace(t,new URL(t,e).toString());n.push(r),s=s.slice(i[0].length).replace(/^[\s]+/,""),i=s.match(o)}return[n.join(";"),s]},a=t=>{if(void 0!==t&&!Array.isArray(t))throw new TypeError("The parameterDescriptors property of given value for processorCtor is not an array.")},c=t=>{if(!(t=>{try{new new Proxy(t,i)}catch{return!1}return!0})(t))throw new TypeError("The given value for processorCtor should be a constructor.");if(null===t.prototype||"object"!=typeof t.prototype)throw new TypeError("The given value for processorCtor should have a prototype.")},u=(t,e,n,i,o,u,h,l,d)=>(p,f,_={credentials:"omit"})=>{const m=u(p),g=new URL(f,d.location.href).toString();if(void 0!==m.audioWorklet)return i(f).then(t=>{const[e,n]=r(t,g),s=new Blob([`${e};(registerProcessor=>{${n}\n})((n,p)=>registerProcessor(n,class extends p{process(i,o,p){return super.process(i.map(j=>j.some(k=>k.length===0)?[]:j),o,p)}}))`],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(s),a=o(m);return(null!==a?a:m).audioWorklet.addModule(i,_).then(()=>URL.revokeObjectURL(i)).catch(t=>{throw URL.revokeObjectURL(i),void 0!==t.code&&"SyntaxError"!==t.name||(t.code=12),t})});const v=l.get(p);if(void 0!==v&&v.has(f))return Promise.resolve();const y=h.get(p);if(void 0!==y){const t=y.get(f);if(void 0!==t)return t}const b=i(f).then(t=>{const[n,s]=r(t,g);return e(`${n};((a,b)=>{(a[b]=a[b]||[]).push((AudioWorkletProcessor,global,registerProcessor,sampleRate,self,window)=>{${s}\n})})(window,'_AWGS')`)}).then(()=>{const e=d._AWGS.pop();if(void 0===e)throw new SyntaxError;n(m.currentTime,m.sampleRate,()=>e(class{},void 0,(e,n)=>{if(""===e.trim())throw t();const i=s.j.get(m);if(void 0!==i){if(i.has(e))throw t();c(n),a(n.parameterDescriptors),i.set(e,n)}else c(n),a(n.parameterDescriptors),s.j.set(m,new Map([[e,n]]))},m.sampleRate,void 0,void 0))}).catch(t=>{throw void 0!==t.code&&"SyntaxError"!==t.name||(t.code=12),t});return void 0===y?h.set(p,new Map([[f,b]])):y.set(f,b),b.then(()=>{const t=l.get(p);void 0===t?l.set(p,new Set([f])):t.add(f)}).catch(()=>{}).then(()=>{const t=h.get(p);void 0!==t&&t.delete(f)}),b}},function(t,e,n){"use strict";n.d(e,"a",(function(){return r}));var s=n(4),i=n(1);const o=t=>"function"==typeof t.getFloatTimeDomainData,r=(t,e,n)=>(r,a)=>{const c=n(r,t=>t.createAnalyser());if(Object(i.a)(c,a),!(a.maxDecibels>a.minDecibels))throw e();return Object(s.a)(c,a,"fftSize"),Object(s.a)(c,a,"maxDecibels"),Object(s.a)(c,a,"minDecibels"),Object(s.a)(c,a,"smoothingTimeConstant"),t(o,()=>o(c))||(t=>{t.getFloatTimeDomainData=e=>{const n=new Uint8Array(e.length);t.getByteTimeDomainData(n);const s=Math.max(n.length,t.fftSize);for(let t=0;t(y,b={})=>{const x=n(y,t=>t.createBufferSource());return Object(o.a)(x,b),Object(s.a)(x,b,"playbackRate"),Object(i.a)(x,b,"buffer"),Object(i.a)(x,b,"loop"),Object(i.a)(x,b,"loopEnd"),Object(i.a)(x,b,"loopStart"),e(u,()=>u(y))||(t=>{t.start=(e=>{let n=!1;return(s=0,i=0,o)=>{if(n)throw Object(r.a)();e.call(t,s,i,o),n=!0}})(t.start)})(x),e(h,h)||((t,e)=>{let n=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;var i,o;t.start=(i=t.start,o=t.stop,(r=0,a=0,c=Number.POSITIVE_INFINITY)=>{if(i.call(t,r,a),c>=0&&c(o=0)=>{s=Math.max(o,e.currentTime),i.call(t,Math.min(n,s))})(t.stop)})(x,y),e(l,()=>l(y))||m(x),e(d,()=>d(y))||g(x,y),e(p,()=>p(y))||Object(a.a)(x),e(f,()=>f(y))||v(x,y),e(_,()=>_(y))||Object(c.a)(x),t(y,x),x}},function(t,e,n){"use strict";n.d(e,"a",(function(){return d}));var s=n(35),i=n(41),o=n(36),r=n(8),a=n(0),c=n(6),u=n(9);var h=n(3);const l=async(t,e,n,h,l,d)=>{const p=null===e?128*Math.ceil(t.context.length/128):e.length,f=h.channelCount*h.numberOfInputs,_=h.outputChannelCount.reduce((t,e)=>t+e,0),m=0===_?null:n.createBuffer(_,p,n.sampleRate);if(void 0===l)throw new Error("Missing the processor constructor.");const g=Object(r.a)(t),v=await((t,e)=>{const n=Object(u.a)(a.k,t),s=Object(c.a)(e);return Object(u.a)(n,s)})(n,t),y=Object(o.a)(h.numberOfInputs,h.channelCount),b=Object(o.a)(h.numberOfOutputs,h.outputChannelCount),x=Array.from(t.parameters.keys()).reduce((t,e)=>({...t,[e]:new Float32Array(128)}),{});for(let o=0;o0&&null!==e)for(let t=0;t{Object(s.a)(e,x,t,f+n,o)});for(let t=0;t0===g.activeInputs[e].size?[]:t),e=d(o/n.sampleRate,n.sampleRate,()=>v.process(t,b,x));if(null!==m)for(let t=0,e=0;t(v,y,b)=>{const x=new WeakMap;let w=null;return{render(T,O,S){a(O,T);const C=x.get(O);return void 0!==C?Promise.resolve(C):(async(a,T,O)=>{let S=d(a),C=null;const k=Object(h.a)(S,T);if(null===p){const t=y.outputChannelCount.reduce((t,e)=>t+e,0),n=i(T,{channelCount:Math.max(1,t),channelCountMode:"explicit",channelInterpretation:"discrete",numberOfOutputs:Math.max(1,t)}),o=[];for(let t=0;t{const c=new f(n,128*Math.ceil(a.context.length/128),T.sampleRate),u=[],h=[];for(let t=0;t{const e=o(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",offset:t.value});return await _(c,t,e.offset,O),e})),d=s(c,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"speakers",numberOfInputs:Math.max(1,t+e)});for(let t=0;tm(a,c,t,O))),g(c)};w=l(a,0===n?null:await c(),T,y,b,u)}const t=await w,e=n(T),[c,h,d]=C;null!==t&&(e.buffer=t,e.start(0)),e.connect(c);for(let t=0,e=0;t(f,_)=>{const m=a(f)?f:r(f);if(o.has(_)){const t=n();return Promise.reject(t)}try{o.add(_)}catch{}if(e(l,()=>l(m))){return("closed"===m.state&&null!==u&&c(m)?new u(1,1,m.sampleRate):m).decodeAudioData(_).catch(t=>{if(t instanceof DOMException&&"NotSupportedError"===t.name)throw new TypeError;throw t}).then(n=>(e(h,()=>h(n))||p(n),t.add(n),n))}return new Promise((e,n)=>{const o=()=>{try{(t=>{const{port1:e}=new MessageChannel;e.postMessage(t,[t])})(_)}catch{}},r=t=>{n(t),o()};try{m.decodeAudioData(_,n=>{"function"!=typeof n.copyFromChannel&&(d(n),Object(s.a)(n)),t.add(n),o(),e(n)},t=>{r(null===t?i():t)})}catch(t){r(t)}})}},function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var s=n(24);const i=(t,e,n)=>function i(o,r){const a=Object(s.a)(r)?r:n(t,r);if((t=>"delayTime"in t)(a))return[];if(o[0]===a)return[o];if(o.includes(a))return[];const{outputs:c}=e(a);return Array.from(c).map(t=>i([...o,a],t[0])).reduce((t,e)=>t.concat(e),[])}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(37);const i={channelCount:2,channelCountMode:"max",channelInterpretation:"speakers"},o=(t,e,n,o,r)=>class extends t{constructor(t,a){const c=o(t),u=r(c),h={...i,...a},l=e(c,u?null:t.baseLatency,h);super(t,!1,l,u?n(h.feedback,h.feedforward):null),(t=>{var e;t.getFrequencyResponse=(e=t.getFrequencyResponse,(n,i,o)=>{if(n.length!==i.length||i.length!==o.length)throw Object(s.a)();return e.call(t,n,i,o)})})(l),this._nativeIIRFilterNode=l}getFrequencyResponse(t,e,n){return this._nativeIIRFilterNode.getFrequencyResponse(t,e,n)}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return s}));const s=(t,e,n,s,i,o)=>(r,a,c,u,h,l)=>{if(null!==c)try{const n=e(r,t=>new c(t,u,l)),i=new Map;let a=null;if(Object.defineProperties(n,{channelCount:{get:()=>l.channelCount,set:()=>{throw t()}},channelCountMode:{get:()=>"explicit",set:()=>{throw t()}},onprocessorerror:{get:()=>a,set:t=>{"function"==typeof a&&n.removeEventListener("processorerror",a),a="function"==typeof t?t:null,"function"==typeof a&&n.addEventListener("processorerror",a)}}}),n.addEventListener=(p=n.addEventListener,(...t)=>{if("processorerror"===t[0]){const e="function"==typeof t[1]?t[1]:"object"==typeof t[1]&&null!==t[1]&&"function"==typeof t[1].handleEvent?t[1].handleEvent:null;if(null!==e){const n=i.get(t[1]);void 0!==n?t[1]=n:(t[1]=n=>{e(new ErrorEvent(t[0],{...n,error:new Error}))},i.set(e,t[1]))}}return p.call(n,t[0],t[1],t[2])}),n.removeEventListener=(d=n.removeEventListener,(...t)=>{if("processorerror"===t[0]){const e=i.get(t[1]);void 0!==e&&(i.delete(t[1]),t[1]=e)}return d.call(n,t[0],t[1],t[2])}),0!==l.numberOfOutputs){const t=s(r,{channelCount:1,channelCountMode:"explicit",channelInterpretation:"discrete",gain:0});return n.connect(t).connect(t.context.destination),o(n,()=>t.disconnect(),()=>t.connect(t.context.destination))}return n}catch(t){if(11===t.code)throw i();throw t}var d,p;if(void 0===h)throw i();return(t=>{const{port1:e}=new MessageChannel;try{e.postMessage(t)}finally{e.close()}})(l),n(r,a,h,l)}},function(t,e,n){"use strict";n.d(e,"a",(function(){return o}));var s=n(1),i=n(7);const o=t=>(e,n)=>{const o=t(e,t=>t.createChannelSplitter(n.numberOfOutputs));return Object(s.a)(o,n),(t=>{const e=t.numberOfOutputs;Object.defineProperty(t,"channelCount",{get:()=>e,set:t=>{if(t!==e)throw Object(i.a)()}}),Object.defineProperty(t,"channelCountMode",{get:()=>"explicit",set:t=>{if("explicit"!==t)throw Object(i.a)()}}),Object.defineProperty(t,"channelInterpretation",{get:()=>"discrete",set:t=>{if("discrete"!==t)throw Object(i.a)()}})})(o),o}},function(t,e,n){var s=n(677),i=n(678),o=n(679),r=n(681);t.exports=function(t,e){return s(t)||i(t,e)||o(t,e)||r()}},function(t,e){t.exports=function(t){if(Array.isArray(t))return t}},function(t,e){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var n=[],s=!0,i=!1,o=void 0;try{for(var r,a=t[Symbol.iterator]();!(s=(r=a.next()).done)&&(n.push(r.value),!e||n.length!==e);s=!0);}catch(t){i=!0,o=t}finally{try{s||null==a.return||a.return()}finally{if(i)throw o}}return n}}},function(t,e,n){var s=n(680);t.exports=function(t,e){if(t){if("string"==typeof t)return s(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(t,e):void 0}}},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,s=new Array(e);n=0;a--)(i=t[a])&&(r=(o<3?i(r):o>3?i(e,n,r):i(e,n))||r);return o>3&&r&&Object.defineProperty(e,n,r),r}function S(t,e,n,s){return new(n||(n=Promise))((function(i,o){function r(t){try{c(s.next(t))}catch(t){o(t)}}function a(t){try{c(s.throw(t))}catch(t){o(t)}}function c(t){t.done?i(t.value):new n((function(e){e(t.value)})).then(r,a)}c((s=s.apply(t,e||[])).next())}))}class C{constructor(t,e,n){this._callback=t,this._type=e,this._updateInterval=n,this._createClock()}_createWorker(){const t=new Blob([`\n\t\t\t// the initial timeout time\n\t\t\tlet timeoutTime =  ${(1e3*this._updateInterval).toFixed(1)};\n\t\t\t// onmessage callback\n\t\t\tself.onmessage = function(msg){\n\t\t\t\ttimeoutTime = parseInt(msg.data);\n\t\t\t};\n\t\t\t// the tick function which posts a message\n\t\t\t// and schedules a new tick\n\t\t\tfunction tick(){\n\t\t\t\tsetTimeout(tick, timeoutTime);\n\t\t\t\tself.postMessage('tick');\n\t\t\t}\n\t\t\t// call tick initially\n\t\t\ttick();\n\t\t\t`],{type:"text/javascript"}),e=URL.createObjectURL(t),n=new Worker(e);n.onmessage=this._callback.bind(this),this._worker=n}_createTimeout(){this._timeout=setTimeout(()=>{this._createTimeout(),this._callback()},1e3*this._updateInterval)}_createClock(){if("worker"===this._type)try{this._createWorker()}catch(t){this._type="timeout",this._createClock()}else"timeout"===this._type&&this._createTimeout()}_disposeClock(){this._timeout&&(clearTimeout(this._timeout),this._timeout=0),this._worker&&(this._worker.terminate(),this._worker.onmessage=null)}get updateInterval(){return this._updateInterval}set updateInterval(t){this._updateInterval=Math.max(t,128/44100),"worker"===this._type&&this._worker.postMessage(Math.max(1e3*t,1))}get type(){return this._type}set type(t){this._disposeClock(),this._type=t,this._createClock()}dispose(){this._disposeClock()}}function k(t){return Object(o.isAnyAudioParam)(t)}function A(t){return Object(o.isAnyAudioNode)(t)}function D(t){return Object(o.isAnyOfflineAudioContext)(t)}function M(t){return Object(o.isAnyAudioContext)(t)}function j(t){return t instanceof AudioBuffer}function E(t,e){return"value"===t||k(e)||A(e)||j(e)}function R(t,...e){if(!e.length)return t;const n=e.shift();if(g(t)&&g(n))for(const e in n)E(e,n[e])?t[e]=n[e]:g(n[e])?(t[e]||Object.assign(t,{[e]:{}}),R(t[e],n[e])):Object.assign(t,{[e]:n[e]});return R(t,...e)}function q(t,e,n=[],s){const i={},o=Array.from(e);if(g(o[0])&&s&&!Reflect.has(o[0],s)){Object.keys(o[0]).some(e=>Reflect.has(t,e))||(R(i,{[s]:o[0]}),n.splice(n.indexOf(s),1),o.shift())}if(1===o.length&&g(o[0]))R(i,o[0]);else for(let t=0;t{Reflect.has(t,e)&&delete t[e]}),t}
-/**
- * Tone.js
- * @author Yotam Mann
- * @license http://opensource.org/licenses/MIT MIT License
- * @copyright 2014-2019 Yotam Mann
- */class V{constructor(){this.debug=!1,this._wasDisposed=!1}static getDefaults(){return{}}log(...t){(this.debug||w&&this.toString()===w.TONE_DEBUG_CLASS)&&l(this,...t)}dispose(){return this._wasDisposed=!0,this}get disposed(){return this._wasDisposed}toString(){return this.name}}V.version=i;function N(t,e){return t>e+1e-6}function P(t,e){return N(t,e)||z(t,e)}function L(t,e){return t+1e-6this.memory){const t=this.length-this.memory;this._timeline.splice(0,t)}return this}remove(t){const e=this._timeline.indexOf(t);return-1!==e&&this._timeline.splice(e,1),this}get(t,e="time"){const n=this._search(t,e);return-1!==n?this._timeline[n]:null}peek(){return this._timeline[0]}shift(){return this._timeline.shift()}getAfter(t,e="time"){const n=this._search(t,e);return n+10&&this._timeline[e-1].time=0?this._timeline[n-1]:null}cancel(t){if(this._timeline.length>1){let e=this._search(t);if(e>=0)if(z(this._timeline[e].time,t)){for(let n=e;n>=0&&z(this._timeline[n].time,t);n--)e=n;this._timeline=this._timeline.slice(0,e)}else this._timeline=this._timeline.slice(0,e+1);else this._timeline=[]}else 1===this._timeline.length&&P(this._timeline[0].time,t)&&(this._timeline=[]);return this}cancelBefore(t){const e=this._search(t);return e>=0&&(this._timeline=this._timeline.slice(e+1)),this}previousEvent(t){const e=this._timeline.indexOf(t);return e>0?this._timeline[e-1]:null}_search(t,e="time"){if(0===this._timeline.length)return-1;let n=0;const s=this._timeline.length;let i=s;if(s>0&&this._timeline[s-1][e]<=t)return s-1;for(;n=0&&this._timeline[n].time>=t;)n--;return this._iterate(e,n+1),this}forEachAtTime(t,e){const n=this._search(t);if(-1!==n&&z(this._timeline[n].time,t)){let s=n;for(let e=n;e>=0&&z(this._timeline[e].time,t);e--)s=e;this._iterate(t=>{e(t)},s,n)}return this}dispose(){return super.dispose(),this._timeline=[],this}}const U=[];function G(t){U.push(t)}const Y=[];function Q(t){Y.push(t)}class Z extends V{constructor(){super(...arguments),this.name="Emitter"}on(t,e){return t.split(/\W+/).forEach(t=>{p(this._events)&&(this._events={}),this._events.hasOwnProperty(t)||(this._events[t]=[]),this._events[t].push(e)}),this}once(t,e){const n=(...s)=>{e(...s),this.off(t,n)};return this.on(t,n),this}off(t,e){return t.split(/\W+/).forEach(n=>{if(p(this._events)&&(this._events={}),this._events.hasOwnProperty(t))if(p(e))this._events[t]=[];else{const n=this._events[t];for(let t=0;t{const n=Object.getOwnPropertyDescriptor(Z.prototype,e);Object.defineProperty(t.prototype,e,n)})}dispose(){return super.dispose(),this._events=void 0,this}}class X extends Z{constructor(){super(...arguments),this.isOffline=!1}}class H extends X{constructor(){super(),this.name="Context",this._constants=new Map,this._timeouts=new W,this._timeoutIds=0,this._initialized=!1,this.isOffline=!1,this._workletModules=new Map;const t=q(H.getDefaults(),arguments,["context"]);t.context?this._context=t.context:this._context=function(t){return new o.AudioContext(t)}({latencyHint:t.latencyHint}),this._ticker=new C(this.emit.bind(this,"tick"),t.clockSource,t.updateInterval),this.on("tick",this._timeoutLoop.bind(this)),this._context.onstatechange=()=>{this.emit("statechange",this.state)},this._setLatencyHint(t.latencyHint),this.lookAhead=t.lookAhead}static getDefaults(){return{clockSource:"worker",latencyHint:"interactive",lookAhead:.1,updateInterval:.05}}initialize(){var t;return this._initialized||(t=this,U.forEach(e=>e(t)),this._initialized=!0),this}createAnalyser(){return this._context.createAnalyser()}createOscillator(){return this._context.createOscillator()}createBufferSource(){return this._context.createBufferSource()}createBiquadFilter(){return this._context.createBiquadFilter()}createBuffer(t,e,n){return this._context.createBuffer(t,e,n)}createChannelMerger(t){return this._context.createChannelMerger(t)}createChannelSplitter(t){return this._context.createChannelSplitter(t)}createConstantSource(){return this._context.createConstantSource()}createConvolver(){return this._context.createConvolver()}createDelay(t){return this._context.createDelay(t)}createDynamicsCompressor(){return this._context.createDynamicsCompressor()}createGain(){return this._context.createGain()}createIIRFilter(t,e){return this._context.createIIRFilter(t,e)}createPanner(){return this._context.createPanner()}createPeriodicWave(t,e,n){return this._context.createPeriodicWave(t,e,n)}createStereoPanner(){return this._context.createStereoPanner()}createWaveShaper(){return this._context.createWaveShaper()}createMediaStreamSource(t){return r(M(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamSource(t)}createMediaStreamDestination(){return r(M(this._context),"Not available if OfflineAudioContext"),this._context.createMediaStreamDestination()}decodeAudioData(t){return this._context.decodeAudioData(t)}get currentTime(){return this._context.currentTime}get state(){return this._context.state}get sampleRate(){return this._context.sampleRate}get listener(){return this.initialize(),this._listener}set listener(t){r(!this._initialized,"The listener cannot be set after initialization."),this._listener=t}get transport(){return this.initialize(),this._transport}set transport(t){r(!this._initialized,"The transport cannot be set after initialization."),this._transport=t}get draw(){return this.initialize(),this._draw}set draw(t){r(!this._initialized,"Draw cannot be set after initialization."),this._draw=t}get destination(){return this.initialize(),this._destination}set destination(t){r(!this._initialized,"The destination cannot be set after initialization."),this._destination=t}createAudioWorkletNode(t,e){return function(t,e,n){return r(f(o.AudioWorkletNode),"This node only works in a secure context (https or localhost)"),new o.AudioWorkletNode(t,e,n)}
-/*! *****************************************************************************
-Copyright (c) Microsoft Corporation. All rights reserved.
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at http://www.apache.org/licenses/LICENSE-2.0
-
-THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
-WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
-MERCHANTABLITY OR NON-INFRINGEMENT.
-
-See the Apache Version 2.0 License for specific language governing permissions
-and limitations under the License.
-***************************************************************************** */(this.rawContext,t,e)}addAudioWorkletModule(t,e){return S(this,void 0,void 0,(function*(){r(f(this.rawContext.audioWorklet),"AudioWorkletNode is only available in a secure context (https or localhost)"),this._workletModules.has(e)||this._workletModules.set(e,this.rawContext.audioWorklet.addModule(t)),yield this._workletModules.get(e)}))}workletsAreReady(){return S(this,void 0,void 0,(function*(){const t=[];this._workletModules.forEach(e=>t.push(e)),yield Promise.all(t)}))}get updateInterval(){return this._ticker.updateInterval}set updateInterval(t){this._ticker.updateInterval=t}get clockSource(){return this._ticker.type}set clockSource(t){this._ticker.type=t}get latencyHint(){return this._latencyHint}_setLatencyHint(t){let e=0;if(this._latencyHint=t,b(t))switch(t){case"interactive":e=.1;break;case"playback":e=.5;break;case"balanced":e=.25}this.lookAhead=e,this.updateInterval=e/2}get rawContext(){return this._context}now(){return this._context.currentTime+this.lookAhead}immediate(){return this._context.currentTime}resume(){return"suspended"===this._context.state&&M(this._context)?this._context.resume():Promise.resolve()}close(){return S(this,void 0,void 0,(function*(){var t;M(this._context)&&(yield this._context.close()),this._initialized&&(t=this,Y.forEach(e=>e(t)))}))}getConstant(t){if(this._constants.has(t))return this._constants.get(t);{const e=this._context.createBuffer(1,128,this._context.sampleRate),n=e.getChannelData(0);for(let e=0;ethis._constants[t].disconnect()),this}_timeoutLoop(){const t=this.now();let e=this._timeouts.peek();for(;this._timeouts.length&&e&&e.time<=t;)e.callback(),this._timeouts.shift(),e=this._timeouts.peek()}setTimeout(t,e){this._timeoutIds++;const n=this.now();return this._timeouts.add({callback:t,id:this._timeoutIds,time:n+e}),this._timeoutIds}clearTimeout(t){return this._timeouts.forEach(e=>{e.id===t&&this._timeouts.remove(e)}),this}clearInterval(t){return this.clearTimeout(t)}setInterval(t,e){const n=++this._timeoutIds,s=()=>{const i=this.now();this._timeouts.add({callback:()=>{t(),s()},id:n,time:i+e})};return s(),n}}function $(t,e){y(e)?e.forEach(e=>$(t,e)):Object.defineProperty(t,e,{enumerable:!0,writable:!1})}function J(t,e){y(e)?e.forEach(e=>J(t,e)):Object.defineProperty(t,e,{writable:!0})}const K=()=>{};class tt extends V{constructor(){super(),this.name="ToneAudioBuffer",this.onload=K;const t=q(tt.getDefaults(),arguments,["url","onload","onerror"]);this.reverse=t.reverse,this.onload=t.onload,t.url&&j(t.url)||t.url instanceof tt?this.set(t.url):b(t.url)&&this.load(t.url).catch(t.onerror)}static getDefaults(){return{onerror:K,onload:K,reverse:!1}}get sampleRate(){return this._buffer?this._buffer.sampleRate:it().sampleRate}set(t){return t instanceof tt?t.loaded?this._buffer=t.get():t.onload=()=>{this.set(t),this.onload(this)}:this._buffer=t,this._reversed&&this._reverse(),this}get(){return this._buffer}load(t){return S(this,void 0,void 0,(function*(){const e=tt.load(t).then(t=>{this.set(t),this.onload(this)});tt.downloads.push(e);try{yield e}finally{const t=tt.downloads.indexOf(e);tt.downloads.splice(t,1)}return this}))}dispose(){return super.dispose(),this._buffer=void 0,this}fromArray(t){const e=y(t)&&t[0].length>0,n=e?t.length:1,s=e?t[0].length:t.length,i=it(),o=i.createBuffer(n,s,i.sampleRate),r=e||1!==n?t:[t];for(let t=0;tt/e),this.fromArray(t)}return this}toArray(t){if(m(t))return this.getChannelData(t);if(1===this.numberOfChannels)return this.toArray(0);{const t=[];for(let e=0;e0}get duration(){return this._buffer?this._buffer.duration:0}get length(){return this._buffer?this._buffer.length:0}get numberOfChannels(){return this._buffer?this._buffer.numberOfChannels:0}get reverse(){return this._reversed}set reverse(t){this._reversed!==t&&(this._reversed=t,this._reverse())}static fromArray(t){return(new tt).fromArray(t)}static fromUrl(t){return S(this,void 0,void 0,(function*(){const e=new tt;return yield e.load(t)}))}static load(t){return S(this,void 0,void 0,(function*(){const e=t.match(/\[(.+\|?)+\]$/);if(e){const n=e[1].split("|");let s=n[0];for(const t of n)if(tt.supportsType(t)){s=t;break}t=t.replace(e[0],s)}const n=""===tt.baseUrl||tt.baseUrl.endsWith("/")?tt.baseUrl:tt.baseUrl+"/",s=yield fetch(n+t);if(!s.ok)throw new Error("could not load url: "+t);const i=yield s.arrayBuffer();return yield it().decodeAudioData(i)}))}static supportsType(t){const e=t.split("."),n=e[e.length-1];return""!==document.createElement("audio").canPlayType("audio/"+n)}static loaded(){return S(this,void 0,void 0,(function*(){for(yield Promise.resolve();tt.downloads.length;)yield tt.downloads[0]}))}}tt.baseUrl="",tt.downloads=[];class et extends H{constructor(){var t,e,n;super({clockSource:"offline",context:D(arguments[0])?arguments[0]:(t=arguments[0],e=arguments[1]*arguments[2],n=arguments[2],new o.OfflineAudioContext(t,e,n)),lookAhead:0,updateInterval:D(arguments[0])?128/arguments[0].sampleRate:128/arguments[2]}),this.name="OfflineContext",this._currentTime=0,this.isOffline=!0,this._duration=D(arguments[0])?arguments[0].length/arguments[0].sampleRate:arguments[1]}now(){return this._currentTime}get currentTime(){return this._currentTime}_renderClock(t){return S(this,void 0,void 0,(function*(){let e=0;for(;this._duration-this._currentTime>=0;){this.emit("tick"),this._currentTime+=128/this.sampleRate,e++;const n=Math.floor(this.sampleRate/128);t&&e%n==0&&(yield new Promise(t=>setTimeout(t,1)))}}))}render(t=!0){return S(this,void 0,void 0,(function*(){yield this.workletsAreReady(),yield this._renderClock(t);const e=yield this._context.startRendering();return new tt(e)}))}close(){return Promise.resolve()}}const nt=new class extends X{constructor(){super(...arguments),this.lookAhead=0,this.latencyHint=0,this.isOffline=!1}createAnalyser(){return{}}createOscillator(){return{}}createBufferSource(){return{}}createBiquadFilter(){return{}}createBuffer(t,e,n){return{}}createChannelMerger(t){return{}}createChannelSplitter(t){return{}}createConstantSource(){return{}}createConvolver(){return{}}createDelay(t){return{}}createDynamicsCompressor(){return{}}createGain(){return{}}createIIRFilter(t,e){return{}}createPanner(){return{}}createPeriodicWave(t,e,n){return{}}createStereoPanner(){return{}}createWaveShaper(){return{}}createMediaStreamSource(t){return{}}createMediaStreamDestination(){return{}}decodeAudioData(t){return Promise.resolve({})}createAudioWorkletNode(t,e){return{}}get rawContext(){return{}}addAudioWorkletModule(t,e){return S(this,void 0,void 0,(function*(){return Promise.resolve()}))}resume(){return Promise.resolve()}setTimeout(t,e){return 0}clearTimeout(t){return this}setInterval(t,e){return 0}clearInterval(t){return this}getConstant(t){return{}}get currentTime(){return 0}get state(){return{}}get sampleRate(){return 0}get listener(){return{}}get transport(){return{}}get draw(){return{}}set draw(t){}get destination(){return{}}set destination(t){}now(){return 0}immediate(){return 0}};let st=nt;function it(){return st===nt&&T&&ot(new H),st}function ot(t){st=M(t)?new H(t):D(t)?new et(t):t}function rt(){return st.resume()}if(w&&!w.TONE_SILENCE_LOGGING){let t="v";"dev"===i&&(t="");const e=` * Tone.js ${t}${i} * `;console.log("%c"+e,"background: #000; color: #fff")}function at(t){return Math.pow(10,t/20)}function ct(t){return Math.log(t)/Math.LN10*20}function ut(t){return Math.pow(2,t/12)}let ht=440;function lt(t){return Math.round(dt(t))}function dt(t){return 69+12*Math.log2(t/ht)}function pt(t){return ht*Math.pow(2,(t-69)/12)}class ft extends V{constructor(t,e,n){super(),this.defaultUnits="s",this._val=e,this._units=n,this.context=t,this._expressions=this._getExpressions()}_getExpressions(){return{hz:{method:t=>this._frequencyToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)hz$/i},i:{method:t=>this._ticksToUnits(parseInt(t,10)),regexp:/^(\d+)i$/i},m:{method:t=>this._beatsToUnits(parseInt(t,10)*this._getTimeSignature()),regexp:/^(\d+)m$/i},n:{method:(t,e)=>{const n=parseInt(t,10),s="."===e?1.5:1;return 1===n?this._beatsToUnits(this._getTimeSignature())*s:this._beatsToUnits(4/n)*s},regexp:/^(\d+)n(\.?)$/i},number:{method:t=>this._expressions[this.defaultUnits].method.call(this,t),regexp:/^(\d+(?:\.\d+)?)$/},s:{method:t=>this._secondsToUnits(parseFloat(t)),regexp:/^(\d+(?:\.\d+)?)s$/},samples:{method:t=>parseInt(t,10)/this.context.sampleRate,regexp:/^(\d+)samples$/},t:{method:t=>{const e=parseInt(t,10);return this._beatsToUnits(8/(3*Math.floor(e)))},regexp:/^(\d+)t$/i},tr:{method:(t,e,n)=>{let s=0;return t&&"0"!==t&&(s+=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s+=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s+=this._beatsToUnits(parseFloat(n)/4)),s},regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?$/}}}valueOf(){if(this._val instanceof ft&&this.fromType(this._val),p(this._val))return this._noArg();if(b(this._val)&&p(this._units)){for(const t in this._expressions)if(this._expressions[t].regexp.test(this._val.trim())){this._units=t;break}}else if(g(this._val)){let t=0;for(const e in this._val)if(f(this._val[e])){const n=this._val[e];t+=new this.constructor(this.context,e).valueOf()*n}return t}if(f(this._units)){const t=this._expressions[this._units],e=this._val.toString().trim().match(t.regexp);return e?t.method.apply(this,e.slice(1)):t.method.call(this,this._val)}return b(this._val)?parseFloat(this._val):this._val}_frequencyToUnits(t){return 1/t}_beatsToUnits(t){return 60/this._getBpm()*t}_secondsToUnits(t){return t}_ticksToUnits(t){return t*this._beatsToUnits(1)/this._getPPQ()}_noArg(){return this._now()}_getBpm(){return this.context.transport.bpm.value}_getTimeSignature(){return this.context.transport.timeSignature}_getPPQ(){return this.context.transport.PPQ}fromType(t){switch(this._units=void 0,this.defaultUnits){case"s":this._val=t.toSeconds();break;case"i":this._val=t.toTicks();break;case"hz":this._val=t.toFrequency();break;case"midi":this._val=t.toMidi()}return this}toFrequency(){return 1/this.toSeconds()}toSamples(){return this.toSeconds()*this.context.sampleRate}toMilliseconds(){return 1e3*this.toSeconds()}}class _t extends ft{constructor(){super(...arguments),this.name="TimeClass"}_getExpressions(){return Object.assign(super._getExpressions(),{now:{method:t=>this._now()+new this.constructor(this.context,t).valueOf(),regexp:/^\+(.+)/},quantize:{method:t=>{const e=new _t(this.context,t).valueOf();return this._secondsToUnits(this.context.transport.nextSubdivision(e))},regexp:/^@(.+)/}})}quantize(t,e=1){const n=new this.constructor(this.context,t).valueOf(),s=this.valueOf();return s+(Math.round(s/n)*n-s)*e}toNotation(){const t=this.toSeconds(),e=["1m"];for(let t=1;t<9;t++){const n=Math.pow(2,t);e.push(n+"n."),e.push(n+"n"),e.push(n+"t")}e.push("0");let n=e[0],s=new _t(this.context,e[0]).toSeconds();return e.forEach(e=>{const i=new _t(this.context,e).toSeconds();Math.abs(i-t)3&&(s=parseFloat(parseFloat(i).toFixed(3))),[n,e,s].join(":")}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.round(e*this._getPPQ())}toSeconds(){return this.valueOf()}toMidi(){return lt(this.toFrequency())}_now(){return this.context.now()}}function mt(t,e){return new _t(it(),t,e)}class gt extends _t{constructor(){super(...arguments),this.name="Frequency",this.defaultUnits="hz"}static get A4(){return ht}static set A4(t){!function(t){ht=t}(t)}_getExpressions(){return Object.assign({},super._getExpressions(),{midi:{regexp:/^(\d+(?:\.\d+)?midi)/,method(t){return"midi"===this.defaultUnits?t:gt.mtof(t)}},note:{regexp:/^([a-g]{1}(?:b|#|x|bb)?)(-?[0-9]+)/i,method(t,e){const n=vt[t.toLowerCase()]+12*(parseInt(e,10)+1);return"midi"===this.defaultUnits?n:gt.mtof(n)}},tr:{regexp:/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?):?(\d+(?:\.\d+)?)?/,method(t,e,n){let s=1;return t&&"0"!==t&&(s*=this._beatsToUnits(this._getTimeSignature()*parseFloat(t))),e&&"0"!==e&&(s*=this._beatsToUnits(parseFloat(e))),n&&"0"!==n&&(s*=this._beatsToUnits(parseFloat(n)/4)),s}}})}transpose(t){return new gt(this.context,this.valueOf()*ut(t))}harmonize(t){return t.map(t=>this.transpose(t))}toMidi(){return lt(this.valueOf())}toNote(){const t=this.toFrequency(),e=Math.log2(t/gt.A4);let n=Math.round(12*e)+57;const s=Math.floor(n/12);return s<0&&(n+=-12*s),yt[n%12]+s.toString()}toSeconds(){return 1/super.toSeconds()}toTicks(){const t=this._beatsToUnits(1),e=this.valueOf()/t;return Math.floor(e*this._getPPQ())}_noArg(){return 0}_frequencyToUnits(t){return t}_ticksToUnits(t){return 1/(60*t/(this._getBpm()*this._getPPQ()))}_beatsToUnits(t){return 1/super._beatsToUnits(t)}_secondsToUnits(t){return 1/t}static mtof(t){return pt(t)}static ftom(t){return lt(t)}}const vt={cbb:-2,cb:-1,c:0,"c#":1,cx:2,dbb:0,db:1,d:2,"d#":3,dx:4,ebb:2,eb:3,e:4,"e#":5,ex:6,fbb:3,fb:4,f:5,"f#":6,fx:7,gbb:5,gb:6,g:7,"g#":8,gx:9,abb:7,ab:8,a:9,"a#":10,ax:11,bbb:9,bb:10,b:11,"b#":12,bx:13},yt=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function bt(t,e){return new gt(it(),t,e)}class xt extends _t{constructor(){super(...arguments),this.name="TransportTime"}_now(){return this.context.transport.seconds}}function wt(t,e){return new xt(it(),t,e)}class Tt extends V{constructor(){super();const t=q(Tt.getDefaults(),arguments,["context"]);this.defaultContext?this.context=this.defaultContext:this.context=t.context}static getDefaults(){return{context:it()}}now(){return this.context.currentTime+this.context.lookAhead}immediate(){return this.context.currentTime}get sampleTime(){return 1/this.context.sampleRate}get blockTime(){return 128/this.context.sampleRate}toSeconds(t){return new _t(this.context,t).toSeconds()}toFrequency(t){return new gt(this.context,t).toFrequency()}toTicks(t){return new xt(this.context,t).toTicks()}_getPartialProperties(t){const e=this.get();return Object.keys(e).forEach(n=>{p(t[n])&&delete e[n]}),e}get(){const t=this.constructor.getDefaults();return Object.keys(t).forEach(e=>{if(Reflect.has(this,e)){const n=this[e];f(n)&&f(n.value)&&f(n.setValueAtTime)?t[e]=n.value:n instanceof Tt?t[e]=n._getPartialProperties(t[e]):y(n)||m(n)||b(n)||v(n)?t[e]=n:delete t[e]}}),t}set(t){return Object.keys(t).forEach(e=>{Reflect.has(this,e)&&f(this[e])&&(this[e]&&f(this[e].value)&&f(this[e].setValueAtTime)?this[e].value!==t[e]&&(this[e].value=t[e]):this[e]instanceof Tt?this[e].set(t[e]):this[e]=t[e])}),this}}class Ot extends W{constructor(t="stopped"){super(),this.name="StateTimeline",this._initial=t,this.setStateAtTime(this._initial,0)}getValueAtTime(t){const e=this.get(t);return null!==e?e.state:this._initial}setStateAtTime(t,e,n){return a(e,0),this.add(Object.assign({},n,{state:t,time:e})),this}getLastState(t,e){for(let n=this._search(e);n>=0;n--){const e=this._timeline[n];if(e.state===t)return e}}getNextState(t,e){const n=this._search(e);if(-1!==n)for(let e=n;e0,"timeConstant must be a number greater than 0");const i=this.toSeconds(e);return this._assertRange(s),r(isFinite(s)&&isFinite(i),`Invalid argument(s) to setTargetAtTime: ${JSON.stringify(t)}, ${JSON.stringify(e)}`),this._events.add({constant:n,time:i,type:"setTargetAtTime",value:s}),this.log(this.units,"setTargetAtTime",t,i,n),this._param.setTargetAtTime(s,i,n),this}setValueCurveAtTime(t,e,n,s=1){n=this.toSeconds(n),e=this.toSeconds(e);const i=this._fromType(t[0])*s;this.setValueAtTime(this._toType(i),e);const o=n/(t.length-1);for(let n=1;n{"cancelScheduledValues"===e.type?t.cancelScheduledValues(e.time):"setTargetAtTime"===e.type?t.setTargetAtTime(e.value,e.time,e.constant):t[e.type](e.value,e.time)}),this}setParam(t){r(this._swappable,"The Param must be assigned as 'swappable' in the constructor");const e=this.input;return e.disconnect(this._param),this.apply(t),this._param=t,e.connect(this._param),this}dispose(){return super.dispose(),this._events.dispose(),this}get defaultValue(){return this._toType(this._param.defaultValue)}_exponentialApproach(t,e,n,s,i){return n+(e-n)*Math.exp(-(i-t)/s)}_linearInterpolate(t,e,n,s,i){return e+(i-t)/(n-t)*(s-e)}_exponentialInterpolate(t,e,n,s,i){return e*Math.pow(s/e,(i-t)/(n-t))}}class Ct extends Tt{constructor(){super(...arguments),this.name="ToneAudioNode",this._internalChannels=[]}get numberOfInputs(){return f(this.input)?k(this.input)||this.input instanceof St?1:this.input.numberOfInputs:0}get numberOfOutputs(){return f(this.output)?this.output.numberOfOutputs:0}_isAudioNode(t){return f(t)&&(t instanceof Ct||A(t))}_getInternalNodes(){const t=this._internalChannels.slice(0);return this._isAudioNode(this.input)&&t.push(this.input),this._isAudioNode(this.output)&&this.input!==this.output&&t.push(this.output),t}_setChannelProperties(t){this._getInternalNodes().forEach(e=>{e.channelCount=t.channelCount,e.channelCountMode=t.channelCountMode,e.channelInterpretation=t.channelInterpretation})}_getChannelProperties(){const t=this._getInternalNodes();r(t.length>0,"ToneAudioNode does not have any internal nodes");const e=t[0];return{channelCount:e.channelCount,channelCountMode:e.channelCountMode,channelInterpretation:e.channelInterpretation}}get channelCount(){return this._getChannelProperties().channelCount}set channelCount(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCount:t}))}get channelCountMode(){return this._getChannelProperties().channelCountMode}set channelCountMode(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelCountMode:t}))}get channelInterpretation(){return this._getChannelProperties().channelInterpretation}set channelInterpretation(t){const e=this._getChannelProperties();this._setChannelProperties(Object.assign(e,{channelInterpretation:t}))}connect(t,e=0,n=0){return At(this,t,e,n),this}toDestination(){return this.connect(this.context.destination),this}toMaster(){return d("toMaster() has been renamed toDestination()"),this.toDestination()}disconnect(t,e=0,n=0){return Dt(this,t,e,n),this}chain(...t){return kt(this,...t),this}fan(...t){return t.forEach(t=>this.connect(t)),this}dispose(){return super.dispose(),f(this.input)&&(this.input instanceof Ct?this.input.dispose():A(this.input)&&this.input.disconnect()),f(this.output)&&(this.output instanceof Ct?this.output.dispose():A(this.output)&&this.output.disconnect()),this._internalChannels=[],this}}function kt(...t){const e=t.shift();t.reduce((t,e)=>(t instanceof Ct?t.connect(e):A(t)&&At(t,e),e),e)}function At(t,e,n=0,s=0){for(r(f(t),"Cannot connect from undefined node"),r(f(e),"Cannot connect to undefined node"),(e instanceof Ct||A(e))&&r(e.numberOfInputs>0,"Cannot connect to node with no inputs"),r(t.numberOfOutputs>0,"Cannot connect from node with no outputs");e instanceof Ct||e instanceof St;)f(e.input)&&(e=e.input);for(;t instanceof Ct;)f(t.output)&&(t=t.output);k(e)?t.connect(e,n):t.connect(e,n,s)}function Dt(t,e,n=0,s=0){if(f(e))for(;e instanceof Ct;)e=e.input;for(;!A(t);)f(t.output)&&(t=t.output);k(e)?t.disconnect(e,n):A(e)?t.disconnect(e,n,s):t.disconnect()}class Mt extends Ct{constructor(){super(q(Mt.getDefaults(),arguments,["gain","units"])),this.name="Gain",this._gainNode=this.context.createGain(),this.input=this._gainNode,this.output=this._gainNode;const t=q(Mt.getDefaults(),arguments,["gain","units"]);this.gain=new St({context:this.context,convert:t.convert,param:this._gainNode.gain,units:t.units,value:t.gain,minValue:t.minValue,maxValue:t.maxValue}),$(this,"gain")}static getDefaults(){return Object.assign(Ct.getDefaults(),{convert:!0,gain:1,units:"gain"})}dispose(){return super.dispose(),this._gainNode.disconnect(),this.gain.dispose(),this}}class jt extends Ct{constructor(t){super(t),this.onended=K,this._startTime=-1,this._stopTime=-1,this._timeout=-1,this.output=new Mt({context:this.context,gain:0}),this._gainNode=this.output,this.getStateAtTime=function(t){const e=this.toSeconds(t);return-1!==this._startTime&&e>=this._startTime&&(-1===this._stopTime||e<=this._stopTime)?"started":"stopped"},this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut,this._curve=t.curve,this.onended=t.onended}static getDefaults(){return Object.assign(Ct.getDefaults(),{curve:"linear",fadeIn:0,fadeOut:0,onended:K})}_startGain(t,e=1){r(-1===this._startTime,"Source cannot be started more than once");const n=this.toSeconds(this._fadeIn);return this._startTime=t+n,this._startTime=Math.max(this._startTime,this.context.currentTime),n>0?(this._gainNode.gain.setValueAtTime(0,t),"linear"===this._curve?this._gainNode.gain.linearRampToValueAtTime(e,t+n):this._gainNode.gain.exponentialApproachValueAtTime(e,t,n)):this._gainNode.gain.setValueAtTime(e,t),this}stop(t){return this.log("stop",t),this._stopGain(this.toSeconds(t)),this}_stopGain(t){r(-1!==this._startTime,"'start' must be called before 'stop'"),this.cancelStop();const e=this.toSeconds(this._fadeOut);return this._stopTime=this.toSeconds(t)+e,this._stopTime=Math.max(this._stopTime,this.context.currentTime),e>0?"linear"===this._curve?this._gainNode.gain.linearRampTo(0,e,t):this._gainNode.gain.targetRampTo(0,e,t):(this._gainNode.gain.cancelAndHoldAtTime(t),this._gainNode.gain.setValueAtTime(0,t)),this.context.clearTimeout(this._timeout),this._timeout=this.context.setTimeout(()=>{const t="exponential"===this._curve?2*e:0;this._stopSource(this.now()+t),this._onended()},this._stopTime-this.context.currentTime),this}_onended(){if(this.onended!==K&&(this.onended(this),this.onended=K,!this.context.isOffline)){const t=()=>this.dispose();void 0!==window.requestIdleCallback?window.requestIdleCallback(t):setTimeout(t,1e3)}}get state(){return this.getStateAtTime(this.now())}cancelStop(){return this.log("cancelStop"),r(-1!==this._startTime,"Source is not started"),this._gainNode.gain.cancelScheduledValues(this._startTime+this.sampleTime),this.context.clearTimeout(this._timeout),this._stopTime=-1,this}dispose(){return super.dispose(),this._gainNode.disconnect(),this}}class Et extends jt{constructor(){super(q(Et.getDefaults(),arguments,["offset"])),this.name="ToneConstantSource",this._source=this.context.createConstantSource();const t=q(Et.getDefaults(),arguments,["offset"]);At(this._source,this._gainNode),this.offset=new St({context:this.context,convert:t.convert,param:this._source.offset,units:t.units,value:t.offset,minValue:t.minValue,maxValue:t.maxValue})}static getDefaults(){return Object.assign(jt.getDefaults(),{convert:!0,offset:1,units:"number"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._source.start(e),this}_stopSource(t){this._source.stop(t)}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._source.disconnect(),this.offset.dispose(),this}}class Rt extends Ct{constructor(){super(q(Rt.getDefaults(),arguments,["value","units"])),this.name="Signal",this.override=!0;const t=q(Rt.getDefaults(),arguments,["value","units"]);this.output=this._constantSource=new Et({context:this.context,convert:t.convert,offset:t.value,units:t.units,minValue:t.minValue,maxValue:t.maxValue}),this._constantSource.start(0),this.input=this._param=this._constantSource.offset}static getDefaults(){return Object.assign(Ct.getDefaults(),{convert:!0,units:"number",value:0})}connect(t,e=0,n=0){return qt(this,t,e,n),this}dispose(){return super.dispose(),this._param.dispose(),this._constantSource.dispose(),this}setValueAtTime(t,e){return this._param.setValueAtTime(t,e),this}getValueAtTime(t){return this._param.getValueAtTime(t)}setRampPoint(t){return this._param.setRampPoint(t),this}linearRampToValueAtTime(t,e){return this._param.linearRampToValueAtTime(t,e),this}exponentialRampToValueAtTime(t,e){return this._param.exponentialRampToValueAtTime(t,e),this}exponentialRampTo(t,e,n){return this._param.exponentialRampTo(t,e,n),this}linearRampTo(t,e,n){return this._param.linearRampTo(t,e,n),this}targetRampTo(t,e,n){return this._param.targetRampTo(t,e,n),this}exponentialApproachValueAtTime(t,e,n){return this._param.exponentialApproachValueAtTime(t,e,n),this}setTargetAtTime(t,e,n){return this._param.setTargetAtTime(t,e,n),this}setValueCurveAtTime(t,e,n,s){return this._param.setValueCurveAtTime(t,e,n,s),this}cancelScheduledValues(t){return this._param.cancelScheduledValues(t),this}cancelAndHoldAtTime(t){return this._param.cancelAndHoldAtTime(t),this}rampTo(t,e,n){return this._param.rampTo(t,e,n),this}get value(){return this._param.value}set value(t){this._param.value=t}get convert(){return this._param.convert}set convert(t){this._param.convert=t}get units(){return this._param.units}get overridden(){return this._param.overridden}set overridden(t){this._param.overridden=t}get maxValue(){return this._param.maxValue}get minValue(){return this._param.minValue}apply(t){return this._param.apply(t),this}}function qt(t,e,n,s){(e instanceof St||k(e)||e instanceof Rt&&e.override)&&(e.cancelScheduledValues(0),e.setValueAtTime(0,0),e instanceof Rt&&(e.overridden=!0)),At(t,e,n,s)}class It extends St{constructor(){super(q(It.getDefaults(),arguments,["value"])),this.name="TickParam",this._events=new W(1/0),this._multiplier=1;const t=q(It.getDefaults(),arguments,["value"]);this._multiplier=t.multiplier,this._events.cancel(0),this._events.add({ticks:0,time:0,type:"setValueAtTime",value:this._fromType(t.value)}),this.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(St.getDefaults(),{multiplier:1,units:"hertz",value:1})}setTargetAtTime(t,e,n){e=this.toSeconds(e),this.setRampPoint(e);const s=this._fromType(t),i=this._events.get(e),o=Math.round(Math.max(1/n,1));for(let t=0;t<=o;t++){const o=n*t+e,r=this._exponentialApproach(i.time,i.value,s,n,o);this.linearRampToValueAtTime(this._toType(r),o)}return this}setValueAtTime(t,e){const n=this.toSeconds(e);super.setValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),o=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(o,0),this}linearRampToValueAtTime(t,e){const n=this.toSeconds(e);super.linearRampToValueAtTime(t,e);const s=this._events.get(n),i=this._events.previousEvent(s),o=this._getTicksUntilEvent(i,n);return s.ticks=Math.max(o,0),this}exponentialRampToValueAtTime(t,e){e=this.toSeconds(e);const n=this._fromType(t),s=this._events.get(e),i=Math.round(Math.max(10*(e-s.time),1)),o=(e-s.time)/i;for(let t=0;t<=i;t++){const i=o*t+s.time,r=this._exponentialInterpolate(s.time,s.value,e,n,i);this.linearRampToValueAtTime(this._toType(r),i)}return this}_getTicksUntilEvent(t,e){if(null===t)t={ticks:0,time:0,type:"setValueAtTime",value:0};else if(p(t.ticks)){const e=this._events.previousEvent(t);t.ticks=this._getTicksUntilEvent(e,t.time)}const n=this._fromType(this.getValueAtTime(t.time));let s=this._fromType(this.getValueAtTime(e));const i=this._events.get(e);return i&&i.time===e&&"setValueAtTime"===i.type&&(s=this._fromType(this.getValueAtTime(e-this.sampleTime))),.5*(e-t.time)*(n+s)+t.ticks}getTicksAtTime(t){const e=this.toSeconds(t),n=this._events.get(e);return Math.max(this._getTicksUntilEvent(n,e),0)}getDurationOfTicks(t,e){const n=this.toSeconds(e),s=this.getTicksAtTime(e);return this.getTimeOfTick(s+t)-n}getTimeOfTick(t){const e=this._events.get(t,"ticks"),n=this._events.getAfter(t,"ticks");if(e&&e.ticks===t)return e.time;if(e&&n&&"linearRampToValueAtTime"===n.type&&e.value!==n.value){const s=this._fromType(this.getValueAtTime(e.time)),i=(this._fromType(this.getValueAtTime(n.time))-s)/(n.time-e.time),o=Math.sqrt(Math.pow(s,2)-2*i*(e.ticks-t)),r=(-s+o)/i,a=(-s-o)/i;return(r>0?r:a)+e.time}return e?0===e.value?1/0:e.time+(t-e.ticks)/e.value:t/this._initialValue}ticksToTime(t,e){return this.getDurationOfTicks(t,e)}timeToTicks(t,e){const n=this.toSeconds(e),s=this.toSeconds(t),i=this.getTicksAtTime(n);return this.getTicksAtTime(n+s)-i}_fromType(t){return"bpm"===this.units&&this.multiplier?1/(60/t/this.multiplier):super._fromType(t)}_toType(t){return"bpm"===this.units&&this.multiplier?t/this.multiplier*60:super._toType(t)}get multiplier(){return this._multiplier}set multiplier(t){const e=this.value;this._multiplier=t,this.cancelScheduledValues(0),this.setValueAtTime(e,0)}}class Ft extends Rt{constructor(){super(q(Ft.getDefaults(),arguments,["value"])),this.name="TickSignal";const t=q(Ft.getDefaults(),arguments,["value"]);this.input=this._param=new It({context:this.context,convert:t.convert,multiplier:t.multiplier,param:this._constantSource.offset,units:t.units,value:t.value})}static getDefaults(){return Object.assign(Rt.getDefaults(),{multiplier:1,units:"hertz",value:1})}ticksToTime(t,e){return this._param.ticksToTime(t,e)}timeToTicks(t,e){return this._param.timeToTicks(t,e)}getTimeOfTick(t){return this._param.getTimeOfTick(t)}getDurationOfTicks(t,e){return this._param.getDurationOfTicks(t,e)}getTicksAtTime(t){return this._param.getTicksAtTime(t)}get multiplier(){return this._param.multiplier}set multiplier(t){this._param.multiplier=t}dispose(){return super.dispose(),this._param.dispose(),this}}class Vt extends Tt{constructor(){super(q(Vt.getDefaults(),arguments,["frequency"])),this.name="TickSource",this._state=new Ot,this._tickOffset=new W;const t=q(Vt.getDefaults(),arguments,["frequency"]);this.frequency=new Ft({context:this.context,units:t.units,value:t.frequency}),$(this,"frequency"),this._state.setStateAtTime("stopped",0),this.setTicksAtTime(0,0)}static getDefaults(){return Object.assign({frequency:1,units:"hertz"},Tt.getDefaults())}get state(){return this.getStateAtTime(this.now())}start(t,e){const n=this.toSeconds(t);return"started"!==this._state.getValueAtTime(n)&&(this._state.setStateAtTime("started",n),f(e)&&this.setTicksAtTime(e,n)),this}stop(t){const e=this.toSeconds(t);if("stopped"===this._state.getValueAtTime(e)){const t=this._state.get(e);t&&t.time>0&&(this._tickOffset.cancel(t.time),this._state.cancel(t.time))}return this._state.cancel(e),this._state.setStateAtTime("stopped",e),this.setTicksAtTime(0,e),this}pause(t){const e=this.toSeconds(t);return"started"===this._state.getValueAtTime(e)&&this._state.setStateAtTime("paused",e),this}cancel(t){return t=this.toSeconds(t),this._state.cancel(t),this._tickOffset.cancel(t),this}getTicksAtTime(t){const e=this.toSeconds(t),n=this._state.getLastState("stopped",e),s={state:"paused",time:e};this._state.add(s);let i=n,o=0;return this._state.forEachBetween(n.time,e+this.sampleTime,t=>{let e=i.time;const n=this._tickOffset.get(t.time);n&&n.time>=i.time&&(o=n.ticks,e=n.time),"started"===i.state&&"started"!==t.state&&(o+=this.frequency.getTicksAtTime(t.time)-this.frequency.getTicksAtTime(e)),i=t}),this._state.remove(s),o}get ticks(){return this.getTicksAtTime(this.now())}set ticks(t){this.setTicksAtTime(t,this.now())}get seconds(){return this.getSecondsAtTime(this.now())}set seconds(t){const e=this.now(),n=this.frequency.timeToTicks(t,e);this.setTicksAtTime(n,e)}getSecondsAtTime(t){t=this.toSeconds(t);const e=this._state.getLastState("stopped",t),n={state:"paused",time:t};this._state.add(n);let s=e,i=0;return this._state.forEachBetween(e.time,t+this.sampleTime,t=>{let e=s.time;const n=this._tickOffset.get(t.time);n&&n.time>=s.time&&(i=n.seconds,e=n.time),"started"===s.state&&"started"!==t.state&&(i+=t.time-e),s=t}),this._state.remove(n),i}setTicksAtTime(t,e){return e=this.toSeconds(e),this._tickOffset.cancel(e),this._tickOffset.add({seconds:this.frequency.getDurationOfTicks(t,e),ticks:t,time:e}),this}getStateAtTime(t){return t=this.toSeconds(t),this._state.getValueAtTime(t)}getTimeOfTick(t,e=this.now()){const n=this._tickOffset.get(e),s=this._state.get(e),i=Math.max(n.time,s.time),o=this.frequency.getTicksAtTime(i)+t-n.ticks;return this.frequency.getTimeOfTick(o)}forEachTickBetween(t,e,n){let s=this._state.get(t);this._state.forEachBetween(t,e,e=>{s&&"started"===s.state&&"started"!==e.state&&this.forEachTickBetween(Math.max(s.time,t),e.time-this.sampleTime,n),s=e});let i=null;if(s&&"started"===s.state){const o=Math.max(s.time,t),r=this.frequency.getTicksAtTime(o),a=r-this.frequency.getTicksAtTime(s.time);let c=Math.ceil(a)-a;c=z(c,1)?0:c;let u=this.frequency.getTimeOfTick(r+c);for(;u{switch(t.state){case"started":const e=this._tickSource.getTicksAtTime(t.time);this.emit("start",t.time,e);break;case"stopped":0!==t.time&&this.emit("stop",t.time);break;case"paused":this.emit("pause",t.time)}}),this._tickSource.forEachTickBetween(t,e,(t,e)=>{this.callback(t,e)}))}getStateAtTime(t){const e=this.toSeconds(t);return this._state.getValueAtTime(e)}dispose(){return super.dispose(),this.context.off("tick",this._boundLoop),this._tickSource.dispose(),this._state.dispose(),this}}Z.mixin(Nt);class Pt extends V{constructor(t){super(),this.name="TimelineValue",this._timeline=new W({memory:10}),this._initialValue=t}set(t,e){return this._timeline.add({value:t,time:e}),this}get(t){const e=this._timeline.get(t);return e?e.value:this._initialValue}}class Lt extends xt{constructor(){super(...arguments),this.name="Ticks",this.defaultUnits="i"}_now(){return this.context.transport.ticks}_beatsToUnits(t){return this._getPPQ()*t}_secondsToUnits(t){return Math.floor(t/(60/this._getBpm())*this._getPPQ())}_ticksToUnits(t){return t}toTicks(){return this.valueOf()}toSeconds(){return this.valueOf()/this._getPPQ()*(60/this._getBpm())}}function zt(t,e){return new Lt(it(),t,e)}class Bt extends V{constructor(){super(...arguments),this.name="IntervalTimeline",this._root=null,this._length=0}add(t){r(f(t.time),"Events must have a time property"),r(f(t.duration),"Events must have a duration parameter"),t.time=t.time.valueOf();let e=new Wt(t.time,t.time+t.duration,t);for(null===this._root?this._root=e:this._root.insert(e),this._length++;null!==e;)e.updateHeight(),e.updateMax(),this._rebalance(e),e=e.parent;return this}remove(t){if(null!==this._root){const e=[];this._root.search(t.time,e);for(const n of e)if(n.event===t){this._removeNode(n),this._length--;break}}return this}get length(){return this._length}cancel(t){return this.forEachFrom(t,t=>this.remove(t)),this}_setRoot(t){this._root=t,null!==this._root&&(this._root.parent=null)}_replaceNodeInParent(t,e){null!==t.parent?(t.isLeftChild()?t.parent.left=e:t.parent.right=e,this._rebalance(t.parent)):this._setRoot(e)}_removeNode(t){if(null===t.left&&null===t.right)this._replaceNodeInParent(t,null);else if(null===t.right)this._replaceNodeInParent(t,t.left);else if(null===t.left)this._replaceNodeInParent(t,t.right);else{let e,n=null;if(t.getBalance()>0)if(null===t.left.right)e=t.left,e.right=t.right,n=e;else{for(e=t.left.right;null!==e.right;)e=e.right;e.parent&&(e.parent.right=e.left,n=e.parent,e.left=t.left,e.right=t.right)}else if(null===t.right.left)e=t.right,e.left=t.left,n=e;else{for(e=t.right.left;null!==e.left;)e=e.left;e.parent&&(e.parent.left=e.right,n=e.parent,e.left=t.left,e.right=t.right)}null!==t.parent?t.isLeftChild()?t.parent.left=e:t.parent.right=e:this._setRoot(e),n&&this._rebalance(n)}t.dispose()}_rotateLeft(t){const e=t.parent,n=t.isLeftChild(),s=t.right;s&&(t.right=s.left,s.left=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rotateRight(t){const e=t.parent,n=t.isLeftChild(),s=t.left;s&&(t.left=s.right,s.right=t),null!==e?n?e.left=s:e.right=s:this._setRoot(s)}_rebalance(t){const e=t.getBalance();e>1&&t.left?t.left.getBalance()<0?this._rotateLeft(t.left):this._rotateRight(t):e<-1&&t.right&&(t.right.getBalance()>0?this._rotateRight(t.right):this._rotateLeft(t))}get(t){if(null!==this._root){const e=[];if(this._root.search(t,e),e.length>0){let t=e[0];for(let n=1;nt.low&&(t=e[n]);return t.event}}return null}forEach(t){if(null!==this._root){const e=[];this._root.traverse(t=>e.push(t)),e.forEach(e=>{e.event&&t(e.event)})}return this}forEachAtTime(t,e){if(null!==this._root){const n=[];this._root.search(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}forEachFrom(t,e){if(null!==this._root){const n=[];this._root.searchAfter(t,n),n.forEach(t=>{t.event&&e(t.event)})}return this}dispose(){return super.dispose(),null!==this._root&&this._root.traverse(t=>t.dispose()),this._root=null,this}}class Wt{constructor(t,e,n){this._left=null,this._right=null,this.parent=null,this.height=0,this.event=n,this.low=t,this.high=e,this.max=this.high}insert(t){t.low<=this.low?null===this.left?this.left=t:this.left.insert(t):null===this.right?this.right=t:this.right.insert(t)}search(t,e){t>this.max||(null!==this.left&&this.left.search(t,e),this.low<=t&&this.high>t&&e.push(this),this.low>t||null!==this.right&&this.right.search(t,e))}searchAfter(t,e){this.low>=t&&(e.push(this),null!==this.left&&this.left.searchAfter(t,e)),null!==this.right&&this.right.searchAfter(t,e)}traverse(t){t(this),null!==this.left&&this.left.traverse(t),null!==this.right&&this.right.traverse(t)}updateHeight(){null!==this.left&&null!==this.right?this.height=Math.max(this.left.height,this.right.height)+1:null!==this.right?this.height=this.right.height+1:null!==this.left?this.height=this.left.height+1:this.height=0}updateMax(){this.max=this.high,null!==this.left&&(this.max=Math.max(this.max,this.left.max)),null!==this.right&&(this.max=Math.max(this.max,this.right.max))}getBalance(){let t=0;return null!==this.left&&null!==this.right?t=this.left.height-this.right.height:null!==this.left?t=this.left.height+1:null!==this.right&&(t=-(this.right.height+1)),t}isLeftChild(){return null!==this.parent&&this.parent.left===this}get left(){return this._left}set left(t){this._left=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}get right(){return this._right}set right(t){this._right=t,null!==t&&(t.parent=this),this.updateHeight(),this.updateMax()}dispose(){this.parent=null,this._left=null,this._right=null,this.event=null}}class Ut{constructor(t,e){this.id=Ut._eventId++;const n=Object.assign(Ut.getDefaults(),e);this.transport=t,this.callback=n.callback,this._once=n.once,this.time=n.time}static getDefaults(){return{callback:K,once:!1,time:0}}invoke(t){this.callback&&(this.callback(t),this._once&&this.transport.clear(this.id))}dispose(){return this.callback=void 0,this}}Ut._eventId=0;class Gt extends Ut{constructor(t,e){super(t,e),this._currentId=-1,this._nextId=-1,this._nextTick=this.time,this._boundRestart=this._restart.bind(this);const n=Object.assign(Gt.getDefaults(),e);this.duration=new Lt(t.context,n.duration).valueOf(),this._interval=new Lt(t.context,n.interval).valueOf(),this._nextTick=n.time,this.transport.on("start",this._boundRestart),this.transport.on("loopStart",this._boundRestart),this.context=this.transport.context,this._restart()}static getDefaults(){return Object.assign({},Ut.getDefaults(),{duration:1/0,interval:1,once:!1})}invoke(t){this._createEvents(t),super.invoke(t)}_createEvents(t){const e=this.transport.getTicksAtTime(t);e>=this.time&&e>=this._nextTick&&this._nextTick+this._intervalthis.time&&(this._nextTick=this.time+Math.ceil((e-this.time)/this._interval)*this._interval),this._currentId=this.transport.scheduleOnce(this.invoke.bind(this),new Lt(this.context,this._nextTick).toSeconds()),this._nextTick+=this._interval,this._nextId=this.transport.scheduleOnce(this.invoke.bind(this),new Lt(this.context,this._nextTick).toSeconds())}dispose(){return super.dispose(),this.transport.clear(this._currentId),this.transport.clear(this._nextId),this.transport.off("start",this._boundRestart),this.transport.off("loopStart",this._boundRestart),this}}class Yt extends Tt{constructor(){super(q(Yt.getDefaults(),arguments)),this.name="Transport",this._loop=new Pt(!1),this._loopStart=0,this._loopEnd=0,this._scheduledEvents={},this._timeline=new W,this._repeatedEvents=new Bt,this._syncedSignals=[],this._swingAmount=0;const t=q(Yt.getDefaults(),arguments);this._ppq=t.ppq,this._clock=new Nt({callback:this._processTick.bind(this),context:this.context,frequency:0,units:"bpm"}),this._bindClockEvents(),this.bpm=this._clock.frequency,this._clock.frequency.multiplier=t.ppq,this.bpm.setValueAtTime(t.bpm,0),$(this,"bpm"),this._timeSignature=t.timeSignature,this._swingTicks=t.ppq/2}static getDefaults(){return Object.assign(Tt.getDefaults(),{bpm:120,loopEnd:"4m",loopStart:0,ppq:192,swing:0,swingSubdivision:"8n",timeSignature:4})}_processTick(t,e){if(this._swingAmount>0&&e%this._ppq!=0&&e%(2*this._swingTicks)!=0){const n=e%(2*this._swingTicks)/(2*this._swingTicks),s=Math.sin(n*Math.PI)*this._swingAmount;t+=new Lt(this.context,2*this._swingTicks/3).toSeconds()*s}this._loop.get(t)&&e>=this._loopEnd&&(this.emit("loopEnd",t),this._clock.setTicksAtTime(this._loopStart,t),e=this._loopStart,this.emit("loopStart",t,this._clock.getSecondsAtTime(t)),this.emit("loop",t)),this._timeline.forEachAtTime(e,e=>e.invoke(t))}schedule(t,e){const n=new Ut(this,{callback:t,time:new xt(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}scheduleRepeat(t,e,n,s=1/0){const i=new Gt(this,{callback:t,duration:new _t(this.context,s).toTicks(),interval:new _t(this.context,e).toTicks(),time:new xt(this.context,n).toTicks()});return this._addEvent(i,this._repeatedEvents)}scheduleOnce(t,e){const n=new Ut(this,{callback:t,once:!0,time:new xt(this.context,e).toTicks()});return this._addEvent(n,this._timeline)}clear(t){if(this._scheduledEvents.hasOwnProperty(t)){const e=this._scheduledEvents[t.toString()];e.timeline.remove(e.event),e.event.dispose(),delete this._scheduledEvents[t.toString()]}return this}_addEvent(t,e){return this._scheduledEvents[t.id.toString()]={event:t,timeline:e},e.add(t),t.id}cancel(t=0){const e=this.toTicks(t);return this._timeline.forEachFrom(e,t=>this.clear(t.id)),this._repeatedEvents.forEachFrom(e,t=>this.clear(t.id)),this}_bindClockEvents(){this._clock.on("start",(t,e)=>{e=new Lt(this.context,e).toSeconds(),this.emit("start",t,e)}),this._clock.on("stop",t=>{this.emit("stop",t)}),this._clock.on("pause",t=>{this.emit("pause",t)})}get state(){return this._clock.getStateAtTime(this.now())}start(t,e){let n;return f(e)&&(n=this.toTicks(e)),this._clock.start(t,n),this}stop(t){return this._clock.stop(t),this}pause(t){return this._clock.pause(t),this}toggle(t){return t=this.toSeconds(t),"started"!==this._clock.getStateAtTime(t)?this.start(t):this.stop(t),this}get timeSignature(){return this._timeSignature}set timeSignature(t){y(t)&&(t=t[0]/t[1]*4),this._timeSignature=t}get loopStart(){return new _t(this.context,this._loopStart,"i").toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t)}get loopEnd(){return new _t(this.context,this._loopEnd,"i").toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t)}get loop(){return this._loop.get(this.now())}set loop(t){this._loop.set(t,this.now())}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get swing(){return this._swingAmount}set swing(t){this._swingAmount=t}get swingSubdivision(){return new Lt(this.context,this._swingTicks).toNotation()}set swingSubdivision(t){this._swingTicks=this.toTicks(t)}get position(){const t=this.now(),e=this._clock.getTicksAtTime(t);return new Lt(this.context,e).toBarsBeatsSixteenths()}set position(t){const e=this.toTicks(t);this.ticks=e}get seconds(){return this._clock.seconds}set seconds(t){const e=this.now(),n=this._clock.frequency.timeToTicks(t,e);this.ticks=n}get progress(){if(this.loop){const t=this.now();return(this._clock.getTicksAtTime(t)-this._loopStart)/(this._loopEnd-this._loopStart)}return 0}get ticks(){return this._clock.ticks}set ticks(t){if(this._clock.ticks!==t){const e=this.now();if("started"===this.state){const n=this._clock.getTicksAtTime(e),s=this._clock.getTimeOfTick(Math.ceil(n));this.emit("stop",s),this._clock.setTicksAtTime(t,s),this.emit("start",s,this._clock.getSecondsAtTime(s))}else this._clock.setTicksAtTime(t,e)}}getTicksAtTime(t){return Math.round(this._clock.getTicksAtTime(t))}getSecondsAtTime(t){return this._clock.getSecondsAtTime(t)}get PPQ(){return this._clock.frequency.multiplier}set PPQ(t){this._clock.frequency.multiplier=t}nextSubdivision(t){if(t=this.toTicks(t),"started"!==this.state)return 0;{const e=this.now(),n=t-this.getTicksAtTime(e)%t;return this._clock.nextTickTime(n,e)}}syncSignal(t,e){if(!e){const n=this.now();if(0!==t.getValueAtTime(n)){const s=1/(60/this.bpm.getValueAtTime(n)/this.PPQ);e=t.getValueAtTime(n)/s}else e=0}const n=new Mt(e);return this.bpm.connect(n),n.connect(t._param),this._syncedSignals.push({initial:t.value,ratio:n,signal:t}),t.value=0,this}unsyncSignal(t){for(let e=this._syncedSignals.length-1;e>=0;e--){const n=this._syncedSignals[e];n.signal===t&&(n.ratio.dispose(),n.signal.value=n.initial,this._syncedSignals.splice(e,1))}return this}dispose(){return super.dispose(),this._clock.dispose(),J(this,"bpm"),this._timeline.dispose(),this._repeatedEvents.dispose(),this}}Z.mixin(Yt),G(t=>{t.transport=new Yt({context:t})}),Q(t=>{t.transport.dispose()});class Qt extends Ct{constructor(){super(q(Qt.getDefaults(),arguments,["delayTime","maxDelay"])),this.name="Delay";const t=q(Qt.getDefaults(),arguments,["delayTime","maxDelay"]),e=this.toSeconds(t.maxDelay);this._maxDelay=Math.max(e,this.toSeconds(t.delayTime)),this._delayNode=this.input=this.output=this.context.createDelay(e),this.delayTime=new St({context:this.context,param:this._delayNode.delayTime,units:"time",value:t.delayTime,minValue:0,maxValue:this.maxDelay}),$(this,"delayTime")}static getDefaults(){return Object.assign(Ct.getDefaults(),{delayTime:0,maxDelay:1})}get maxDelay(){return this._maxDelay}dispose(){return super.dispose(),this._delayNode.disconnect(),this.delayTime.dispose(),this}}class Zt extends Ct{constructor(){super(q(Zt.getDefaults(),arguments,["volume"])),this.name="Volume";const t=q(Zt.getDefaults(),arguments,["volume"]);this.input=this.output=new Mt({context:this.context,gain:t.volume,units:"decibels"}),this.volume=this.output.gain,$(this,"volume"),this._unmutedVolume=t.volume,this.mute=t.mute}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}get mute(){return this.volume.value===-1/0}set mute(t){!this.mute&&t?(this._unmutedVolume=this.volume.value,this.volume.value=-1/0):this.mute&&!t&&(this.volume.value=this._unmutedVolume)}dispose(){return super.dispose(),this.input.dispose(),this.volume.dispose(),this}}class Xt extends Ct{constructor(){super(q(Xt.getDefaults(),arguments)),this.name="Destination",this.input=new Zt({context:this.context}),this.output=new Mt({context:this.context}),this.volume=this.input.volume;const t=q(Xt.getDefaults(),arguments);kt(this.input,this.output,this.context.rawContext.destination),this.mute=t.mute,this._internalChannels=[this.input,this.context.rawContext.destination,this.output]}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}get mute(){return this.input.mute}set mute(t){this.input.mute=t}chain(...t){return this.input.disconnect(),t.unshift(this.input),t.push(this.output),kt(...t),this}get maxChannelCount(){return this.context.rawContext.destination.maxChannelCount}dispose(){return super.dispose(),this.volume.dispose(),this}}function Ht(t,e,n=2,s=it().sampleRate){return S(this,void 0,void 0,(function*(){const i=it(),o=new et(n,e,s);ot(o),yield t(o);const r=o.render();ot(i);const a=yield r;return new tt(a)}))}G(t=>{t.destination=new Xt({context:t})}),Q(t=>{t.destination.dispose()});class $t extends V{constructor(){super(),this.name="ToneAudioBuffers",this._buffers=new Map,this._loadingCount=0;const t=q($t.getDefaults(),arguments,["urls","onload","baseUrl"],"urls");this.baseUrl=t.baseUrl,Object.keys(t.urls).forEach(e=>{this._loadingCount++;const n=t.urls[e];this.add(e,n,this._bufferLoaded.bind(this,t.onload),t.onerror)})}static getDefaults(){return{baseUrl:"",onerror:K,onload:K,urls:{}}}has(t){return this._buffers.has(t.toString())}get(t){return r(this.has(t),"ToneAudioBuffers has no buffer named: "+t),this._buffers.get(t.toString())}_bufferLoaded(t){this._loadingCount--,0===this._loadingCount&&t&&t()}get loaded(){return Array.from(this._buffers).every(([t,e])=>e.loaded)}add(t,e,n=K,s=K){return b(e)?this._buffers.set(t.toString(),new tt(this.baseUrl+e,n,s)):this._buffers.set(t.toString(),new tt(e,n,s)),this}dispose(){return super.dispose(),this._buffers.forEach(t=>t.dispose()),this._buffers.clear(),this}}class Jt extends gt{constructor(){super(...arguments),this.name="MidiClass",this.defaultUnits="midi"}_frequencyToUnits(t){return lt(super._frequencyToUnits(t))}_ticksToUnits(t){return lt(super._ticksToUnits(t))}_beatsToUnits(t){return lt(super._beatsToUnits(t))}_secondsToUnits(t){return lt(super._secondsToUnits(t))}toMidi(){return this.valueOf()}toFrequency(){return pt(this.toMidi())}transpose(t){return new Jt(this.context,this.toMidi()+t)}}function Kt(t,e){return new Jt(it(),t,e)}class te extends Tt{constructor(){super(...arguments),this.name="Draw",this.expiration=.25,this.anticipation=.008,this._events=new W,this._boundDrawLoop=this._drawLoop.bind(this),this._animationFrame=-1}schedule(t,e){return this._events.add({callback:t,time:this.toSeconds(e)}),1===this._events.length&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop)),this}cancel(t){return this._events.cancel(this.toSeconds(t)),this}_drawLoop(){const t=this.context.currentTime;for(;this._events.length&&this._events.peek().time-this.anticipation<=t;){const e=this._events.shift();e&&t-e.time<=this.expiration&&e.callback()}this._events.length>0&&(this._animationFrame=requestAnimationFrame(this._boundDrawLoop))}dispose(){return super.dispose(),this._events.dispose(),cancelAnimationFrame(this._animationFrame),this}}G(t=>{t.draw=new te({context:t})}),Q(t=>{t.draw.dispose()});var ee=n(515);class ne extends Ct{constructor(t){super(t),this.input=void 0,this._state=new Ot("stopped"),this._synced=!1,this._scheduled=[],this._syncedStart=K,this._syncedStop=K,this._state.memory=100,this._state.increasing=!0,this._volume=this.output=new Zt({context:this.context,mute:t.mute,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this.onstop=t.onstop}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,onstop:K,volume:0})}get state(){return this._synced?"started"===this.context.transport.state?this._state.getValueAtTime(this.context.transport.seconds):"stopped":this._state.getValueAtTime(this.now())}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}_clampToCurrentTime(t){return this._synced?t:Math.max(t,this.context.currentTime)}start(t,e,n){let s=p(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(s=this._clampToCurrentTime(s),this._synced||"started"!==this._state.getValueAtTime(s))if(this.log("start",s),this._state.setStateAtTime("started",s),this._synced){const t=this._state.get(s);t&&(t.offset=this.toSeconds(I(e,0)),t.duration=n?this.toSeconds(n):void 0);const i=this.context.transport.schedule(t=>{this._start(t,e,n)},s);this._scheduled.push(i),"started"===this.context.transport.state&&this.context.transport.getSecondsAtTime(this.immediate())>s&&this._syncedStart(this.now(),this.context.transport.seconds)}else c(this.context),this._start(s,e,n);else r(N(s,this._state.get(s).time),"Start time must be strictly greater than previous start time"),this._state.cancel(s),this._state.setStateAtTime("started",s),this.log("restart",s),this.restart(s,e,n);return this}stop(t){let e=p(t)&&this._synced?this.context.transport.seconds:this.toSeconds(t);if(e=this._clampToCurrentTime(e),"started"===this._state.getValueAtTime(e)||f(this._state.getNextState("started",e))){if(this.log("stop",e),this._synced){const t=this.context.transport.schedule(this._stop.bind(this),e);this._scheduled.push(t)}else this._stop(e);this._state.cancel(e),this._state.setStateAtTime("stopped",e)}return this}restart(t,e,n){return t=this.toSeconds(t),"started"===this._state.getValueAtTime(t)&&(this._state.cancel(t),this._restart(t,e,n)),this}sync(){return this._synced||(this._synced=!0,this._syncedStart=(t,e)=>{if(e>0){const n=this._state.get(e);if(n&&"started"===n.state&&n.time!==e){const s=e-this.toSeconds(n.time);let i;n.duration&&(i=this.toSeconds(n.duration)-s),this._start(t,this.toSeconds(n.offset)+s,i)}}},this._syncedStop=t=>{const e=this.context.transport.getSecondsAtTime(Math.max(t-this.sampleTime,0));"started"===this._state.getValueAtTime(e)&&this._stop(t)},this.context.transport.on("start",this._syncedStart),this.context.transport.on("loopStart",this._syncedStart),this.context.transport.on("stop",this._syncedStop),this.context.transport.on("pause",this._syncedStop),this.context.transport.on("loopEnd",this._syncedStop)),this}unsync(){return this._synced&&(this.context.transport.off("stop",this._syncedStop),this.context.transport.off("pause",this._syncedStop),this.context.transport.off("loopEnd",this._syncedStop),this.context.transport.off("start",this._syncedStart),this.context.transport.off("loopStart",this._syncedStart)),this._synced=!1,this._scheduled.forEach(t=>this.context.transport.clear(t)),this._scheduled=[],this._state.cancel(0),this._stop(0),this}dispose(){return super.dispose(),this.onstop=K,this.unsync(),this._volume.dispose(),this._state.dispose(),this}}class se extends jt{constructor(){super(q(se.getDefaults(),arguments,["url","onload"])),this.name="ToneBufferSource",this._source=this.context.createBufferSource(),this._internalChannels=[this._source],this._sourceStarted=!1,this._sourceStopped=!1;const t=q(se.getDefaults(),arguments,["url","onload"]);At(this._source,this._gainNode),this._source.onended=()=>this._stopSource(),this.playbackRate=new St({context:this.context,param:this._source.playbackRate,units:"positive",value:t.playbackRate}),this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this._buffer=new tt(t.url,t.onload,t.onerror),this._internalChannels.push(this._source)}static getDefaults(){return Object.assign(jt.getDefaults(),{url:new tt,loop:!1,loopEnd:0,loopStart:0,onload:K,onerror:K,playbackRate:1})}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t}get curve(){return this._curve}set curve(t){this._curve=t}start(t,e,n,s=1){r(this.buffer.loaded,"buffer is either not set or not loaded");const i=this.toSeconds(t);this._startGain(i,s),e=this.loop?I(e,this.loopStart):I(e,0);let o=Math.max(this.toSeconds(e),0);if(this.loop){const t=this.toSeconds(this.loopEnd)||this.buffer.duration,e=this.toSeconds(this.loopStart),n=t-e;P(o,t)&&(o=(o-e)%n+e),z(o,this.buffer.duration)&&(o=0)}if(this._source.buffer=this.buffer.get(),this._source.loopEnd=this.toSeconds(this.loopEnd)||this.buffer.duration,L(o,this.buffer.duration)&&(this._sourceStarted=!0,this._source.start(i,o)),f(n)){let t=this.toSeconds(n);t=Math.max(t,0),this.stop(i+t)}return this}_stopSource(t){!this._sourceStopped&&this._sourceStarted&&(this._sourceStopped=!0,this._source.stop(this.toSeconds(t)),this._onended())}get loopStart(){return this._source.loopStart}set loopStart(t){this._source.loopStart=this.toSeconds(t)}get loopEnd(){return this._source.loopEnd}set loopEnd(t){this._source.loopEnd=this.toSeconds(t)}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._source.loop}set loop(t){this._source.loop=t,this._sourceStarted&&this.cancelStop()}dispose(){return super.dispose(),this._source.onended=null,this._source.disconnect(),this._buffer.dispose(),this.playbackRate.dispose(),this}}class ie extends ne{constructor(){super(q(ie.getDefaults(),arguments,["type"])),this.name="Noise",this._source=null;const t=q(ie.getDefaults(),arguments,["type"]);this._playbackRate=t.playbackRate,this.type=t.type,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{fadeIn:0,fadeOut:0,playbackRate:1,type:"white"})}get type(){return this._type}set type(t){if(r(t in re,"Noise: invalid type: "+t),this._type!==t&&(this._type=t,"started"===this.state)){const t=this.now();this._stop(t),this._start(t)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._source&&(this._source.playbackRate.value=t)}_start(t){const e=re[this._type];this._source=new se({url:e,context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,loop:!0,onended:()=>this.onstop(this),playbackRate:this._playbackRate}).connect(this.output),this._source.start(this.toSeconds(t),Math.random()*(e.duration-.001))}_stop(t){this._source&&(this._source.stop(this.toSeconds(t)),this._source=null)}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._source&&(this._source.fadeIn=this._fadeIn)}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._source&&(this._source.fadeOut=this._fadeOut)}_restart(t){this._stop(t),this._start(t)}dispose(){return super.dispose(),this._source&&this._source.disconnect(),this}}const oe={brown:null,pink:null,white:null},re={get brown(){if(!oe.brown){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);t[e]=n;let s=0;for(let t=0;t<220500;t++){const e=2*Math.random()-1;n[t]=(s+.02*e)/1.02,s=n[t],n[t]*=3.5}}oe.brown=(new tt).fromArray(t)}return oe.brown},get pink(){if(!oe.pink){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);let s,i,o,r,a,c,u;t[e]=n,s=i=o=r=a=c=u=0;for(let t=0;t<220500;t++){const e=2*Math.random()-1;s=.99886*s+.0555179*e,i=.99332*i+.0750759*e,o=.969*o+.153852*e,r=.8665*r+.3104856*e,a=.55*a+.5329522*e,c=-.7616*c-.016898*e,n[t]=s+i+o+r+a+c+u+.5362*e,n[t]*=.11,u=.115926*e}}oe.pink=(new tt).fromArray(t)}return oe.pink},get white(){if(!oe.white){const t=[];for(let e=0;e<2;e++){const n=new Float32Array(220500);t[e]=n;for(let t=0;t<220500;t++)n[t]=2*Math.random()-1}oe.white=(new tt).fromArray(t)}return oe.white}};class ae extends Ct{constructor(){super(q(ae.getDefaults(),arguments,["volume"])),this.name="UserMedia";const t=q(ae.getDefaults(),arguments,["volume"]);this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this.mute=t.mute}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,volume:0})}open(t){return S(this,void 0,void 0,(function*(){r(ae.supported,"UserMedia is not supported"),"started"===this.state&&this.close();const e=yield ae.enumerateDevices();m(t)?this._device=e[t]:(this._device=e.find(e=>e.label===t||e.deviceId===t),!this._device&&e.length>0&&(this._device=e[0]),r(f(this._device),"No matching device "+t));const n={audio:{echoCancellation:!1,sampleRate:this.context.sampleRate,noiseSuppression:!1,mozNoiseSuppression:!1}};this._device&&(n.audio.deviceId=this._device.deviceId);const s=yield navigator.mediaDevices.getUserMedia(n);if(!this._stream){this._stream=s;const t=this.context.createMediaStreamSource(s);At(t,this.output),this._mediaStream=t}return this}))}close(){return this._stream&&this._mediaStream&&(this._stream.getAudioTracks().forEach(t=>{t.stop()}),this._stream=void 0,this._mediaStream.disconnect(),this._mediaStream=void 0),this._device=void 0,this}static enumerateDevices(){return S(this,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter(t=>"audioinput"===t.kind)}))}get state(){return this._stream&&this._stream.active?"started":"stopped"}get deviceId(){return this._device?this._device.deviceId:void 0}get groupId(){return this._device?this._device.groupId:void 0}get label(){return this._device?this._device.label:void 0}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this.close(),this._volume.dispose(),this.volume.dispose(),this}static get supported(){return f(navigator.mediaDevices)&&f(navigator.mediaDevices.getUserMedia)}}function ce(t,e){return S(this,void 0,void 0,(function*(){const n=e/t.context.sampleRate,s=new et(1,n,t.context.sampleRate);return new t.constructor(Object.assign(t.get(),{frequency:2/n,detune:0,context:s})).toDestination().start(0),(yield s.render()).getChannelData(0)}))}class ue extends jt{constructor(){super(q(ue.getDefaults(),arguments,["frequency","type"])),this.name="ToneOscillatorNode",this._oscillator=this.context.createOscillator(),this._internalChannels=[this._oscillator];const t=q(ue.getDefaults(),arguments,["frequency","type"]);At(this._oscillator,this._gainNode),this.type=t.type,this.frequency=new St({context:this.context,param:this._oscillator.frequency,units:"frequency",value:t.frequency}),this.detune=new St({context:this.context,param:this._oscillator.detune,units:"cents",value:t.detune}),$(this,["frequency","detune"])}static getDefaults(){return Object.assign(jt.getDefaults(),{detune:0,frequency:440,type:"sine"})}start(t){const e=this.toSeconds(t);return this.log("start",e),this._startGain(e),this._oscillator.start(e),this}_stopSource(t){this._oscillator.stop(t)}setPeriodicWave(t){return this._oscillator.setPeriodicWave(t),this}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t}dispose(){return super.dispose(),"started"===this.state&&this.stop(),this._oscillator.disconnect(),this.frequency.dispose(),this.detune.dispose(),this}}class he extends ne{constructor(){super(q(he.getDefaults(),arguments,["frequency","type"])),this.name="Oscillator",this._oscillator=null;const t=q(he.getDefaults(),arguments,["frequency","type"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),$(this,"frequency"),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),$(this,"detune"),this._partials=t.partials,this._partialCount=t.partialCount,this._type=t.type,t.partialCount&&"custom"!==t.type&&(this._type=this.baseType+t.partialCount.toString()),this.phase=t.phase}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,partialCount:0,partials:[],phase:0,type:"sine"})}_start(t){const e=this.toSeconds(t),n=new ue({context:this.context,onended:()=>this.onstop(this)});this._oscillator=n,this._wave?this._oscillator.setPeriodicWave(this._wave):this._oscillator.type=this._type,this._oscillator.connect(this.output),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.start(e)}_stop(t){const e=this.toSeconds(t);this._oscillator&&this._oscillator.stop(e)}_restart(t){const e=this.toSeconds(t);return this.log("restart",e),this._oscillator&&this._oscillator.cancelStop(),this._state.cancel(e),this}syncFrequency(){return this.context.transport.syncSignal(this.frequency),this}unsyncFrequency(){return this.context.transport.unsyncSignal(this.frequency),this}_getCachedPeriodicWave(){if("custom"===this._type){return he._periodicWaveCache.find(t=>{return t.phase===this._phase&&(e=t.partials,n=this._partials,e.length===n.length&&e.every((t,e)=>n[e]===t));var e,n})}{const t=he._periodicWaveCache.find(t=>t.type===this._type&&t.phase===this._phase);return this._partialCount=t?t.partialCount:this._partialCount,t}}get type(){return this._type}set type(t){this._type=t;const e=-1!==["sine","square","sawtooth","triangle"].indexOf(t);if(0===this._phase&&e)this._wave=void 0,this._partialCount=0,null!==this._oscillator&&(this._oscillator.type=t);else{const e=this._getCachedPeriodicWave();if(f(e)){const{partials:t,wave:n}=e;this._wave=n,this._partials=t,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave)}else{const[e,n]=this._getRealImaginary(t,this._phase),s=this.context.createPeriodicWave(e,n);this._wave=s,null!==this._oscillator&&this._oscillator.setPeriodicWave(this._wave),he._periodicWaveCache.push({imag:n,partialCount:this._partialCount,partials:this._partials,phase:this._phase,real:e,type:this._type,wave:this._wave}),he._periodicWaveCache.length>100&&he._periodicWaveCache.shift()}}}get baseType(){return this._type.replace(this.partialCount.toString(),"")}set baseType(t){this.partialCount&&"custom"!==this._type&&"custom"!==t?this.type=t+this.partialCount:this.type=t}get partialCount(){return this._partialCount}set partialCount(t){a(t,0);let e=this._type;const n=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(this._type);if(n&&(e=n[1]),"custom"!==this._type)this.type=0===t?e:e+t.toString();else{const e=new Float32Array(t);this._partials.forEach((t,n)=>e[n]=t),this._partials=Array.from(e),this.type=this._type}}_getRealImaginary(t,e){let n=2048;const s=new Float32Array(n),i=new Float32Array(n);let o=1;if("custom"===t){if(o=this._partials.length+1,this._partialCount=this._partials.length,n=o,0===this._partials.length)return[s,i]}else{const e=/^(sine|triangle|square|sawtooth)(\d+)$/.exec(t);e?(o=parseInt(e[2],10)+1,this._partialCount=parseInt(e[2],10),t=e[1],o=Math.max(o,2),n=o):this._partialCount=0,this._partials=[]}for(let r=1;r>1&1?-1:1):0,this._partials[r-1]=a;break;case"custom":a=this._partials[r-1];break;default:throw new TypeError("Oscillator: invalid type: "+t)}0!==a?(s[r]=-a*Math.sin(e*r),i[r]=a*Math.cos(e*r)):(s[r]=0,i[r]=0)}return[s,i]}_inverseFFT(t,e,n){let s=0;const i=t.length;for(let o=0;oe.includes(t)),"oversampling must be either 'none', '2x', or '4x'"),this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.disconnect(),this}}class pe extends le{constructor(){super(...arguments),this.name="AudioToGain",this._norm=new de({context:this.context,mapping:t=>(t+1)/2}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class fe extends Rt{constructor(){super(Object.assign(q(fe.getDefaults(),arguments,["value"]))),this.name="Multiply",this.override=!1;const t=q(fe.getDefaults(),arguments,["value"]);this._mult=this.input=this.output=new Mt({context:this.context,minValue:t.minValue,maxValue:t.maxValue}),this.factor=this._param=this._mult.gain,this.factor.setValueAtTime(t.value,0)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._mult.dispose(),this}}class _e extends ne{constructor(){super(q(_e.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="AMOscillator",this._modulationScale=new pe({context:this.context}),this._modulationNode=new Mt({context:this.context});const t=q(_e.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.frequency=this._carrier.frequency,this.detune=this._carrier.detune,this._modulator=new he({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this.frequency.chain(this.harmonicity,this._modulator.frequency),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output),$(this,["frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(he.getDefaults(),{harmonicity:1,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){this._modulator.restart(t),this._carrier.restart(t)}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this._modulationScale.dispose(),this}}class me extends ne{constructor(){super(q(me.getDefaults(),arguments,["frequency","type","modulationType"])),this.name="FMOscillator",this._modulationNode=new Mt({context:this.context,gain:0});const t=q(me.getDefaults(),arguments,["frequency","type","modulationType"]);this._carrier=new he({context:this.context,detune:t.detune,frequency:0,onstop:()=>this.onstop(this),phase:t.phase,type:t.type}),this.detune=this._carrier.detune,this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this._modulator=new he({context:this.context,phase:t.phase,type:t.modulationType}),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this.modulationIndex=new fe({context:this.context,units:"positive",value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output),this.detune.connect(this._modulator.detune),$(this,["modulationIndex","frequency","detune","harmonicity"])}static getDefaults(){return Object.assign(he.getDefaults(),{harmonicity:1,modulationIndex:2,modulationType:"square"})}_start(t){this._modulator.start(t),this._carrier.start(t)}_stop(t){this._modulator.stop(t),this._carrier.stop(t)}_restart(t){return this._modulator.restart(t),this._carrier.restart(t),this}get type(){return this._carrier.type}set type(t){this._carrier.type=t}get baseType(){return this._carrier.baseType}set baseType(t){this._carrier.baseType=t}get partialCount(){return this._carrier.partialCount}set partialCount(t){this._carrier.partialCount=t}get modulationType(){return this._modulator.type}set modulationType(t){this._modulator.type=t}get phase(){return this._carrier.phase}set phase(t){this._carrier.phase=t,this._modulator.phase=t}get partials(){return this._carrier.partials}set partials(t){this._carrier.partials=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.harmonicity.dispose(),this._carrier.dispose(),this._modulator.dispose(),this._modulationNode.dispose(),this.modulationIndex.dispose(),this}}class ge extends ne{constructor(){super(q(ge.getDefaults(),arguments,["frequency","width"])),this.name="PulseOscillator",this._widthGate=new Mt({context:this.context,gain:0}),this._thresh=new de({context:this.context,mapping:t=>t<=0?-1:1});const t=q(ge.getDefaults(),arguments,["frequency","width"]);this.width=new Rt({context:this.context,units:"audioRange",value:t.width}),this._triangle=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase,type:"triangle"}),this.frequency=this._triangle.frequency,this.detune=this._triangle.detune,this._triangle.chain(this._thresh,this.output),this.width.chain(this._widthGate,this._thresh),$(this,["width","frequency","detune"])}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,phase:0,type:"pulse",width:.2})}_start(t){t=this.toSeconds(t),this._triangle.start(t),this._widthGate.gain.setValueAtTime(1,t)}_stop(t){t=this.toSeconds(t),this._triangle.stop(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(0,t)}_restart(t){this._triangle.restart(t),this._widthGate.gain.cancelScheduledValues(t),this._widthGate.gain.setValueAtTime(1,t)}get phase(){return this._triangle.phase}set phase(t){this._triangle.phase=t}get type(){return"pulse"}get baseType(){return"pulse"}get partials(){return[]}get partialCount(){return 0}set carrierType(t){this._triangle.type=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this._triangle.dispose(),this.width.dispose(),this._widthGate.dispose(),this._thresh.dispose(),this}}class ve extends ne{constructor(){super(q(ve.getDefaults(),arguments,["frequency","type","spread"])),this.name="FatOscillator",this._oscillators=[];const t=q(ve.getDefaults(),arguments,["frequency","type","spread"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this._spread=t.spread,this._type=t.type,this._phase=t.phase,this._partials=t.partials,this._partialCount=t.partialCount,this.count=t.count,$(this,["frequency","detune"])}static getDefaults(){return Object.assign(he.getDefaults(),{count:3,spread:20,type:"sawtooth"})}_start(t){t=this.toSeconds(t),this._forEach(e=>e.start(t))}_stop(t){t=this.toSeconds(t),this._forEach(e=>e.stop(t))}_restart(t){this._forEach(e=>e.restart(t))}_forEach(t){for(let e=0;ee.type=t)}get spread(){return this._spread}set spread(t){if(this._spread=t,this._oscillators.length>1){const e=-t/2,n=t/(this._oscillators.length-1);this._forEach((t,s)=>t.detune.value=e+n*s)}}get count(){return this._oscillators.length}set count(t){if(a(t,1),this._oscillators.length!==t){this._forEach(t=>t.dispose()),this._oscillators=[];for(let e=0;ethis.onstop(this):K});"custom"===this.type&&(n.partials=this._partials),this.frequency.connect(n.frequency),this.detune.connect(n.detune),n.detune.overridden=!1,n.connect(this.output),this._oscillators[e]=n}this.spread=this._spread,"started"===this.state&&this._forEach(t=>t.start())}}get phase(){return this._phase}set phase(t){this._phase=t,this._forEach(e=>e.phase=t)}get baseType(){return this._oscillators[0].baseType}set baseType(t){this._forEach(e=>e.baseType=t),this._type=this._oscillators[0].type}get partials(){return this._oscillators[0].partials}set partials(t){this._partials=t,this._partialCount=this._partials.length,t.length&&(this._type="custom",this._forEach(e=>e.partials=t))}get partialCount(){return this._oscillators[0].partialCount}set partialCount(t){this._partialCount=t,this._forEach(e=>e.partialCount=t),this._type=this._oscillators[0].type}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.frequency.dispose(),this.detune.dispose(),this._forEach(t=>t.dispose()),this}}class ye extends ne{constructor(){super(q(ye.getDefaults(),arguments,["frequency","modulationFrequency"])),this.name="PWMOscillator",this.sourceType="pwm",this._scale=new fe({context:this.context,value:2});const t=q(ye.getDefaults(),arguments,["frequency","modulationFrequency"]);this._pulse=new ge({context:this.context,frequency:t.modulationFrequency}),this._pulse.carrierType="sine",this.modulationFrequency=this._pulse.frequency,this._modulator=new he({context:this.context,detune:t.detune,frequency:t.frequency,onstop:()=>this.onstop(this),phase:t.phase}),this.frequency=this._modulator.frequency,this.detune=this._modulator.detune,this._modulator.chain(this._scale,this._pulse.width),this._pulse.connect(this.output),$(this,["modulationFrequency","frequency","detune"])}static getDefaults(){return Object.assign(ne.getDefaults(),{detune:0,frequency:440,modulationFrequency:.4,phase:0,type:"pwm"})}_start(t){t=this.toSeconds(t),this._modulator.start(t),this._pulse.start(t)}_stop(t){t=this.toSeconds(t),this._modulator.stop(t),this._pulse.stop(t)}_restart(t){this._modulator.restart(t),this._pulse.restart(t)}get type(){return"pwm"}get baseType(){return"pwm"}get partials(){return[]}get partialCount(){return 0}get phase(){return this._modulator.phase}set phase(t){this._modulator.phase=t}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this._pulse.dispose(),this._scale.dispose(),this._modulator.dispose(),this}}const be={am:_e,fat:ve,fm:me,oscillator:he,pulse:ge,pwm:ye};class xe extends ne{constructor(){super(q(xe.getDefaults(),arguments,["frequency","type"])),this.name="OmniOscillator";const t=q(xe.getDefaults(),arguments,["frequency","type"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),$(this,["frequency","detune"]),this.set(t)}static getDefaults(){return Object.assign(he.getDefaults(),me.getDefaults(),_e.getDefaults(),ve.getDefaults(),ge.getDefaults(),ye.getDefaults())}_start(t){this._oscillator.start(t)}_stop(t){this._oscillator.stop(t)}_restart(t){return this._oscillator.restart(t),this}get type(){let t="";return["am","fm","fat"].some(t=>this._sourceType===t)&&(t=this._sourceType),t+this._oscillator.type}set type(t){"fm"===t.substr(0,2)?(this._createNewOscillator("fm"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"am"===t.substr(0,2)?(this._createNewOscillator("am"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(2)):"fat"===t.substr(0,3)?(this._createNewOscillator("fat"),this._oscillator=this._oscillator,this._oscillator.type=t.substr(3)):"pwm"===t?(this._createNewOscillator("pwm"),this._oscillator=this._oscillator):"pulse"===t?this._createNewOscillator("pulse"):(this._createNewOscillator("oscillator"),this._oscillator=this._oscillator,this._oscillator.type=t)}get partials(){return this._oscillator.partials}set partials(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partials=t)}get partialCount(){return this._oscillator.partialCount}set partialCount(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||(this._oscillator.partialCount=t)}set(t){return Reflect.has(t,"type")&&t.type&&(this.type=t.type),super.set(t),this}_createNewOscillator(t){if(t!==this._sourceType){this._sourceType=t;const e=be[t],n=this.now();if(this._oscillator){const t=this._oscillator;t.stop(n),this.context.setTimeout(()=>t.dispose(),this.blockTime)}this._oscillator=new e({context:this.context}),this.frequency.connect(this._oscillator.frequency),this.detune.connect(this._oscillator.detune),this._oscillator.connect(this.output),this._oscillator.onstop=()=>this.onstop(this),"started"===this.state&&this._oscillator.start(n)}}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t}get sourceType(){return this._sourceType}set sourceType(t){let e="sine";"pwm"!==this._oscillator.type&&"pulse"!==this._oscillator.type&&(e=this._oscillator.type),"fm"===t?this.type="fm"+e:"am"===t?this.type="am"+e:"fat"===t?this.type="fat"+e:"oscillator"===t?this.type=e:"pulse"===t?this.type="pulse":"pwm"===t&&(this.type="pwm")}_getOscType(t,e){return t instanceof be[e]}get baseType(){return this._oscillator.baseType}set baseType(t){this._getOscType(this._oscillator,"pulse")||this._getOscType(this._oscillator,"pwm")||"pulse"===t||"pwm"===t||(this._oscillator.baseType=t)}get width(){return this._getOscType(this._oscillator,"pulse")?this._oscillator.width:void 0}get count(){return this._getOscType(this._oscillator,"fat")?this._oscillator.count:void 0}set count(t){this._getOscType(this._oscillator,"fat")&&m(t)&&(this._oscillator.count=t)}get spread(){return this._getOscType(this._oscillator,"fat")?this._oscillator.spread:void 0}set spread(t){this._getOscType(this._oscillator,"fat")&&m(t)&&(this._oscillator.spread=t)}get modulationType(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.modulationType:void 0}set modulationType(t){(this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am"))&&b(t)&&(this._oscillator.modulationType=t)}get modulationIndex(){return this._getOscType(this._oscillator,"fm")?this._oscillator.modulationIndex:void 0}get harmonicity(){return this._getOscType(this._oscillator,"fm")||this._getOscType(this._oscillator,"am")?this._oscillator.harmonicity:void 0}get modulationFrequency(){return this._getOscType(this._oscillator,"pwm")?this._oscillator.modulationFrequency:void 0}asArray(t=1024){return S(this,void 0,void 0,(function*(){return ce(this,t)}))}dispose(){return super.dispose(),this.detune.dispose(),this.frequency.dispose(),this._oscillator.dispose(),this}}class we extends Rt{constructor(){super(Object.assign(q(we.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Add",this._sum=new Mt({context:this.context}),this.input=this._sum,this.output=this._sum,this.addend=this._param,kt(this._constantSource,this._sum)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._sum.dispose(),this}}class Te extends le{constructor(){super(Object.assign(q(Te.getDefaults(),arguments,["min","max"]))),this.name="Scale";const t=q(Te.getDefaults(),arguments,["min","max"]);this._mult=this.input=new fe({context:this.context,value:t.max-t.min}),this._add=this.output=new we({context:this.context,value:t.min}),this._min=t.min,this._max=t.max,this.input.connect(this.output)}static getDefaults(){return Object.assign(le.getDefaults(),{max:1,min:0})}get min(){return this._min}set min(t){this._min=t,this._setRange()}get max(){return this._max}set max(t){this._max=t,this._setRange()}_setRange(){this._add.value=this._min,this._mult.value=this._max-this._min}dispose(){return super.dispose(),this._add.dispose(),this._mult.dispose(),this}}class Oe extends le{constructor(){super(Object.assign(q(Oe.getDefaults(),arguments))),this.name="Zero",this._gain=new Mt({context:this.context}),this.output=this._gain,this.input=void 0,At(this.context.getConstant(0),this._gain)}dispose(){return super.dispose(),Dt(this.context.getConstant(0),this._gain),this}}class Se extends Ct{constructor(){super(q(Se.getDefaults(),arguments,["frequency","min","max"])),this.name="LFO",this._stoppedValue=0,this._units="number",this.convert=!0,this._fromType=St.prototype._fromType,this._toType=St.prototype._toType,this._is=St.prototype._is,this._clampValue=St.prototype._clampValue;const t=q(Se.getDefaults(),arguments,["frequency","min","max"]);this._oscillator=new he({context:this.context,frequency:t.frequency,type:t.type}),this.frequency=this._oscillator.frequency,this._amplitudeGain=new Mt({context:this.context,gain:t.amplitude,units:"normalRange"}),this.amplitude=this._amplitudeGain.gain,this._stoppedSignal=new Rt({context:this.context,units:"audioRange",value:0}),this._zeros=new Oe({context:this.context}),this._a2g=new pe({context:this.context}),this._scaler=this.output=new Te({context:this.context,max:t.max,min:t.min}),this.units=t.units,this.min=t.min,this.max=t.max,this._oscillator.chain(this._a2g,this._amplitudeGain,this._scaler),this._zeros.connect(this._a2g),this._stoppedSignal.connect(this._a2g),$(this,["amplitude","frequency"]),this.phase=t.phase}static getDefaults(){return Object.assign(Ct.getDefaults(),{amplitude:1,frequency:"4n",max:1,min:0,phase:0,type:"sine",units:"number"})}start(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(0,t),this._oscillator.start(t),this}stop(t){return t=this.toSeconds(t),this._stoppedSignal.setValueAtTime(this._stoppedValue,t),this._oscillator.stop(t),this}sync(){return this._oscillator.sync(),this._oscillator.syncFrequency(),this}unsync(){return this._oscillator.unsync(),this._oscillator.unsyncFrequency(),this}get min(){return this._toType(this._scaler.min)}set min(t){t=this._fromType(t),this._scaler.min=t}get max(){return this._toType(this._scaler.max)}set max(t){t=this._fromType(t),this._scaler.max=t}get type(){return this._oscillator.type}set type(t){this._oscillator.type=t,this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get phase(){return this._oscillator.phase}set phase(t){this._oscillator.phase=t,this._stoppedValue=this._oscillator.getInitialValue(),this._stoppedSignal.value=this._stoppedValue}get units(){return this._units}set units(t){const e=this.min,n=this.max;this._units=t,this.min=e,this.max=n}get state(){return this._oscillator.state}connect(t,e,n){return(t instanceof St||t instanceof Rt)&&(this.convert=t.convert,this.units=t.units),qt(this,t,e,n),this}dispose(){return super.dispose(),this._oscillator.dispose(),this._stoppedSignal.dispose(),this._zeros.dispose(),this._scaler.dispose(),this._a2g.dispose(),this._amplitudeGain.dispose(),this.amplitude.dispose(),this}}function Ce(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){a(s,t,e),n.set(this,s)}})}}function ke(t,e=1/0){const n=new WeakMap;return function(s,i){Reflect.defineProperty(s,i,{configurable:!0,enumerable:!0,get:function(){return n.get(this)},set:function(s){a(this.toSeconds(s),t,e),n.set(this,s)}})}}class Ae extends ne{constructor(){super(q(Ae.getDefaults(),arguments,["url","onload"])),this.name="Player",this._activeSources=new Set;const t=q(Ae.getDefaults(),arguments,["url","onload"]);this._buffer=new tt({onload:this._onload.bind(this,t.onload),onerror:t.onerror,reverse:t.reverse,url:t.url}),this.autostart=t.autostart,this._loop=t.loop,this._loopStart=t.loopStart,this._loopEnd=t.loopEnd,this._playbackRate=t.playbackRate,this.fadeIn=t.fadeIn,this.fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{autostart:!1,fadeIn:0,fadeOut:0,loop:!1,loopEnd:0,loopStart:0,onload:K,onerror:K,playbackRate:1,reverse:!1})}load(t){return S(this,void 0,void 0,(function*(){return yield this._buffer.load(t),this._onload(),this}))}_onload(t=K){t(),this.autostart&&this.start()}_onSourceEnd(t){this.onstop(this),this._activeSources.delete(t),0!==this._activeSources.size||this._synced||"started"!==this._state.getValueAtTime(this.now())||this._state.setStateAtTime("stopped",this.now())}start(t,e,n){return super.start(t,e,n),this}_start(t,e,n){e=this._loop?I(e,this._loopStart):I(e,0);let s=this.toSeconds(e);this._synced&&(s*=this._playbackRate);const i=n;n=I(n,Math.max(this._buffer.duration-s,0));let o=this.toSeconds(n);o/=this._playbackRate,t=this.toSeconds(t);const r=new se({url:this._buffer,context:this.context,fadeIn:this.fadeIn,fadeOut:this.fadeOut,loop:this._loop,loopEnd:this._loopEnd,loopStart:this._loopStart,onended:this._onSourceEnd.bind(this),playbackRate:this._playbackRate}).connect(this.output);this._loop||this._synced||(this._state.cancel(t+o),this._state.setStateAtTime("stopped",t+o,{implicitEnd:!0})),this._activeSources.add(r),this._loop&&p(i)?r.start(t,s):r.start(t,s,o-this.toSeconds(this.fadeOut))}_stop(t){const e=this.toSeconds(t);this._activeSources.forEach(t=>t.stop(e))}restart(t,e,n){return super.restart(t,e,n),this}_restart(t,e,n){this._stop(t),this._start(t,e,n)}seek(t,e){const n=this.toSeconds(e);if("started"===this._state.getValueAtTime(n)){const e=this.toSeconds(t);this._stop(n),this._start(n,e)}return this}setLoopPoints(t,e){return this.loopStart=t,this.loopEnd=e,this}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopStart=t})}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._activeSources.forEach(e=>{e.loopEnd=t})}get buffer(){return this._buffer}set buffer(t){this._buffer.set(t)}get loop(){return this._loop}set loop(t){if(this._loop!==t&&(this._loop=t,this._activeSources.forEach(e=>{e.loop=t}),t)){const t=this._state.getNextState("stopped",this.now());t&&this._state.cancel(t.time)}}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t;const e=this.now(),n=this._state.getNextState("stopped",e);n&&n.implicitEnd&&(this._state.cancel(n.time),this._activeSources.forEach(t=>t.cancelStop())),this._activeSources.forEach(n=>{n.playbackRate.setValueAtTime(t,e)})}get reverse(){return this._buffer.reverse}set reverse(t){this._buffer.reverse=t}get loaded(){return this._buffer.loaded}dispose(){return super.dispose(),this._activeSources.forEach(t=>t.dispose()),this._activeSources.clear(),this._buffer.dispose(),this}}O([ke(0)],Ae.prototype,"fadeIn",void 0),O([ke(0)],Ae.prototype,"fadeOut",void 0);class De extends Ct{constructor(){super(q(De.getDefaults(),arguments,["urls","onload"],"urls")),this.name="Players",this.input=void 0,this._players=new Map;const t=q(De.getDefaults(),arguments,["urls","onload"],"urls");this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,$(this,"volume"),this._buffers=new $t({urls:t.urls,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.mute=t.mute,this._fadeIn=t.fadeIn,this._fadeOut=t.fadeOut}static getDefaults(){return Object.assign(ne.getDefaults(),{baseUrl:"",fadeIn:0,fadeOut:0,mute:!1,onload:K,onerror:K,urls:{},volume:0})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}get fadeIn(){return this._fadeIn}set fadeIn(t){this._fadeIn=t,this._players.forEach(e=>{e.fadeIn=t})}get fadeOut(){return this._fadeOut}set fadeOut(t){this._fadeOut=t,this._players.forEach(e=>{e.fadeOut=t})}get state(){return Array.from(this._players).some(([t,e])=>"started"===e.state)?"started":"stopped"}has(t){return this._buffers.has(t)}player(t){if(r(this.has(t),`No Player with the name ${t} exists on this object`),!this._players.has(t)){const e=new Ae({context:this.context,fadeIn:this._fadeIn,fadeOut:this._fadeOut,url:this._buffers.get(t)}).connect(this.output);this._players.set(t,e)}return this._players.get(t)}get loaded(){return this._buffers.loaded}add(t,e,n){return r(!this._buffers.has(t),"A buffer with that name already exists on this object"),this._buffers.add(t,e,n),this}stopAll(t){return this._players.forEach(e=>e.stop(t)),this}dispose(){return super.dispose(),this._volume.dispose(),this.volume.dispose(),this._players.forEach(t=>t.dispose()),this._buffers.dispose(),this}}class Me extends ne{constructor(){super(q(Me.getDefaults(),arguments,["url","onload"])),this.name="GrainPlayer",this._loopStart=0,this._loopEnd=0,this._activeSources=[];const t=q(Me.getDefaults(),arguments,["url","onload"]);this.buffer=new tt({onload:t.onload,onerror:t.onerror,reverse:t.reverse,url:t.url}),this._clock=new Nt({context:this.context,callback:this._tick.bind(this),frequency:1/t.grainSize}),this._playbackRate=t.playbackRate,this._grainSize=t.grainSize,this._overlap=t.overlap,this.detune=t.detune,this.overlap=t.overlap,this.loop=t.loop,this.playbackRate=t.playbackRate,this.grainSize=t.grainSize,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.reverse=t.reverse,this._clock.on("stop",this._onstop.bind(this))}static getDefaults(){return Object.assign(ne.getDefaults(),{onload:K,onerror:K,overlap:.1,grainSize:.2,playbackRate:1,detune:0,loop:!1,loopStart:0,loopEnd:0,reverse:!1})}_start(t,e,n){e=I(e,0),e=this.toSeconds(e),t=this.toSeconds(t);const s=1/this._clock.frequency.getValueAtTime(t);this._clock.start(t,e/s),n&&this.stop(t+this.toSeconds(n))}restart(t,e,n){return super.restart(t,e,n),this}_restart(t,e,n){this._stop(t),this._start(t,e,n)}_stop(t){this._clock.stop(t)}_onstop(t){this._activeSources.forEach(e=>{e.fadeOut=0,e.stop(t)}),this.onstop(this)}_tick(t){const e=this._clock.getTicksAtTime(t),n=e*this._grainSize;if(this.log("offset",n),!this.loop&&n>this.buffer.duration)return void this.stop(t);const s=n{const t=this._activeSources.indexOf(i);-1!==t&&this._activeSources.splice(t,1)}}get playbackRate(){return this._playbackRate}set playbackRate(t){a(t,.001),this._playbackRate=t,this.grainSize=this._grainSize}get loopStart(){return this._loopStart}set loopStart(t){this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._loopStart=this.toSeconds(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this.buffer.loaded&&a(this.toSeconds(t),0,this.buffer.duration),this._loopEnd=this.toSeconds(t)}get reverse(){return this.buffer.reverse}set reverse(t){this.buffer.reverse=t}get grainSize(){return this._grainSize}set grainSize(t){this._grainSize=this.toSeconds(t),this._clock.frequency.setValueAtTime(this._playbackRate/this._grainSize,this.now())}get overlap(){return this._overlap}set overlap(t){const e=this.toSeconds(t);a(e,0),this._overlap=e}get loaded(){return this.buffer.loaded}dispose(){return super.dispose(),this.buffer.dispose(),this._clock.dispose(),this._activeSources.forEach(t=>t.dispose()),this}}class je extends le{constructor(){super(...arguments),this.name="Abs",this._abs=new de({context:this.context,mapping:t=>Math.abs(t)<.001?0:Math.abs(t)}),this.input=this._abs,this.output=this._abs}dispose(){return super.dispose(),this._abs.dispose(),this}}class Ee extends le{constructor(){super(...arguments),this.name="GainToAudio",this._norm=new de({context:this.context,mapping:t=>2*Math.abs(t)-1}),this.input=this._norm,this.output=this._norm}dispose(){return super.dispose(),this._norm.dispose(),this}}class Re extends le{constructor(){super(...arguments),this.name="Negate",this._multiply=new fe({context:this.context,value:-1}),this.input=this._multiply,this.output=this._multiply}dispose(){return super.dispose(),this._multiply.dispose(),this}}class qe extends Rt{constructor(){super(Object.assign(q(qe.getDefaults(),arguments,["value"]))),this.override=!1,this.name="Subtract",this._sum=new Mt({context:this.context}),this.input=this._sum,this.output=this._sum,this._neg=new Re({context:this.context}),this.subtrahend=this._param,kt(this._constantSource,this._neg,this._sum)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._neg.dispose(),this._sum.dispose(),this}}class Ie extends le{constructor(){super(Object.assign(q(Ie.getDefaults(),arguments))),this.name="GreaterThanZero",this._thresh=this.output=new de({context:this.context,length:127,mapping:t=>t<=0?0:1}),this._scale=this.input=new fe({context:this.context,value:1e4}),this._scale.connect(this._thresh)}dispose(){return super.dispose(),this._scale.dispose(),this._thresh.dispose(),this}}class Fe extends Rt{constructor(){super(Object.assign(q(Fe.getDefaults(),arguments,["value"]))),this.name="GreaterThan",this.override=!1;const t=q(Fe.getDefaults(),arguments,["value"]);this._subtract=this.input=new qe({context:this.context,value:t.value}),this._gtz=this.output=new Ie({context:this.context}),this.comparator=this._param=this._subtract.subtrahend,$(this,"comparator"),this._subtract.connect(this._gtz)}static getDefaults(){return Object.assign(Rt.getDefaults(),{value:0})}dispose(){return super.dispose(),this._gtz.dispose(),this._subtract.dispose(),this.comparator.dispose(),this}}class Ve extends le{constructor(){super(Object.assign(q(Ve.getDefaults(),arguments,["value"]))),this.name="Pow";const t=q(Ve.getDefaults(),arguments,["value"]);this._exponentScaler=this.input=this.output=new de({context:this.context,mapping:this._expFunc(t.value),length:8192}),this._exponent=t.value}static getDefaults(){return Object.assign(le.getDefaults(),{value:1})}_expFunc(t){return e=>Math.pow(Math.abs(e),t)}get value(){return this._exponent}set value(t){this._exponent=t,this._exponentScaler.setMap(this._expFunc(this._exponent))}dispose(){return super.dispose(),this._exponentScaler.dispose(),this}}class Ne extends Te{constructor(){super(Object.assign(q(Ne.getDefaults(),arguments,["min","max","exponent"]))),this.name="ScaleExp";const t=q(Ne.getDefaults(),arguments,["min","max","exponent"]);this.input=this._exp=new Ve({context:this.context,value:t.exponent}),this._exp.connect(this._mult)}static getDefaults(){return Object.assign(Te.getDefaults(),{exponent:1})}get exponent(){return this._exp.value}set exponent(t){this._exp.value=t}dispose(){return super.dispose(),this._exp.dispose(),this}}class Pe extends Rt{constructor(){super(q(Rt.getDefaults(),arguments,["value","units"])),this.name="SyncedSignal",this.override=!1;const t=q(Rt.getDefaults(),arguments,["value","units"]);this._lastVal=t.value,this._synced=this.context.transport.scheduleRepeat(this._onTick.bind(this),"1i"),this._syncedCallback=this._anchorValue.bind(this),this.context.transport.on("start",this._syncedCallback),this.context.transport.on("pause",this._syncedCallback),this.context.transport.on("stop",this._syncedCallback),this._constantSource.disconnect(),this._constantSource.stop(0),this._constantSource=this.output=new Et({context:this.context,offset:t.value,units:t.units}).start(0),this.setValueAtTime(t.value,0)}_onTick(t){const e=super.getValueAtTime(this.context.transport.seconds);this._lastVal!==e&&(this._lastVal=e,this._constantSource.offset.setValueAtTime(e,t))}_anchorValue(t){const e=super.getValueAtTime(this.context.transport.seconds);this._lastVal=e,this._constantSource.offset.cancelAndHoldAtTime(t),this._constantSource.offset.setValueAtTime(e,t)}getValueAtTime(t){const e=new xt(this.context,t).toSeconds();return super.getValueAtTime(e)}setValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.setValueAtTime(t,n),this}linearRampToValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.linearRampToValueAtTime(t,n),this}exponentialRampToValueAtTime(t,e){const n=new xt(this.context,e).toSeconds();return super.exponentialRampToValueAtTime(t,n),this}setTargetAtTime(t,e,n){const s=new xt(this.context,e).toSeconds();return super.setTargetAtTime(t,s,n),this}cancelScheduledValues(t){const e=new xt(this.context,t).toSeconds();return super.cancelScheduledValues(e),this}setValueCurveAtTime(t,e,n,s){const i=new xt(this.context,e).toSeconds();return n=this.toSeconds(n),super.setValueCurveAtTime(t,i,n,s),this}cancelAndHoldAtTime(t){const e=new xt(this.context,t).toSeconds();return super.cancelAndHoldAtTime(e),this}setRampPoint(t){const e=new xt(this.context,t).toSeconds();return super.setRampPoint(e),this}exponentialRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.exponentialRampTo(t,e,s),this}linearRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.linearRampTo(t,e,s),this}targetRampTo(t,e,n){const s=new xt(this.context,n).toSeconds();return super.targetRampTo(t,e,s),this}dispose(){return super.dispose(),this.context.transport.clear(this._synced),this.context.transport.off("start",this._syncedCallback),this.context.transport.off("pause",this._syncedCallback),this.context.transport.off("stop",this._syncedCallback),this._constantSource.dispose(),this}}class Le extends Ct{constructor(){super(q(Le.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="Envelope",this._sig=new Rt({context:this.context,value:0}),this.output=this._sig,this.input=void 0;const t=q(Le.getDefaults(),arguments,["attack","decay","sustain","release"]);this.attack=t.attack,this.decay=t.decay,this.sustain=t.sustain,this.release=t.release,this.attackCurve=t.attackCurve,this.releaseCurve=t.releaseCurve,this.decayCurve=t.decayCurve}static getDefaults(){return Object.assign(Ct.getDefaults(),{attack:.01,attackCurve:"linear",decay:.1,decayCurve:"exponential",release:1,releaseCurve:"exponential",sustain:.5})}get value(){return this.getValueAtTime(this.now())}_getCurve(t,e){if(b(t))return t;{let n;for(n in ze)if(ze[n][e]===t)return n;return t}}_setCurve(t,e,n){if(b(n)&&Reflect.has(ze,n)){const s=ze[n];g(s)?"_decayCurve"!==t&&(this[t]=s[e]):this[t]=s}else{if(!y(n)||"_decayCurve"===t)throw new Error("Envelope: invalid curve: "+n);this[t]=n}}get attackCurve(){return this._getCurve(this._attackCurve,"In")}set attackCurve(t){this._setCurve("_attackCurve","In",t)}get releaseCurve(){return this._getCurve(this._releaseCurve,"Out")}set releaseCurve(t){this._setCurve("_releaseCurve","Out",t)}get decayCurve(){return this._decayCurve}set decayCurve(t){r(["linear","exponential"].some(e=>e===t),"Invalid envelope curve: "+t),this._decayCurve=t}triggerAttack(t,e=1){this.log("triggerAttack",t,e),t=this.toSeconds(t);let n=this.toSeconds(this.attack);const s=this.toSeconds(this.decay),i=this.getValueAtTime(t);if(i>0){n=(1-i)/(1/n)}if(n0){const n=this.toSeconds(this.release);n{let t,e;const n=[];for(t=0;t<128;t++)n[t]=Math.sin(t/127*(Math.PI/2));const s=[];for(t=0;t<127;t++){e=t/127;const n=Math.sin(e*(2*Math.PI)*6.4-Math.PI/2)+1;s[t]=n/10+.83*e}s[127]=1;const i=[];for(t=0;t<128;t++)i[t]=Math.ceil(t/127*5)/5;const o=[];for(t=0;t<128;t++)e=t/127,o[t]=.5*(1-Math.cos(Math.PI*e));const r=[];for(t=0;t<128;t++){e=t/127;const n=4*Math.pow(e,3)+.2,s=Math.cos(n*Math.PI*2*e);r[t]=Math.abs(s*(1-e))}function a(t){const e=new Array(t.length);for(let n=0;n{const s=t[e],i=this.context.transport.schedule(s=>{t[e]=s,n.apply(this,t)},s);this._scheduledEvents.push(i)}}unsync(){return this._scheduledEvents.forEach(t=>this.context.transport.clear(t)),this._scheduledEvents=[],this._synced&&(this._synced=!1,this.triggerAttack=this._original_triggerAttack,this.triggerRelease=this._original_triggerRelease),this}triggerAttackRelease(t,e,n,s){const i=this.toSeconds(n),o=this.toSeconds(e);return this.triggerAttack(t,i,s),this.triggerRelease(i+o),this}dispose(){return super.dispose(),this._volume.dispose(),this.unsync(),this._scheduledEvents=[],this}}class We extends Be{constructor(){super(q(We.getDefaults(),arguments));const t=q(We.getDefaults(),arguments);this.portamento=t.portamento,this.onsilence=t.onsilence}static getDefaults(){return Object.assign(Be.getDefaults(),{detune:0,onsilence:K,portamento:0})}triggerAttack(t,e,n=1){this.log("triggerAttack",t,e,n);const s=this.toSeconds(e);return this._triggerEnvelopeAttack(s,n),this.setNote(t,s),this}triggerRelease(t){this.log("triggerRelease",t);const e=this.toSeconds(t);return this._triggerEnvelopeRelease(e),this}setNote(t,e){const n=this.toSeconds(e),s=t instanceof gt?t.toFrequency():t;if(this.portamento>0&&this.getLevelAtTime(n)>.05){const t=this.toSeconds(this.portamento);this.frequency.exponentialRampTo(s,t,n)}else this.frequency.setValueAtTime(s,n);return this}}O([ke(0)],We.prototype,"portamento",void 0);class Ue extends Le{constructor(){super(q(Ue.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="AmplitudeEnvelope",this._gainNode=new Mt({context:this.context,gain:0}),this.output=this._gainNode,this.input=this._gainNode,this._sig.connect(this._gainNode.gain),this.output=this._gainNode,this.input=this._gainNode}dispose(){return super.dispose(),this._gainNode.dispose(),this}}class Ge extends We{constructor(){super(q(Ge.getDefaults(),arguments)),this.name="Synth";const t=q(Ge.getDefaults(),arguments);this.oscillator=new xe(Object.assign({context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)},t.oscillator)),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.envelope=new Ue(Object.assign({context:this.context},t.envelope)),this.oscillator.chain(this.envelope,this.output),$(this,["oscillator","frequency","detune","envelope"])}static getDefaults(){return Object.assign(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.3}),oscillator:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"triangle"})})}_triggerEnvelopeAttack(t,e){if(this.envelope.triggerAttack(t,e),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+n)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this}}class Ye extends We{constructor(){super(q(Ye.getDefaults(),arguments)),this.name="ModulationSynth";const t=q(Ye.getDefaults(),arguments);this._carrier=new Ge({context:this.context,oscillator:t.oscillator,envelope:t.envelope,onsilence:()=>this.onsilence(this),volume:-10}),this._modulator=new Ge({context:this.context,oscillator:t.modulation,envelope:t.modulationEnvelope,volume:-10}),this.oscillator=this._carrier.oscillator,this.envelope=this._carrier.envelope,this.modulation=this._modulator.oscillator,this.modulationEnvelope=this._modulator.envelope,this.frequency=new Rt({context:this.context,units:"frequency"}),this.detune=new Rt({context:this.context,value:t.detune,units:"cents"}),this.harmonicity=new fe({context:this.context,value:t.harmonicity,minValue:0}),this._modulationNode=new Mt({context:this.context,gain:0}),$(this,["frequency","harmonicity","oscillator","envelope","modulation","modulationEnvelope","detune"])}static getDefaults(){return Object.assign(We.getDefaults(),{harmonicity:3,oscillator:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"sine"}),envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.01,decay:.01,sustain:1,release:.5}),modulation:Object.assign(F(xe.getDefaults(),[...Object.keys(ne.getDefaults()),"frequency","detune"]),{type:"square"}),modulationEnvelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.5,decay:0,sustain:1,release:.5})})}_triggerEnvelopeAttack(t,e){this._carrier._triggerEnvelopeAttack(t,e),this._modulator._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this._carrier._triggerEnvelopeRelease(t),this._modulator._triggerEnvelopeRelease(t),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this._carrier.dispose(),this._modulator.dispose(),this.frequency.dispose(),this.detune.dispose(),this.harmonicity.dispose(),this._modulationNode.dispose(),this}}class Qe extends Ye{constructor(){super(q(Qe.getDefaults(),arguments)),this.name="AMSynth",this._modulationScale=new pe({context:this.context}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.chain(this._modulationScale,this._modulationNode.gain),this._carrier.chain(this._modulationNode,this.output)}dispose(){return super.dispose(),this._modulationScale.dispose(),this}}class Ze extends Ct{constructor(){super(q(Ze.getDefaults(),arguments,["frequency","type"])),this.name="BiquadFilter";const t=q(Ze.getDefaults(),arguments,["frequency","type"]);this._filter=this.context.createBiquadFilter(),this.input=this.output=this._filter,this.Q=new St({context:this.context,units:"number",value:t.Q,param:this._filter.Q}),this.frequency=new St({context:this.context,units:"frequency",value:t.frequency,param:this._filter.frequency}),this.detune=new St({context:this.context,units:"cents",value:t.detune,param:this._filter.detune}),this.gain=new St({context:this.context,units:"gain",value:t.gain,param:this._filter.gain}),this.type=t.type}static getDefaults(){return Object.assign(Ct.getDefaults(),{Q:1,type:"lowpass",frequency:350,detune:0,gain:0})}get type(){return this._filter.type}set type(t){r(-1!==["lowpass","highpass","bandpass","lowshelf","highshelf","notch","allpass","peaking"].indexOf(t),"Invalid filter type: "+t),this._filter.type=t}getFrequencyResponse(t=128){const e=new Float32Array(t);for(let n=0;ne.type=t)}get rolloff(){return this._rolloff}set rolloff(t){const e=m(t)?t:parseInt(t,10),n=[-12,-24,-48,-96];let s=n.indexOf(e);r(-1!==s,"rolloff can only be "+n.join(", ")),s+=1,this._rolloff=e,this.input.disconnect(),this._filters.forEach(t=>t.disconnect()),this._filters=new Array(s);for(let t=0;t1);return this._filters.forEach(()=>{e.getFrequencyResponse(t).forEach((t,e)=>n[e]*=t)}),e.dispose(),n}dispose(){return super.dispose(),this._filters.forEach(t=>{t.dispose()}),J(this,["detune","frequency","gain","Q"]),this.frequency.dispose(),this.Q.dispose(),this.detune.dispose(),this.gain.dispose(),this}}class He extends Le{constructor(){super(q(He.getDefaults(),arguments,["attack","decay","sustain","release"])),this.name="FrequencyEnvelope";const t=q(He.getDefaults(),arguments,["attack","decay","sustain","release"]);this._octaves=t.octaves,this._baseFrequency=this.toFrequency(t.baseFrequency),this._exponent=this.input=new Ve({context:this.context,value:t.exponent}),this._scale=this.output=new Te({context:this.context,min:this._baseFrequency,max:this._baseFrequency*Math.pow(2,this._octaves)}),this._sig.chain(this._exponent,this._scale)}static getDefaults(){return Object.assign(Le.getDefaults(),{baseFrequency:200,exponent:1,octaves:4})}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){const e=this.toFrequency(t);a(e,0),this._baseFrequency=e,this._scale.min=this._baseFrequency,this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){a(t,0),this._octaves=t,this._scale.max=this._baseFrequency*Math.pow(2,t)}get exponent(){return this._exponent.value}set exponent(t){this._exponent.value=t}dispose(){return super.dispose(),this._exponent.dispose(),this._scale.dispose(),this}}class $e extends We{constructor(){super(q($e.getDefaults(),arguments)),this.name="MonoSynth";const t=q($e.getDefaults(),arguments);this.oscillator=new xe(Object.assign(t.oscillator,{context:this.context,detune:t.detune,onstop:()=>this.onsilence(this)})),this.frequency=this.oscillator.frequency,this.detune=this.oscillator.detune,this.filter=new Xe(Object.assign(t.filter,{context:this.context})),this.filterEnvelope=new He(Object.assign(t.filterEnvelope,{context:this.context})),this.envelope=new Ue(Object.assign(t.envelope,{context:this.context})),this.oscillator.chain(this.filter,this.envelope,this.output),this.filterEnvelope.connect(this.filter.frequency),$(this,["oscillator","frequency","detune","filter","filterEnvelope","envelope"])}static getDefaults(){return Object.assign(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.005,decay:.1,release:1,sustain:.9}),filter:Object.assign(F(Xe.getDefaults(),Object.keys(Ct.getDefaults())),{Q:1,rolloff:-12,type:"lowpass"}),filterEnvelope:Object.assign(F(He.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.6,baseFrequency:200,decay:.2,exponent:2,octaves:3,release:2,sustain:.5}),oscillator:Object.assign(F(xe.getDefaults(),Object.keys(ne.getDefaults())),{type:"sawtooth"})})}_triggerEnvelopeAttack(t,e=1){if(this.envelope.triggerAttack(t,e),this.filterEnvelope.triggerAttack(t),this.oscillator.start(t),0===this.envelope.sustain){const e=this.toSeconds(this.envelope.attack),n=this.toSeconds(this.envelope.decay);this.oscillator.stop(t+e+n)}}_triggerEnvelopeRelease(t){this.envelope.triggerRelease(t),this.filterEnvelope.triggerRelease(t),this.oscillator.stop(t+this.toSeconds(this.envelope.release))}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}dispose(){return super.dispose(),this.oscillator.dispose(),this.envelope.dispose(),this.filterEnvelope.dispose(),this.filter.dispose(),this}}class Je extends We{constructor(){super(q(Je.getDefaults(),arguments)),this.name="DuoSynth";const t=q(Je.getDefaults(),arguments);this.voice0=new $e(Object.assign(t.voice0,{context:this.context,onsilence:()=>this.onsilence(this)})),this.voice1=new $e(Object.assign(t.voice1,{context:this.context})),this.harmonicity=new fe({context:this.context,units:"positive",value:t.harmonicity}),this._vibrato=new Se({frequency:t.vibratoRate,context:this.context,min:-50,max:50}),this._vibrato.start(),this.vibratoRate=this._vibrato.frequency,this._vibratoGain=new Mt({context:this.context,units:"normalRange",gain:t.vibratoAmount}),this.vibratoAmount=this._vibratoGain.gain,this.frequency=new Rt({context:this.context,units:"frequency",value:440}),this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this.frequency.connect(this.voice0.frequency),this.frequency.chain(this.harmonicity,this.voice1.frequency),this._vibrato.connect(this._vibratoGain),this._vibratoGain.fan(this.voice0.detune,this.voice1.detune),this.detune.fan(this.voice0.detune,this.voice1.detune),this.voice0.connect(this.output),this.voice1.connect(this.output),$(this,["voice0","voice1","frequency","vibratoAmount","vibratoRate"])}getLevelAtTime(t){return t=this.toSeconds(t),this.voice0.envelope.getValueAtTime(t)+this.voice1.envelope.getValueAtTime(t)}static getDefaults(){return R(We.getDefaults(),{vibratoAmount:.5,vibratoRate:5,harmonicity:1.5,voice0:R(F($e.getDefaults(),Object.keys(We.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}}),voice1:R(F($e.getDefaults(),Object.keys(We.getDefaults())),{filterEnvelope:{attack:.01,decay:0,sustain:1,release:.5},envelope:{attack:.01,decay:0,sustain:1,release:.5}})})}_triggerEnvelopeAttack(t,e){this.voice0._triggerEnvelopeAttack(t,e),this.voice1._triggerEnvelopeAttack(t,e)}_triggerEnvelopeRelease(t){return this.voice0._triggerEnvelopeRelease(t),this.voice1._triggerEnvelopeRelease(t),this}dispose(){return super.dispose(),this.voice0.dispose(),this.voice1.dispose(),this.frequency.dispose(),this.detune.dispose(),this._vibrato.dispose(),this.vibratoRate.dispose(),this._vibratoGain.dispose(),this.harmonicity.dispose(),this}}class Ke extends Ye{constructor(){super(q(Ke.getDefaults(),arguments)),this.name="FMSynth";const t=q(Ke.getDefaults(),arguments);this.modulationIndex=new fe({context:this.context,value:t.modulationIndex}),this.frequency.connect(this._carrier.frequency),this.frequency.chain(this.harmonicity,this._modulator.frequency),this.frequency.chain(this.modulationIndex,this._modulationNode),this.detune.fan(this._carrier.detune,this._modulator.detune),this._modulator.connect(this._modulationNode.gain),this._modulationNode.connect(this._carrier.frequency),this._carrier.connect(this.output)}static getDefaults(){return Object.assign(Ye.getDefaults(),{modulationIndex:10})}dispose(){return super.dispose(),this.modulationIndex.dispose(),this}}const tn=[1,1.483,1.932,2.546,2.63,3.897];class en extends We{constructor(){super(q(en.getDefaults(),arguments)),this.name="MetalSynth",this._oscillators=[],this._freqMultipliers=[];const t=q(en.getDefaults(),arguments);this.detune=new Rt({context:this.context,units:"cents",value:t.detune}),this.frequency=new Rt({context:this.context,units:"frequency"}),this._amplitude=new Mt({context:this.context,gain:0}).connect(this.output),this._highpass=new Xe({Q:0,context:this.context,type:"highpass"}).connect(this._amplitude);for(let e=0;ethis.onsilence(this):K,type:"square"});n.connect(this._highpass),this._oscillators[e]=n;const s=new fe({context:this.context,value:tn[e]});this._freqMultipliers[e]=s,this.frequency.chain(s,n.frequency),this.detune.connect(n.detune)}this._filterFreqScaler=new Te({context:this.context,max:7e3,min:this.toFrequency(t.resonance)}),this.envelope=new Le({attack:t.envelope.attack,attackCurve:"linear",context:this.context,decay:t.envelope.decay,release:t.envelope.release,sustain:0}),this.envelope.chain(this._filterFreqScaler,this._highpass.frequency),this.envelope.connect(this._amplitude.gain),this._octaves=t.octaves,this.octaves=t.octaves}static getDefaults(){return R(We.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{attack:.001,decay:1.4,release:.2}),harmonicity:5.1,modulationIndex:32,octaves:1.5,resonance:4e3})}_triggerEnvelopeAttack(t,e=1){return this.envelope.triggerAttack(t,e),this._oscillators.forEach(e=>e.start(t)),0===this.envelope.sustain&&this._oscillators.forEach(e=>{e.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay))}),this}_triggerEnvelopeRelease(t){return this.envelope.triggerRelease(t),this._oscillators.forEach(e=>e.stop(t+this.toSeconds(this.envelope.release))),this}getLevelAtTime(t){return t=this.toSeconds(t),this.envelope.getValueAtTime(t)}get modulationIndex(){return this._oscillators[0].modulationIndex.value}set modulationIndex(t){this._oscillators.forEach(e=>e.modulationIndex.value=t)}get harmonicity(){return this._oscillators[0].harmonicity.value}set harmonicity(t){this._oscillators.forEach(e=>e.harmonicity.value=t)}get resonance(){return this._filterFreqScaler.min}set resonance(t){this._filterFreqScaler.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._filterFreqScaler.max=this._filterFreqScaler.min*Math.pow(2,t)}dispose(){return super.dispose(),this._oscillators.forEach(t=>t.dispose()),this._freqMultipliers.forEach(t=>t.dispose()),this.frequency.dispose(),this.detune.dispose(),this._filterFreqScaler.dispose(),this._amplitude.dispose(),this.envelope.dispose(),this._highpass.dispose(),this}}class nn extends Ge{constructor(){super(q(nn.getDefaults(),arguments)),this.name="MembraneSynth",this.portamento=0;const t=q(nn.getDefaults(),arguments);this.pitchDecay=t.pitchDecay,this.octaves=t.octaves,$(this,["oscillator","envelope"])}static getDefaults(){return R(We.getDefaults(),Ge.getDefaults(),{envelope:{attack:.001,attackCurve:"exponential",decay:.4,release:1.4,sustain:.01},octaves:10,oscillator:{type:"sine"},pitchDecay:.05})}setNote(t,e){const n=this.toSeconds(e),s=this.toFrequency(t instanceof gt?t.toFrequency():t),i=s*this.octaves;return this.oscillator.frequency.setValueAtTime(i,n),this.oscillator.frequency.exponentialRampToValueAtTime(s,n+this.toSeconds(this.pitchDecay)),this}dispose(){return super.dispose(),this}}O([Ce(0)],nn.prototype,"octaves",void 0),O([ke(0)],nn.prototype,"pitchDecay",void 0);class sn extends Be{constructor(){super(q(sn.getDefaults(),arguments)),this.name="NoiseSynth";const t=q(sn.getDefaults(),arguments);this.noise=new ie(Object.assign({context:this.context},t.noise)),this.envelope=new Ue(Object.assign({context:this.context},t.envelope)),this.noise.chain(this.envelope,this.output)}static getDefaults(){return Object.assign(Be.getDefaults(),{envelope:Object.assign(F(Le.getDefaults(),Object.keys(Ct.getDefaults())),{decay:.1,sustain:0}),noise:Object.assign(F(ie.getDefaults(),Object.keys(ne.getDefaults())),{type:"white"})})}triggerAttack(t,e=1){return t=this.toSeconds(t),this.envelope.triggerAttack(t,e),this.noise.start(t),0===this.envelope.sustain&&this.noise.stop(t+this.toSeconds(this.envelope.attack)+this.toSeconds(this.envelope.decay)),this}triggerRelease(t){return t=this.toSeconds(t),this.envelope.triggerRelease(t),this.noise.stop(t+this.toSeconds(this.envelope.release)),this}sync(){return this._syncMethod("triggerAttack",0),this._syncMethod("triggerRelease",0),this}triggerAttackRelease(t,e,n=1){return e=this.toSeconds(e),t=this.toSeconds(t),this.triggerAttack(e,n),this.triggerRelease(e+t),this}dispose(){return super.dispose(),this.noise.dispose(),this.envelope.dispose(),this}}const on=new Set;function rn(t){on.add(t)}function an(t,e){const n=`registerProcessor("${t}", ${e})`;on.add(n)}class cn extends Ct{constructor(t){super(t),this.name="ToneAudioWorklet",this.workletOptions={},this.onprocessorerror=K;const e=URL.createObjectURL(new Blob([Array.from(on).join("\n")],{type:"text/javascript"})),n=this._audioWorkletName();this._dummyGain=this.context.createGain(),this._dummyParam=this._dummyGain.gain,this.context.addAudioWorkletModule(e,n).then(()=>{this.disposed||(this._worklet=this.context.createAudioWorkletNode(n,this.workletOptions),this._worklet.onprocessorerror=this.onprocessorerror.bind(this),this.onReady(this._worklet))})}dispose(){return super.dispose(),this._dummyGain.disconnect(),this._worklet&&(this._worklet.port.postMessage("dispose"),this._worklet.disconnect()),this}}rn('\n\t/**\n\t * The base AudioWorkletProcessor for use in Tone.js. Works with the [[ToneAudioWorklet]]. \n\t */\n\tclass ToneAudioWorkletProcessor extends AudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\t\n\t\t\tsuper(options);\n\t\t\t/**\n\t\t\t * If the processor was disposed or not. Keep alive until it\'s disposed.\n\t\t\t */\n\t\t\tthis.disposed = false;\n\t\t   \t/** \n\t\t\t * The number of samples in the processing block\n\t\t\t */\n\t\t\tthis.blockSize = 128;\n\t\t\t/**\n\t\t\t * the sample rate\n\t\t\t */\n\t\t\tthis.sampleRate = sampleRate;\n\n\t\t\tthis.port.onmessage = (event) => {\n\t\t\t\t// when it receives a dispose \n\t\t\t\tif (event.data === "dispose") {\n\t\t\t\t\tthis.disposed = true;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n');rn("\n\t/**\n\t * Abstract class for a single input/output processor. \n\t * has a 'generate' function which processes one sample at a time\n\t */\n\tclass SingleIOProcessor extends ToneAudioWorkletProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(Object.assign(options, {\n\t\t\t\tnumberOfInputs: 1,\n\t\t\t\tnumberOfOutputs: 1\n\t\t\t}));\n\t\t\t/**\n\t\t\t * Holds the name of the parameter and a single value of that\n\t\t\t * parameter at the current sample\n\t\t\t * @type { [name: string]: number }\n\t\t\t */\n\t\t\tthis.params = {}\n\t\t}\n\n\t\t/**\n\t\t * Generate an output sample from the input sample and parameters\n\t\t * @abstract\n\t\t * @param input number\n\t\t * @param channel number\n\t\t * @param parameters { [name: string]: number }\n\t\t * @returns number\n\t\t */\n\t\tgenerate(){}\n\n\t\t/**\n\t\t * Update the private params object with the \n\t\t * values of the parameters at the given index\n\t\t * @param parameters { [name: string]: Float32Array },\n\t\t * @param index number\n\t\t */\n\t\tupdateParams(parameters, index) {\n\t\t\tfor (const paramName in parameters) {\n\t\t\t\tconst param = parameters[paramName];\n\t\t\t\tif (param.length > 1) {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][index];\n\t\t\t\t} else {\n\t\t\t\t\tthis.params[paramName] = parameters[paramName][0];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Process a single frame of the audio\n\t\t * @param inputs Float32Array[][]\n\t\t * @param outputs Float32Array[][]\n\t\t */\n\t\tprocess(inputs, outputs, parameters) {\n\t\t\tconst input = inputs[0];\n\t\t\tconst output = outputs[0];\n\t\t\t// get the parameter values\n\t\t\tconst channelCount = Math.max(input && input.length || 0, output.length);\n\t\t\tfor (let sample = 0; sample < this.blockSize; sample++) {\n\t\t\t\tthis.updateParams(parameters, sample);\n\t\t\t\tfor (let channel = 0; channel < channelCount; channel++) {\n\t\t\t\t\tconst inputSample = input && input.length ? input[channel][sample] : 0;\n\t\t\t\t\toutput[channel][sample] = this.generate(inputSample, channel, this.params);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !this.disposed;\n\t\t}\n\t};\n");rn("\n\t/**\n\t * A multichannel buffer for use within an AudioWorkletProcessor as a delay line\n\t */\n\tclass DelayLine {\n\t\t\n\t\tconstructor(size, channels) {\n\t\t\tthis.buffer = [];\n\t\t\tthis.writeHead = []\n\t\t\tthis.size = size;\n\n\t\t\t// create the empty channels\n\t\t\tfor (let i = 0; i < channels; i++) {\n\t\t\t\tthis.buffer[i] = new Float32Array(this.size);\n\t\t\t\tthis.writeHead[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Push a value onto the end\n\t\t * @param channel number\n\t\t * @param value number\n\t\t */\n\t\tpush(channel, value) {\n\t\t\tthis.writeHead[channel] += 1;\n\t\t\tif (this.writeHead[channel] > this.size) {\n\t\t\t\tthis.writeHead[channel] = 0;\n\t\t\t}\n\t\t\tthis.buffer[channel][this.writeHead[channel]] = value;\n\t\t}\n\n\t\t/**\n\t\t * Get the recorded value of the channel given the delay\n\t\t * @param channel number\n\t\t * @param delay number delay samples\n\t\t */\n\t\tget(channel, delay) {\n\t\t\tlet readHead = this.writeHead[channel] - Math.floor(delay);\n\t\t\tif (readHead < 0) {\n\t\t\t\treadHead += this.size;\n\t\t\t}\n\t\t\treturn this.buffer[channel][readHead];\n\t\t}\n\t}\n");an("feedback-comb-filter",'\n\tclass FeedbackCombFilterWorklet extends SingleIOProcessor {\n\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tthis.delayLine = new DelayLine(this.sampleRate, options.channelCount || 2);\n\t\t}\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: "delayTime",\n\t\t\t\tdefaultValue: 0.1,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 1,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}, {\n\t\t\t\tname: "feedback",\n\t\t\t\tdefaultValue: 0.5,\n\t\t\t\tminValue: 0,\n\t\t\t\tmaxValue: 0.9999,\n\t\t\t\tautomationRate: "k-rate"\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, channel, parameters) {\n\t\t\tconst delayedSample = this.delayLine.get(channel, parameters.delayTime * this.sampleRate);\n\t\t\tthis.delayLine.push(channel, input + delayedSample * parameters.feedback);\n\t\t\treturn delayedSample;\n\t\t}\n\t}\n');class un extends cn{constructor(){super(q(un.getDefaults(),arguments,["delayTime","resonance"])),this.name="FeedbackCombFilter";const t=q(un.getDefaults(),arguments,["delayTime","resonance"]);this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.delayTime=new St({context:this.context,value:t.delayTime,units:"time",minValue:0,maxValue:1,param:this._dummyParam,swappable:!0}),this.resonance=new St({context:this.context,value:t.resonance,units:"normalRange",param:this._dummyParam,swappable:!0}),$(this,["resonance","delayTime"])}_audioWorkletName(){return"feedback-comb-filter"}static getDefaults(){return Object.assign(Ct.getDefaults(),{delayTime:.1,resonance:.5})}onReady(t){kt(this.input,t,this.output);const e=t.parameters.get("delayTime");this.delayTime.setParam(e);const n=t.parameters.get("feedback");this.resonance.setParam(n)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.delayTime.dispose(),this.resonance.dispose(),this}}class hn extends Ct{constructor(){super(q(hn.getDefaults(),arguments,["frequency","type"])),this.name="OnePoleFilter";const t=q(hn.getDefaults(),arguments,["frequency","type"]);this._frequency=t.frequency,this._type=t.type,this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this._createFilter()}static getDefaults(){return Object.assign(Ct.getDefaults(),{frequency:880,type:"lowpass"})}_createFilter(){const t=this._filter,e=this.toFrequency(this._frequency),n=1/(2*Math.PI*e);if("lowpass"===this._type){const t=1/(n*this.context.sampleRate),e=t-1;this._filter=this.context.createIIRFilter([t,0],[1,e])}else{const t=1/(n*this.context.sampleRate)-1;this._filter=this.context.createIIRFilter([1,-1],[1,t])}this.input.chain(this._filter,this.output),t&&this.context.setTimeout(()=>{this.disposed||(this.input.disconnect(t),t.disconnect())},this.blockTime)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._createFilter()}get type(){return this._type}set type(t){this._type=t,this._createFilter()}getFrequencyResponse(t=128){const e=new Float32Array(t);for(let n=0;ne.voice===t);this._activeVoices.splice(e,1)}_getNextAvailableVoice(){if(this._availableVoices.length)return this._availableVoices.shift();if(this._voices.lengthMath.ceil(this._averageActiveVoices+1)){const t=this._availableVoices.shift(),e=this._voices.indexOf(t);this._voices.splice(e,1),this.context.isOffline||t.dispose()}}_triggerAttack(t,e,n){t.forEach(t=>{const s=new Jt(this.context,t).toMidi(),i=this._getNextAvailableVoice();i&&(i.triggerAttack(t,e,n),this._activeVoices.push({midi:s,voice:i,released:!1}),this.log("triggerAttack",t,e))})}_triggerRelease(t,e){t.forEach(t=>{const n=new Jt(this.context,t).toMidi(),s=this._activeVoices.find(({midi:t,released:e})=>t===n&&!e);s&&(s.voice.triggerRelease(e),s.released=!0,this.log("triggerRelease",t,e))})}_scheduleEvent(t,e,n,s){r(!this.disposed,"Synth was already disposed"),n<=this.now()?"attack"===t?this._triggerAttack(e,n,s):this._triggerRelease(e,n):this.context.setTimeout(()=>{this._scheduleEvent(t,e,n,s)},n-this.now())}triggerAttack(t,e,n){Array.isArray(t)||(t=[t]);const s=this.toSeconds(e);return this._scheduleEvent("attack",t,s,n),this}triggerRelease(t,e){Array.isArray(t)||(t=[t]);const n=this.toSeconds(e);return this._scheduleEvent("release",t,n),this}triggerAttackRelease(t,e,n,s){const i=this.toSeconds(n);if(this.triggerAttack(t,i,s),y(e)){r(y(t),"If the duration is an array, the notes must also be an array"),t=t;for(let n=0;n0,"The duration must be greater than 0"),this.triggerRelease(t[n],i+o)}}else{const n=this.toSeconds(e);r(n>0,"The duration must be greater than 0"),this.triggerRelease(t,i+n)}return this}sync(){return this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this}set(t){const e=F(t,["onsilence","context"]);return this.options=R(this.options,e),this._voices.forEach(t=>t.set(e)),this._dummyVoice.set(e),this}get(){return this._dummyVoice.get()}releaseAll(t){const e=this.toSeconds(t);return this._activeVoices.forEach(({voice:t})=>{t.triggerRelease(e)}),this}dispose(){return super.dispose(),this._dummyVoice.dispose(),this._voices.forEach(t=>t.dispose()),this._activeVoices=[],this._availableVoices=[],this.context.clearInterval(this._gcTimeout),this}}class fn extends Be{constructor(){super(q(fn.getDefaults(),arguments,["urls","onload","baseUrl"],"urls")),this.name="Sampler",this._activeSources=new Map;const t=q(fn.getDefaults(),arguments,["urls","onload","baseUrl"],"urls"),e={};Object.keys(t.urls).forEach(n=>{const s=parseInt(n,10);if(r(x(n)||m(s)&&isFinite(s),"url key is neither a note or midi pitch: "+n),x(n)){const s=new gt(this.context,n).toMidi();e[s]=t.urls[n]}else m(s)&&isFinite(s)&&(e[s]=t.urls[s])}),this._buffers=new $t({urls:e,onload:t.onload,baseUrl:t.baseUrl,onerror:t.onerror}),this.attack=t.attack,this.release=t.release,this.curve=t.curve,this._buffers.loaded&&Promise.resolve().then(t.onload)}static getDefaults(){return Object.assign(Be.getDefaults(),{attack:0,baseUrl:"",curve:"exponential",onload:K,onerror:K,release:.1,urls:{}})}_findClosest(t){let e=0;for(;e<96;){if(this._buffers.has(t+e))return-e;if(this._buffers.has(t-e))return e;e++}throw new Error("No available buffers for note: "+t)}triggerAttack(t,e,n=1){return this.log("triggerAttack",t,e,n),Array.isArray(t)||(t=[t]),t.forEach(t=>{const s=dt(new gt(this.context,t).toFrequency()),i=Math.round(s),o=s-i,r=this._findClosest(i),a=i-r,c=this._buffers.get(a),u=ut(r+o),h=new se({url:c,context:this.context,curve:this.curve,fadeIn:this.attack,fadeOut:this.release,playbackRate:u}).connect(this.output);h.start(e,0,c.duration/u,n),y(this._activeSources.get(i))||this._activeSources.set(i,[]),this._activeSources.get(i).push(h),h.onended=()=>{if(this._activeSources&&this._activeSources.has(i)){const t=this._activeSources.get(i),e=t.indexOf(h);-1!==e&&t.splice(e,1)}}}),this}triggerRelease(t,e){return this.log("triggerRelease",t,e),Array.isArray(t)||(t=[t]),t.forEach(t=>{const n=new gt(this.context,t).toMidi();if(this._activeSources.has(n)&&this._activeSources.get(n).length){const t=this._activeSources.get(n);e=this.toSeconds(e),t.forEach(t=>{t.stop(e)}),this._activeSources.set(n,[])}}),this}releaseAll(t){const e=this.toSeconds(t);return this._activeSources.forEach(t=>{for(;t.length;){t.shift().stop(e)}}),this}sync(){return this._syncMethod("triggerAttack",1),this._syncMethod("triggerRelease",1),this}triggerAttackRelease(t,e,n,s=1){const i=this.toSeconds(n);return this.triggerAttack(t,i,s),y(e)?(r(y(t),"notes must be an array when duration is array"),t.forEach((t,n)=>{const s=e[Math.min(n,e.length-1)];this.triggerRelease(t,i+this.toSeconds(s))})):this.triggerRelease(t,i+this.toSeconds(e)),this}add(t,e,n){if(r(x(t)||isFinite(t),"note must be a pitch or midi: "+t),x(t)){const s=new gt(this.context,t).toMidi();this._buffers.add(s,e,n)}else this._buffers.add(t,e,n);return this}get loaded(){return this._buffers.loaded}dispose(){return super.dispose(),this._buffers.dispose(),this._activeSources.forEach(t=>{t.forEach(t=>t.dispose())}),this._activeSources.clear(),this}}O([ke(0)],fn.prototype,"attack",void 0),O([ke(0)],fn.prototype,"release",void 0);class _n extends Tt{constructor(){super(q(_n.getDefaults(),arguments,["callback","value"])),this.name="ToneEvent",this._state=new Ot("stopped"),this._startOffset=0;const t=q(_n.getDefaults(),arguments,["callback","value"]);this._loop=t.loop,this.callback=t.callback,this.value=t.value,this._loopStart=this.toTicks(t.loopStart),this._loopEnd=this.toTicks(t.loopEnd),this._playbackRate=t.playbackRate,this._probability=t.probability,this._humanize=t.humanize,this.mute=t.mute,this._playbackRate=t.playbackRate,this._state.increasing=!0,this._rescheduleEvents()}static getDefaults(){return Object.assign(Tt.getDefaults(),{callback:K,humanize:!1,loop:!1,loopEnd:"1m",loopStart:0,mute:!1,playbackRate:1,probability:1,value:null})}_rescheduleEvents(t=-1){this._state.forEachFrom(t,t=>{let e;if("started"===t.state){-1!==t.id&&this.context.transport.clear(t.id);const n=t.time+Math.round(this.startOffset/this._playbackRate);if(!0===this._loop||m(this._loop)&&this._loop>1){e=1/0,m(this._loop)&&(e=this._loop*this._getLoopDuration());const s=this._state.getAfter(n);null!==s&&(e=Math.min(e,s.time-n)),e!==1/0&&(this._state.setStateAtTime("stopped",n+e+1,{id:-1}),e=new Lt(this.context,e));const i=new Lt(this.context,this._getLoopDuration());t.id=this.context.transport.scheduleRepeat(this._tick.bind(this),i,new Lt(this.context,n),e)}else t.id=this.context.transport.schedule(this._tick.bind(this),new Lt(this.context,n))}})}get state(){return this._state.getValueAtTime(this.context.transport.ticks)}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t}get probability(){return this._probability}set probability(t){this._probability=t}get humanize(){return this._humanize}set humanize(t){this._humanize=t}start(t){const e=this.toTicks(t);return"stopped"===this._state.getValueAtTime(e)&&(this._state.add({id:-1,state:"started",time:e}),this._rescheduleEvents(e)),this}stop(t){this.cancel(t);const e=this.toTicks(t);if("started"===this._state.getValueAtTime(e)){this._state.setStateAtTime("stopped",e,{id:-1});const t=this._state.getBefore(e);let n=e;null!==t&&(n=t.time),this._rescheduleEvents(n)}return this}cancel(t){t=I(t,-1/0);const e=this.toTicks(t);return this._state.forEachFrom(e,t=>{this.context.transport.clear(t.id)}),this._state.cancel(e),this}_tick(t){const e=this.context.transport.getTicksAtTime(t);if(!this.mute&&"started"===this._state.getValueAtTime(e)){if(this.probability<1&&Math.random()>this.probability)return;if(this.humanize){let e=.02;v(this.humanize)||(e=this.toSeconds(this.humanize)),t+=(2*Math.random()-1)*e}this.callback(t,this.value)}}_getLoopDuration(){return Math.round((this._loopEnd-this._loopStart)/this._playbackRate)}get loop(){return this._loop}set loop(t){this._loop=t,this._rescheduleEvents()}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._rescheduleEvents()}get loopEnd(){return new Lt(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._rescheduleEvents()}get loopStart(){return new Lt(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._rescheduleEvents()}get progress(){if(this._loop){const t=this.context.transport.ticks,e=this._state.get(t);if(null!==e&&"started"===e.state){const n=this._getLoopDuration();return(t-e.time)%n/n}return 0}return 0}dispose(){return super.dispose(),this.cancel(),this._state.dispose(),this}}class mn extends Tt{constructor(){super(q(mn.getDefaults(),arguments,["callback","interval"])),this.name="Loop";const t=q(mn.getDefaults(),arguments,["callback","interval"]);this._event=new _n({context:this.context,callback:this._tick.bind(this),loop:!0,loopEnd:t.interval,playbackRate:t.playbackRate,probability:t.probability}),this.callback=t.callback,this.iterations=t.iterations}static getDefaults(){return Object.assign(Tt.getDefaults(),{interval:"4n",callback:K,playbackRate:1,iterations:1/0,probability:1,mute:!1,humanize:!1})}start(t){return this._event.start(t),this}stop(t){return this._event.stop(t),this}cancel(t){return this._event.cancel(t),this}_tick(t){this.callback(t)}get state(){return this._event.state}get progress(){return this._event.progress}get interval(){return this._event.loopEnd}set interval(t){this._event.loopEnd=t}get playbackRate(){return this._event.playbackRate}set playbackRate(t){this._event.playbackRate=t}get humanize(){return this._event.humanize}set humanize(t){this._event.humanize=t}get probability(){return this._event.probability}set probability(t){this._event.probability=t}get mute(){return this._event.mute}set mute(t){this._event.mute=t}get iterations(){return!0===this._event.loop?1/0:this._event.loop}set iterations(t){this._event.loop=t===1/0||t}dispose(){return super.dispose(),this._event.dispose(),this}}class gn extends _n{constructor(){super(q(gn.getDefaults(),arguments,["callback","events"])),this.name="Part",this._state=new Ot("stopped"),this._events=new Set;const t=q(gn.getDefaults(),arguments,["callback","events"]);this._state.increasing=!0,t.events.forEach(t=>{y(t)?this.add(t[0],t[1]):this.add(t)})}static getDefaults(){return Object.assign(_n.getDefaults(),{events:[]})}start(t,e){const n=this.toTicks(t);if("started"!==this._state.getValueAtTime(n)){e=I(e,this._loop?this._loopStart:0),e=this._loop?I(e,this._loopStart):I(e,0);const t=this.toTicks(e);this._state.add({id:-1,offset:t,state:"started",time:n}),this._forEach(e=>{this._startNote(e,n,t)})}return this}_startNote(t,e,n){e-=n,this._loop?t.startOffset>=this._loopStart&&t.startOffset=n&&(t.loop=!1,t.start(new Lt(this.context,e))):t.startOffset>=n&&t.start(new Lt(this.context,e))}get startOffset(){return this._startOffset}set startOffset(t){this._startOffset=t,this._forEach(t=>{t.startOffset+=this._startOffset})}stop(t){const e=this.toTicks(t);return this._state.cancel(e),this._state.setStateAtTime("stopped",e),this._forEach(e=>{e.stop(t)}),this}at(t,e){const n=new xt(this.context,t).toTicks(),s=new Lt(this.context,1).toSeconds(),i=this._events.values();let o=i.next();for(;!o.done;){const t=o.value;if(Math.abs(n-t.startOffset){"started"===e.state?this._startNote(t,e.time,e.offset):t.stop(new Lt(this.context,e.time))})}remove(t,e){return g(t)&&t.hasOwnProperty("time")&&(t=(e=t).time),t=this.toTicks(t),this._events.forEach(n=>{n.startOffset===t&&(p(e)||f(e)&&n.value===e)&&(this._events.delete(n),n.dispose())}),this}clear(){return this._forEach(t=>t.dispose()),this._events.clear(),this}cancel(t){return this._forEach(e=>e.cancel(t)),this._state.cancel(this.toTicks(t)),this}_forEach(t){return this._events&&this._events.forEach(e=>{e instanceof gn?e._forEach(t):t(e)}),this}_setAll(t,e){this._forEach(n=>{n[t]=e})}_tick(t,e){this.mute||this.callback(t,e)}_testLoopBoundries(t){this._loop&&(t.startOffset=this._loopEnd)?t.cancel(0):"stopped"===t.state&&this._restartEvent(t)}get probability(){return this._probability}set probability(t){this._probability=t,this._setAll("probability",t)}get humanize(){return this._humanize}set humanize(t){this._humanize=t,this._setAll("humanize",t)}get loop(){return this._loop}set loop(t){this._loop=t,this._forEach(e=>{e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.loop=t,this._testLoopBoundries(e)})}get loopEnd(){return new Lt(this.context,this._loopEnd).toSeconds()}set loopEnd(t){this._loopEnd=this.toTicks(t),this._loop&&this._forEach(e=>{e.loopEnd=t,this._testLoopBoundries(e)})}get loopStart(){return new Lt(this.context,this._loopStart).toSeconds()}set loopStart(t){this._loopStart=this.toTicks(t),this._loop&&this._forEach(t=>{t.loopStart=this.loopStart,this._testLoopBoundries(t)})}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._setAll("playbackRate",t)}get length(){return this._events.size}dispose(){return super.dispose(),this.clear(),this}}function*vn(t){let e=0;for(;e=0;)e=xn(e,t),yield t[e],e--}function*bn(t,e){for(;;)yield*e(t)}function xn(t,e){return B(t,0,e.length-1)}function*wn(t,e){let n=e?0:t.length-1;for(;;)n=xn(n,t),yield t[n],e?(n++,n>=t.length-1&&(e=!1)):(n--,n<=0&&(e=!0))}function*Tn(t){let e=0,n=0;for(;e=0;)e=xn(e,t),yield t[e],n++,e+=n%2?-2:1}function*Sn(t){const e=[];for(let n=0;n0;){const n=xn(e.splice(Math.floor(e.length*Math.random()),1)[0],t);yield t[n]}}function*Cn(t,e="up",n=0){switch(r(t.length>0,"The array must have more than one value in it"),e){case"up":yield*bn(t,vn);case"down":yield*bn(t,yn);case"upDown":yield*wn(t,!0);case"downUp":yield*wn(t,!1);case"alternateUp":yield*bn(t,Tn);case"alternateDown":yield*bn(t,On);case"random":yield*function*(t){for(;;){const e=Math.floor(Math.random()*t.length);yield t[e]}}(t);case"randomOnce":yield*bn(t,Sn);case"randomWalk":yield*function*(t){let e=Math.floor(Math.random()*t.length);for(;;)0===e?e++:e===t.length-1||Math.random()<.5?e--:e++,yield t[e]}(t)}}class kn extends mn{constructor(){super(q(kn.getDefaults(),arguments,["callback","values","pattern"])),this.name="Pattern";const t=q(kn.getDefaults(),arguments,["callback","values","pattern"]);this.callback=t.callback,this._values=t.values,this._pattern=Cn(t.values,t.pattern),this._type=t.pattern}static getDefaults(){return Object.assign(mn.getDefaults(),{pattern:"up",values:[],callback:K})}_tick(t){const e=this._pattern.next();this._value=e.value,this.callback(t,this._value)}get values(){return this._values}set values(t){this._values=t,this.pattern=this._type}get value(){return this._value}get pattern(){return this._type}set pattern(t){this._type=t,this._pattern=Cn(this._values,this._type)}}class An extends _n{constructor(){super(q(An.getDefaults(),arguments,["callback","events","subdivision"])),this.name="Sequence",this._part=new gn({callback:this._seqCallback.bind(this),context:this.context}),this._events=[],this._eventsArray=[];const t=q(An.getDefaults(),arguments,["callback","events","subdivision"]);this._subdivision=this.toTicks(t.subdivision),this.events=t.events,this.loop=t.loop,this.loopStart=t.loopStart,this.loopEnd=t.loopEnd,this.playbackRate=t.playbackRate,this.probability=t.probability,this.humanize=t.humanize,this.mute=t.mute,this.playbackRate=t.playbackRate}static getDefaults(){return Object.assign(F(_n.getDefaults(),["value"]),{events:[],loop:!0,loopEnd:0,loopStart:0,subdivision:"8n"})}_seqCallback(t,e){null!==e&&this.callback(t,e)}get events(){return this._events}set events(t){this.clear(),this._eventsArray=t,this._events=this._createSequence(this._eventsArray),this._eventsUpdated()}start(t,e){return this._part.start(t,e?this._indexTime(e):e),this}stop(t){return this._part.stop(t),this}get subdivision(){return new Lt(this.context,this._subdivision).toSeconds()}_createSequence(t){return new Proxy(t,{get:(t,e)=>t[e],set:(t,e,n)=>(b(e)&&isFinite(parseInt(e,10))&&y(n)?t[e]=this._createSequence(n):t[e]=n,this._eventsUpdated(),!0)})}_eventsUpdated(){this._part.clear(),this._rescheduleSequence(this._eventsArray,this._subdivision,this.startOffset),this.loopEnd=this.loopEnd}_rescheduleSequence(t,e,n){t.forEach((t,s)=>{const i=s*e+n;if(y(t))this._rescheduleSequence(t,e/t.length,i);else{const e=new Lt(this.context,i,"i").toSeconds();this._part.add(e,t)}})}_indexTime(t){return new Lt(this.context,t*this._subdivision+this.startOffset).toSeconds()}clear(){return this._part.clear(),this}dispose(){return super.dispose(),this._part.dispose(),this}get loop(){return this._part.loop}set loop(t){this._part.loop=t}get loopStart(){return this._loopStart}set loopStart(t){this._loopStart=t,this._part.loopStart=this._indexTime(t)}get loopEnd(){return this._loopEnd}set loopEnd(t){this._loopEnd=t,this._part.loopEnd=0===t?this._indexTime(this._eventsArray.length):this._indexTime(t)}get startOffset(){return this._part.startOffset}set startOffset(t){this._part.startOffset=t}get playbackRate(){return this._part.playbackRate}set playbackRate(t){this._part.playbackRate=t}get probability(){return this._part.probability}set probability(t){this._part.probability=t}get progress(){return this._part.progress}get humanize(){return this._part.humanize}set humanize(t){this._part.humanize=t}get length(){return this._part.length}}class Dn extends Ct{constructor(){super(Object.assign(q(Dn.getDefaults(),arguments,["fade"]))),this.name="CrossFade",this._panner=this.context.createStereoPanner(),this._split=this.context.createChannelSplitter(2),this._g2a=new Ee({context:this.context}),this.a=new Mt({context:this.context,gain:0}),this.b=new Mt({context:this.context,gain:0}),this.output=new Mt({context:this.context}),this._internalChannels=[this.a,this.b];const t=q(Dn.getDefaults(),arguments,["fade"]);this.fade=new Rt({context:this.context,units:"normalRange",value:t.fade}),$(this,"fade"),this.context.getConstant(1).connect(this._panner),this._panner.connect(this._split),this._panner.channelCount=1,this._panner.channelCountMode="explicit",At(this._split,this.a.gain,0),At(this._split,this.b.gain,1),this.fade.chain(this._g2a,this._panner.pan),this.a.connect(this.output),this.b.connect(this.output)}static getDefaults(){return Object.assign(Ct.getDefaults(),{fade:.5})}dispose(){return super.dispose(),this.a.dispose(),this.b.dispose(),this.output.dispose(),this.fade.dispose(),this._g2a.dispose(),this._panner.disconnect(),this._split.disconnect(),this}}class Mn extends Ct{constructor(t){super(t),this.name="Effect",this._dryWet=new Dn({context:this.context}),this.wet=this._dryWet.fade,this.effectSend=new Mt({context:this.context}),this.effectReturn=new Mt({context:this.context}),this.input=new Mt({context:this.context}),this.output=this._dryWet,this.input.fan(this._dryWet.a,this.effectSend),this.effectReturn.connect(this._dryWet.b),this.wet.setValueAtTime(t.wet,0),this._internalChannels=[this.effectReturn,this.effectSend],$(this,"wet")}static getDefaults(){return Object.assign(Ct.getDefaults(),{wet:1})}connectEffect(t){return this._internalChannels.push(t),this.effectSend.chain(t,this.effectReturn),this}dispose(){return super.dispose(),this._dryWet.dispose(),this.effectSend.dispose(),this.effectReturn.dispose(),this.wet.dispose(),this}}class jn extends Mn{constructor(t){super(t),this.name="LFOEffect",this._lfo=new Se({context:this.context,frequency:t.frequency,amplitude:t.depth}),this.depth=this._lfo.amplitude,this.frequency=this._lfo.frequency,this.type=t.type,$(this,["frequency","depth"])}static getDefaults(){return Object.assign(Mn.getDefaults(),{frequency:1,type:"sine",depth:1})}start(t){return this._lfo.start(t),this}stop(t){return this._lfo.stop(t),this}sync(){return this._lfo.sync(),this}unsync(){return this._lfo.unsync(),this}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class En extends jn{constructor(){super(q(En.getDefaults(),arguments,["frequency","baseFrequency","octaves"])),this.name="AutoFilter";const t=q(En.getDefaults(),arguments,["frequency","baseFrequency","octaves"]);this.filter=new Xe(Object.assign(t.filter,{context:this.context})),this.connectEffect(this.filter),this._lfo.connect(this.filter.frequency),this.octaves=t.octaves,this.baseFrequency=t.baseFrequency}static getDefaults(){return Object.assign(jn.getDefaults(),{baseFrequency:200,octaves:2.6,filter:{type:"lowpass",rolloff:-12,Q:1}})}get baseFrequency(){return this._lfo.min}set baseFrequency(t){this._lfo.min=this.toFrequency(t),this.octaves=this._octaves}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._lfo.max=this._lfo.min*Math.pow(2,t)}dispose(){return super.dispose(),this.filter.dispose(),this}}class Rn extends Ct{constructor(){super(Object.assign(q(Rn.getDefaults(),arguments,["pan"]))),this.name="Panner",this._panner=this.context.createStereoPanner(),this.input=this._panner,this.output=this._panner;const t=q(Rn.getDefaults(),arguments,["pan"]);this.pan=new St({context:this.context,param:this._panner.pan,value:t.pan,minValue:-1,maxValue:1}),this._panner.channelCount=t.channelCount,this._panner.channelCountMode="explicit",$(this,"pan")}static getDefaults(){return Object.assign(Ct.getDefaults(),{pan:0,channelCount:1})}dispose(){return super.dispose(),this._panner.disconnect(),this.pan.dispose(),this}}class qn extends jn{constructor(){super(q(qn.getDefaults(),arguments,["frequency"])),this.name="AutoPanner";const t=q(qn.getDefaults(),arguments,["frequency"]);this._panner=new Rn({context:this.context,channelCount:t.channelCount}),this.connectEffect(this._panner),this._lfo.connect(this._panner.pan),this._lfo.min=-1,this._lfo.max=1}static getDefaults(){return Object.assign(jn.getDefaults(),{channelCount:1})}dispose(){return super.dispose(),this._panner.dispose(),this}}class In extends Ct{constructor(){super(q(In.getDefaults(),arguments,["smoothing"])),this.name="Follower";const t=q(In.getDefaults(),arguments,["smoothing"]);this._abs=this.input=new je({context:this.context}),this._lowpass=this.output=new hn({context:this.context,frequency:1/this.toSeconds(t.smoothing),type:"lowpass"}),this._abs.connect(this._lowpass),this._smoothing=t.smoothing}static getDefaults(){return Object.assign(Ct.getDefaults(),{smoothing:.05})}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this._lowpass.frequency=1/this.toSeconds(this.smoothing)}dispose(){return super.dispose(),this._abs.dispose(),this._lowpass.dispose(),this}}class Fn extends Mn{constructor(){super(q(Fn.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"])),this.name="AutoWah";const t=q(Fn.getDefaults(),arguments,["baseFrequency","octaves","sensitivity"]);this._follower=new In({context:this.context,smoothing:t.follower}),this._sweepRange=new Ne({context:this.context,min:0,max:1,exponent:.5}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this._inputBoost=new Mt({context:this.context}),this._bandpass=new Xe({context:this.context,rolloff:-48,frequency:0,Q:t.Q}),this._peaking=new Xe({context:this.context,type:"peaking"}),this._peaking.gain.value=t.gain,this.gain=this._peaking.gain,this.Q=this._bandpass.Q,this.effectSend.chain(this._inputBoost,this._follower,this._sweepRange),this._sweepRange.connect(this._bandpass.frequency),this._sweepRange.connect(this._peaking.frequency),this.effectSend.chain(this._bandpass,this._peaking,this.effectReturn),this._setSweepRange(),this.sensitivity=t.sensitivity,$(this,["gain","Q"])}static getDefaults(){return Object.assign(Mn.getDefaults(),{baseFrequency:100,octaves:6,sensitivity:0,Q:2,gain:2,follower:.2})}get octaves(){return this._octaves}set octaves(t){this._octaves=t,this._setSweepRange()}get follower(){return this._follower.smoothing}set follower(t){this._follower.smoothing=t}get baseFrequency(){return this._baseFrequency}set baseFrequency(t){this._baseFrequency=this.toFrequency(t),this._setSweepRange()}get sensitivity(){return ct(1/this._inputBoost.gain.value)}set sensitivity(t){this._inputBoost.gain.value=1/at(t)}_setSweepRange(){this._sweepRange.min=this._baseFrequency,this._sweepRange.max=Math.min(this._baseFrequency*Math.pow(2,this._octaves),this.context.sampleRate/2)}dispose(){return super.dispose(),this._follower.dispose(),this._sweepRange.dispose(),this._bandpass.dispose(),this._peaking.dispose(),this._inputBoost.dispose(),this}}an("bit-crusher","\n\tclass BitCrusherWorklet extends SingleIOProcessor {\n\n\t\tstatic get parameterDescriptors() {\n\t\t\treturn [{\n\t\t\t\tname: \"bits\",\n\t\t\t\tdefaultValue: 12,\n\t\t\t\tminValue: 1,\n\t\t\t\tmaxValue: 16,\n\t\t\t\tautomationRate: 'k-rate'\n\t\t\t}];\n\t\t}\n\n\t\tgenerate(input, _channel, parameters) {\n\t\t\tconst step = Math.pow(0.5, parameters.bits - 1);\n\t\t\tconst val = step * Math.floor(input / step + 0.5);\n\t\t\treturn val;\n\t\t}\n\t}\n");class Vn extends Mn{constructor(){super(q(Vn.getDefaults(),arguments,["bits"])),this.name="BitCrusher";const t=q(Vn.getDefaults(),arguments,["bits"]);this._bitCrusherWorklet=new Nn({context:this.context,bits:t.bits}),this.connectEffect(this._bitCrusherWorklet),this.bits=this._bitCrusherWorklet.bits}static getDefaults(){return Object.assign(Mn.getDefaults(),{bits:4})}dispose(){return super.dispose(),this._bitCrusherWorklet.dispose(),this}}class Nn extends cn{constructor(){super(q(Nn.getDefaults(),arguments)),this.name="BitCrusherWorklet";const t=q(Nn.getDefaults(),arguments);this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.bits=new St({context:this.context,value:t.bits,units:"positive",minValue:1,maxValue:16,param:this._dummyParam,swappable:!0})}static getDefaults(){return Object.assign(cn.getDefaults(),{bits:12})}_audioWorkletName(){return"bit-crusher"}onReady(t){kt(this.input,t,this.output);const e=t.parameters.get("bits");this.bits.setParam(e)}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.bits.dispose(),this}}class Pn extends Mn{constructor(){super(q(Pn.getDefaults(),arguments,["order"])),this.name="Chebyshev";const t=q(Pn.getDefaults(),arguments,["order"]);this._shaper=new de({context:this.context,length:4096}),this._order=t.order,this.connectEffect(this._shaper),this.order=t.order,this.oversample=t.oversample}static getDefaults(){return Object.assign(Mn.getDefaults(),{order:1,oversample:"none"})}_getCoefficient(t,e,n){return n.has(e)||(0===e?n.set(e,0):1===e?n.set(e,t):n.set(e,2*t*this._getCoefficient(t,e-1,n)-this._getCoefficient(t,e-2,n))),n.get(e)}get order(){return this._order}set order(t){this._order=t,this._shaper.setMap(e=>this._getCoefficient(e,t,new Map))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class Ln extends Ct{constructor(){super(q(Ln.getDefaults(),arguments,["channels"])),this.name="Split";const t=q(Ln.getDefaults(),arguments,["channels"]);this._splitter=this.input=this.output=this.context.createChannelSplitter(t.channels),this._internalChannels=[this._splitter]}static getDefaults(){return Object.assign(Ct.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._splitter.disconnect(),this}}class zn extends Ct{constructor(){super(q(zn.getDefaults(),arguments,["channels"])),this.name="Merge";const t=q(zn.getDefaults(),arguments,["channels"]);this._merger=this.output=this.input=this.context.createChannelMerger(t.channels)}static getDefaults(){return Object.assign(Ct.getDefaults(),{channels:2})}dispose(){return super.dispose(),this._merger.disconnect(),this}}class Bn extends Ct{constructor(t){super(t),this.name="StereoEffect",this.input=new Mt({context:this.context}),this.input.channelCount=2,this.input.channelCountMode="explicit",this._dryWet=this.output=new Dn({context:this.context,fade:t.wet}),this.wet=this._dryWet.fade,this._split=new Ln({context:this.context,channels:2}),this._merge=new zn({context:this.context,channels:2}),this.input.connect(this._split),this.input.connect(this._dryWet.a),this._merge.connect(this._dryWet.b),$(this,["wet"])}connectEffectLeft(...t){this._split.connect(t[0],0,0),kt(...t),At(t[t.length-1],this._merge,0,0)}connectEffectRight(...t){this._split.connect(t[0],1,0),kt(...t),At(t[t.length-1],this._merge,0,1)}static getDefaults(){return Object.assign(Ct.getDefaults(),{wet:1})}dispose(){return super.dispose(),this._dryWet.dispose(),this._split.dispose(),this._merge.dispose(),this}}class Wn extends Bn{constructor(t){super(t),this.feedback=new Rt({context:this.context,value:t.feedback,units:"normalRange"}),this._feedbackL=new Mt({context:this.context}),this._feedbackR=new Mt({context:this.context}),this._feedbackSplit=new Ln({context:this.context,channels:2}),this._feedbackMerge=new zn({context:this.context,channels:2}),this._merge.connect(this._feedbackSplit),this._feedbackMerge.connect(this._split),this._feedbackSplit.connect(this._feedbackL,0,0),this._feedbackL.connect(this._feedbackMerge,0,0),this._feedbackSplit.connect(this._feedbackR,1,0),this._feedbackR.connect(this._feedbackMerge,0,1),this.feedback.fan(this._feedbackL.gain,this._feedbackR.gain),$(this,["feedback"])}static getDefaults(){return Object.assign(Bn.getDefaults(),{feedback:.5})}dispose(){return super.dispose(),this.feedback.dispose(),this._feedbackL.dispose(),this._feedbackR.dispose(),this._feedbackSplit.dispose(),this._feedbackMerge.dispose(),this}}class Un extends Wn{constructor(){super(q(Un.getDefaults(),arguments,["frequency","delayTime","depth"])),this.name="Chorus";const t=q(Un.getDefaults(),arguments,["frequency","delayTime","depth"]);this._depth=t.depth,this._delayTime=t.delayTime/1e3,this._lfoL=new Se({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new Se({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._delayNodeL=new Qt({context:this.context}),this._delayNodeR=new Qt({context:this.context}),this.frequency=this._lfoL.frequency,$(this,["frequency"]),this._lfoL.frequency.connect(this._lfoR.frequency),this.connectEffectLeft(this._delayNodeL),this.connectEffectRight(this._delayNodeR),this._lfoL.connect(this._delayNodeL.delayTime),this._lfoR.connect(this._delayNodeR.delayTime),this.depth=this._depth,this.type=t.type,this.spread=t.spread}static getDefaults(){return Object.assign(Wn.getDefaults(),{frequency:1.5,delayTime:3.5,depth:.7,type:"sine",spread:180,feedback:0,wet:.5})}get depth(){return this._depth}set depth(t){this._depth=t;const e=this._delayTime*t;this._lfoL.min=Math.max(this._delayTime-e,0),this._lfoL.max=this._delayTime+e,this._lfoR.min=Math.max(this._delayTime-e,0),this._lfoR.max=this._delayTime+e}get delayTime(){return 1e3*this._delayTime}set delayTime(t){this._delayTime=t/1e3,this.depth=this._depth}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._delayNodeL.dispose(),this._delayNodeR.dispose(),this.frequency.dispose(),this}}class Gn extends Mn{constructor(){super(q(Gn.getDefaults(),arguments,["distortion"])),this.name="Distortion";const t=q(Gn.getDefaults(),arguments,["distortion"]);this._shaper=new de({context:this.context,length:4096}),this._distortion=t.distortion,this.connectEffect(this._shaper),this.distortion=t.distortion,this.oversample=t.oversample}static getDefaults(){return Object.assign(Mn.getDefaults(),{distortion:.4,oversample:"none"})}get distortion(){return this._distortion}set distortion(t){this._distortion=t;const e=100*t,n=Math.PI/180;this._shaper.setMap(t=>Math.abs(t)<.001?0:(3+e)*t*20*n/(Math.PI+e*Math.abs(t)))}get oversample(){return this._shaper.oversample}set oversample(t){this._shaper.oversample=t}dispose(){return super.dispose(),this._shaper.dispose(),this}}class Yn extends Mn{constructor(t){super(t),this.name="FeedbackEffect",this._feedbackGain=new Mt({context:this.context,gain:t.feedback,units:"normalRange"}),this.feedback=this._feedbackGain.gain,$(this,"feedback"),this.effectReturn.chain(this._feedbackGain,this.effectSend)}static getDefaults(){return Object.assign(Mn.getDefaults(),{feedback:.125})}dispose(){return super.dispose(),this._feedbackGain.dispose(),this.feedback.dispose(),this}}class Qn extends Yn{constructor(){super(q(Qn.getDefaults(),arguments,["delayTime","feedback"])),this.name="FeedbackDelay";const t=q(Qn.getDefaults(),arguments,["delayTime","feedback"]);this._delayNode=new Qt({context:this.context,delayTime:t.delayTime,maxDelay:t.maxDelay}),this.delayTime=this._delayNode.delayTime,this.connectEffect(this._delayNode),$(this,"delayTime")}static getDefaults(){return Object.assign(Yn.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._delayNode.dispose(),this.delayTime.dispose(),this}}class Zn extends Ct{constructor(t){super(t),this.name="PhaseShiftAllpass",this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this.offset90=new Mt({context:this.context});this._bank0=this._createAllPassFilterBank([.6923878,.9360654322959,.988229522686,.9987488452737]),this._bank1=this._createAllPassFilterBank([.4021921162426,.856171088242,.9722909545651,.9952884791278]),this._oneSampleDelay=this.context.createIIRFilter([0,1],[1,0]),kt(this.input,...this._bank0,this._oneSampleDelay,this.output),kt(this.input,...this._bank1,this.offset90)}_createAllPassFilterBank(t){return t.map(t=>{const e=[[t*t,0,-1],[1,0,-t*t]];return this.context.createIIRFilter(e[0],e[1])})}dispose(){return super.dispose(),this.input.dispose(),this.output.dispose(),this.offset90.dispose(),this._bank0.forEach(t=>t.disconnect()),this._bank1.forEach(t=>t.disconnect()),this._oneSampleDelay.disconnect(),this}}class Xn extends Mn{constructor(){super(q(Xn.getDefaults(),arguments,["frequency"])),this.name="FrequencyShifter";const t=q(Xn.getDefaults(),arguments,["frequency"]);this.frequency=new Rt({context:this.context,units:"frequency",value:t.frequency,minValue:-this.context.sampleRate/2,maxValue:this.context.sampleRate/2}),this._sine=new ue({context:this.context,type:"sine"}),this._cosine=new he({context:this.context,phase:-90,type:"sine"}),this._sineMultiply=new fe({context:this.context}),this._cosineMultiply=new fe({context:this.context}),this._negate=new Re({context:this.context}),this._add=new we({context:this.context}),this._phaseShifter=new Zn({context:this.context}),this.effectSend.connect(this._phaseShifter),this.frequency.fan(this._sine.frequency,this._cosine.frequency),this._phaseShifter.offset90.connect(this._cosineMultiply),this._cosine.connect(this._cosineMultiply.factor),this._phaseShifter.connect(this._sineMultiply),this._sine.connect(this._sineMultiply.factor),this._sineMultiply.connect(this._negate),this._cosineMultiply.connect(this._add),this._negate.connect(this._add.addend),this._add.connect(this.effectReturn);const e=this.immediate();this._sine.start(e),this._cosine.start(e)}static getDefaults(){return Object.assign(Mn.getDefaults(),{frequency:0})}dispose(){return super.dispose(),this.frequency.dispose(),this._add.dispose(),this._cosine.dispose(),this._cosineMultiply.dispose(),this._negate.dispose(),this._phaseShifter.dispose(),this._sine.dispose(),this._sineMultiply.dispose(),this}}const Hn=[1557/44100,1617/44100,1491/44100,1422/44100,1277/44100,1356/44100,1188/44100,1116/44100],$n=[225,556,441,341];class Jn extends Bn{constructor(){super(q(Jn.getDefaults(),arguments,["roomSize","dampening"])),this.name="Freeverb",this._combFilters=[],this._allpassFiltersL=[],this._allpassFiltersR=[];const t=q(Jn.getDefaults(),arguments,["roomSize","dampening"]);this.roomSize=new Rt({context:this.context,value:t.roomSize,units:"normalRange"}),this._allpassFiltersL=$n.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._allpassFiltersR=$n.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._combFilters=Hn.map((e,n)=>{const s=new ln({context:this.context,dampening:t.dampening,delayTime:e});return ne.dampening=t)}dispose(){return super.dispose(),this._allpassFiltersL.forEach(t=>t.disconnect()),this._allpassFiltersR.forEach(t=>t.disconnect()),this._combFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this}}const Kn=[.06748,.06404,.08212,.09004],ts=[.773,.802,.753,.733],es=[347,113,37];class ns extends Bn{constructor(){super(q(ns.getDefaults(),arguments,["roomSize"])),this.name="JCReverb",this._allpassFilters=[],this._feedbackCombFilters=[];const t=q(ns.getDefaults(),arguments,["roomSize"]);this.roomSize=new Rt({context:this.context,value:t.roomSize,units:"normalRange"}),this._scaleRoomSize=new Te({context:this.context,min:-.733,max:.197}),this._allpassFilters=es.map(t=>{const e=this.context.createBiquadFilter();return e.type="allpass",e.frequency.value=t,e}),this._feedbackCombFilters=Kn.map((t,e)=>{const n=new un({context:this.context,delayTime:t});return this._scaleRoomSize.connect(n.resonance),n.resonance.value=ts[e],et.disconnect()),this._feedbackCombFilters.forEach(t=>t.dispose()),this.roomSize.dispose(),this._scaleRoomSize.dispose(),this}}class ss extends Wn{constructor(t){super(t),this._feedbackL.disconnect(),this._feedbackL.connect(this._feedbackMerge,0,1),this._feedbackR.disconnect(),this._feedbackR.connect(this._feedbackMerge,0,0),$(this,["feedback"])}}class is extends ss{constructor(){super(q(is.getDefaults(),arguments,["delayTime","feedback"])),this.name="PingPongDelay";const t=q(is.getDefaults(),arguments,["delayTime","feedback"]);this._leftDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this._rightDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this._rightPreDelay=new Qt({context:this.context,maxDelay:t.maxDelay}),this.delayTime=new Rt({context:this.context,units:"time",value:t.delayTime}),this.connectEffectLeft(this._leftDelay),this.connectEffectRight(this._rightPreDelay,this._rightDelay),this.delayTime.fan(this._leftDelay.delayTime,this._rightDelay.delayTime,this._rightPreDelay.delayTime),this._feedbackL.disconnect(),this._feedbackL.connect(this._rightDelay),$(this,["delayTime"])}static getDefaults(){return Object.assign(ss.getDefaults(),{delayTime:.25,maxDelay:1})}dispose(){return super.dispose(),this._leftDelay.dispose(),this._rightDelay.dispose(),this._rightPreDelay.dispose(),this.delayTime.dispose(),this}}class os extends Yn{constructor(){super(q(os.getDefaults(),arguments,["pitch"])),this.name="PitchShift";const t=q(os.getDefaults(),arguments,["pitch"]);this._frequency=new Rt({context:this.context}),this._delayA=new Qt({maxDelay:1,context:this.context}),this._lfoA=new Se({context:this.context,min:0,max:.1,type:"sawtooth"}).connect(this._delayA.delayTime),this._delayB=new Qt({maxDelay:1,context:this.context}),this._lfoB=new Se({context:this.context,min:0,max:.1,type:"sawtooth",phase:180}).connect(this._delayB.delayTime),this._crossFade=new Dn({context:this.context}),this._crossFadeLFO=new Se({context:this.context,min:0,max:1,type:"triangle",phase:90}).connect(this._crossFade.fade),this._feedbackDelay=new Qt({delayTime:t.delayTime,context:this.context}),this.delayTime=this._feedbackDelay.delayTime,$(this,"delayTime"),this._pitch=t.pitch,this._windowSize=t.windowSize,this._delayA.connect(this._crossFade.a),this._delayB.connect(this._crossFade.b),this._frequency.fan(this._lfoA.frequency,this._lfoB.frequency,this._crossFadeLFO.frequency),this.effectSend.fan(this._delayA,this._delayB),this._crossFade.chain(this._feedbackDelay,this.effectReturn);const e=this.now();this._lfoA.start(e),this._lfoB.start(e),this._crossFadeLFO.start(e),this.windowSize=this._windowSize}static getDefaults(){return Object.assign(Yn.getDefaults(),{pitch:0,windowSize:.1,delayTime:0,feedback:0})}get pitch(){return this._pitch}set pitch(t){this._pitch=t;let e=0;t<0?(this._lfoA.min=0,this._lfoA.max=this._windowSize,this._lfoB.min=0,this._lfoB.max=this._windowSize,e=ut(t-1)+1):(this._lfoA.min=this._windowSize,this._lfoA.max=0,this._lfoB.min=this._windowSize,this._lfoB.max=0,e=ut(t)-1),this._frequency.value=e*(1.2/this._windowSize)}get windowSize(){return this._windowSize}set windowSize(t){this._windowSize=this.toSeconds(t),this.pitch=this._pitch}dispose(){return super.dispose(),this._frequency.dispose(),this._delayA.dispose(),this._delayB.dispose(),this._lfoA.dispose(),this._lfoB.dispose(),this._crossFade.dispose(),this._crossFadeLFO.dispose(),this._feedbackDelay.dispose(),this}}class rs extends Bn{constructor(){super(q(rs.getDefaults(),arguments,["frequency","octaves","baseFrequency"])),this.name="Phaser";const t=q(rs.getDefaults(),arguments,["frequency","octaves","baseFrequency"]);this._lfoL=new Se({context:this.context,frequency:t.frequency,min:0,max:1}),this._lfoR=new Se({context:this.context,frequency:t.frequency,min:0,max:1,phase:180}),this._baseFrequency=this.toFrequency(t.baseFrequency),this._octaves=t.octaves,this.Q=new Rt({context:this.context,value:t.Q,units:"positive"}),this._filtersL=this._makeFilters(t.stages,this._lfoL),this._filtersR=this._makeFilters(t.stages,this._lfoR),this.frequency=this._lfoL.frequency,this.frequency.value=t.frequency,this.connectEffectLeft(...this._filtersL),this.connectEffectRight(...this._filtersR),this._lfoL.frequency.connect(this._lfoR.frequency),this.baseFrequency=t.baseFrequency,this.octaves=t.octaves,this._lfoL.start(),this._lfoR.start(),$(this,["frequency","Q"])}static getDefaults(){return Object.assign(Bn.getDefaults(),{frequency:.5,octaves:3,stages:10,Q:10,baseFrequency:350})}_makeFilters(t,e){const n=[];for(let s=0;st.disconnect()),this._filtersR.forEach(t=>t.disconnect()),this.frequency.dispose(),this}}class as extends Mn{constructor(){super(q(as.getDefaults(),arguments,["decay"])),this.name="Reverb",this._convolver=this.context.createConvolver(),this.ready=Promise.resolve();const t=q(as.getDefaults(),arguments,["decay"]);this._decay=t.decay,this._preDelay=t.preDelay,this.generate(),this.connectEffect(this._convolver)}static getDefaults(){return Object.assign(Mn.getDefaults(),{decay:1.5,preDelay:.01})}get decay(){return this._decay}set decay(t){a(t=this.toSeconds(t),.001),this._decay=t,this.generate()}get preDelay(){return this._preDelay}set preDelay(t){a(t=this.toSeconds(t),0),this._preDelay=t,this.generate()}generate(){return S(this,void 0,void 0,(function*(){const t=this.ready,e=new et(2,this._decay+this._preDelay,this.context.sampleRate),n=new ie({context:e}),s=new ie({context:e}),i=new zn({context:e});n.connect(i,0,0),s.connect(i,0,1);const o=new Mt({context:e}).toDestination();i.connect(o),n.start(0),s.start(0),o.gain.setValueAtTime(0,0),o.gain.setValueAtTime(1,this._preDelay),o.gain.exponentialApproachValueAtTime(0,this._preDelay,this.decay);const r=e.render();return this.ready=r.then(K),yield t,this._convolver.buffer=(yield r).get(),this}))}dispose(){return super.dispose(),this._convolver.disconnect(),this}}class cs extends Ct{constructor(){super(q(cs.getDefaults(),arguments)),this.name="MidSideSplit",this._split=this.input=new Ln({channels:2,context:this.context}),this._midAdd=new we({context:this.context}),this.mid=new fe({context:this.context,value:Math.SQRT1_2}),this._sideSubtract=new qe({context:this.context}),this.side=new fe({context:this.context,value:Math.SQRT1_2}),this._split.connect(this._midAdd,0),this._split.connect(this._midAdd.addend,1),this._split.connect(this._sideSubtract,0),this._split.connect(this._sideSubtract.subtrahend,1),this._midAdd.connect(this.mid),this._sideSubtract.connect(this.side)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midAdd.dispose(),this._sideSubtract.dispose(),this._split.dispose(),this}}class us extends Ct{constructor(){super(q(us.getDefaults(),arguments)),this.name="MidSideMerge",this.mid=new Mt({context:this.context}),this.side=new Mt({context:this.context}),this._left=new we({context:this.context}),this._leftMult=new fe({context:this.context,value:Math.SQRT1_2}),this._right=new qe({context:this.context}),this._rightMult=new fe({context:this.context,value:Math.SQRT1_2}),this._merge=this.output=new zn({context:this.context}),this.mid.fan(this._left),this.side.connect(this._left.addend),this.mid.connect(this._right),this.side.connect(this._right.subtrahend),this._left.connect(this._leftMult),this._right.connect(this._rightMult),this._leftMult.connect(this._merge,0,0),this._rightMult.connect(this._merge,0,1)}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._leftMult.dispose(),this._rightMult.dispose(),this._left.dispose(),this._right.dispose(),this}}class hs extends Mn{constructor(t){super(t),this.name="MidSideEffect",this._midSideMerge=new us({context:this.context}),this._midSideSplit=new cs({context:this.context}),this._midSend=this._midSideSplit.mid,this._sideSend=this._midSideSplit.side,this._midReturn=this._midSideMerge.mid,this._sideReturn=this._midSideMerge.side,this.effectSend.connect(this._midSideSplit),this._midSideMerge.connect(this.effectReturn)}connectEffectMid(...t){this._midSend.chain(...t,this._midReturn)}connectEffectSide(...t){this._sideSend.chain(...t,this._sideReturn)}dispose(){return super.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this._midSend.dispose(),this._sideSend.dispose(),this._midReturn.dispose(),this._sideReturn.dispose(),this}}class ls extends hs{constructor(){super(q(ls.getDefaults(),arguments,["width"])),this.name="StereoWidener";const t=q(ls.getDefaults(),arguments,["width"]);this.width=new Rt({context:this.context,value:t.width,units:"normalRange"}),$(this,["width"]),this._twoTimesWidthMid=new fe({context:this.context,value:2}),this._twoTimesWidthSide=new fe({context:this.context,value:2}),this._midMult=new fe({context:this.context}),this._twoTimesWidthMid.connect(this._midMult.factor),this.connectEffectMid(this._midMult),this._oneMinusWidth=new qe({context:this.context}),this._oneMinusWidth.connect(this._twoTimesWidthMid),At(this.context.getConstant(1),this._oneMinusWidth),this.width.connect(this._oneMinusWidth.subtrahend),this._sideMult=new fe({context:this.context}),this.width.connect(this._twoTimesWidthSide),this._twoTimesWidthSide.connect(this._sideMult.factor),this.connectEffectSide(this._sideMult)}static getDefaults(){return Object.assign(hs.getDefaults(),{width:.5})}dispose(){return super.dispose(),this.width.dispose(),this._midMult.dispose(),this._sideMult.dispose(),this._twoTimesWidthMid.dispose(),this._twoTimesWidthSide.dispose(),this._oneMinusWidth.dispose(),this}}class ds extends Bn{constructor(){super(q(ds.getDefaults(),arguments,["frequency","depth"])),this.name="Tremolo";const t=q(ds.getDefaults(),arguments,["frequency","depth"]);this._lfoL=new Se({context:this.context,type:t.type,min:1,max:0}),this._lfoR=new Se({context:this.context,type:t.type,min:1,max:0}),this._amplitudeL=new Mt({context:this.context}),this._amplitudeR=new Mt({context:this.context}),this.frequency=new Rt({context:this.context,value:t.frequency,units:"frequency"}),this.depth=new Rt({context:this.context,value:t.depth,units:"normalRange"}),$(this,["frequency","depth"]),this.connectEffectLeft(this._amplitudeL),this.connectEffectRight(this._amplitudeR),this._lfoL.connect(this._amplitudeL.gain),this._lfoR.connect(this._amplitudeR.gain),this.frequency.fan(this._lfoL.frequency,this._lfoR.frequency),this.depth.fan(this._lfoR.amplitude,this._lfoL.amplitude),this.spread=t.spread}static getDefaults(){return Object.assign(Bn.getDefaults(),{frequency:10,type:"sine",depth:.5,spread:180})}start(t){return this._lfoL.start(t),this._lfoR.start(t),this}stop(t){return this._lfoL.stop(t),this._lfoR.stop(t),this}sync(){return this._lfoL.sync(),this._lfoR.sync(),this.context.transport.syncSignal(this.frequency),this}unsync(){return this._lfoL.unsync(),this._lfoR.unsync(),this.context.transport.unsyncSignal(this.frequency),this}get type(){return this._lfoL.type}set type(t){this._lfoL.type=t,this._lfoR.type=t}get spread(){return this._lfoR.phase-this._lfoL.phase}set spread(t){this._lfoL.phase=90-t/2,this._lfoR.phase=t/2+90}dispose(){return super.dispose(),this._lfoL.dispose(),this._lfoR.dispose(),this._amplitudeL.dispose(),this._amplitudeR.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class ps extends Mn{constructor(){super(q(ps.getDefaults(),arguments,["frequency","depth"])),this.name="Vibrato";const t=q(ps.getDefaults(),arguments,["frequency","depth"]);this._delayNode=new Qt({context:this.context,delayTime:0,maxDelay:t.maxDelay}),this._lfo=new Se({context:this.context,type:t.type,min:0,max:t.maxDelay,frequency:t.frequency,phase:-90}).start().connect(this._delayNode.delayTime),this.frequency=this._lfo.frequency,this.depth=this._lfo.amplitude,this.depth.value=t.depth,$(this,["frequency","depth"]),this.effectSend.chain(this._delayNode,this.effectReturn)}static getDefaults(){return Object.assign(Mn.getDefaults(),{maxDelay:.005,frequency:5,depth:.1,type:"sine"})}get type(){return this._lfo.type}set type(t){this._lfo.type=t}dispose(){return super.dispose(),this._delayNode.dispose(),this._lfo.dispose(),this.frequency.dispose(),this.depth.dispose(),this}}class fs extends Ct{constructor(){super(q(fs.getDefaults(),arguments,["type","size"])),this.name="Analyser",this._analysers=[],this._buffers=[];const t=q(fs.getDefaults(),arguments,["type","size"]);this.input=this.output=this._gain=new Mt({context:this.context}),this._split=new Ln({context:this.context,channels:t.channels}),this.input.connect(this._split),a(t.channels,1);for(let e=0;e{const n=this._buffers[e];"fft"===this._type?t.getFloatFrequencyData(n):"waveform"===this._type&&t.getFloatTimeDomainData(n)}),1===this.channels?this._buffers[0]:this._buffers}get size(){return this._analysers[0].frequencyBinCount}set size(t){this._analysers.forEach((e,n)=>{e.fftSize=2*t,this._buffers[n]=new Float32Array(t)})}get channels(){return this._analysers.length}get type(){return this._type}set type(t){r("waveform"===t||"fft"===t,"Analyser: invalid type: "+t),this._type=t}get smoothing(){return this._analysers[0].smoothingTimeConstant}set smoothing(t){this._analysers.forEach(e=>e.smoothingTimeConstant=t)}dispose(){return super.dispose(),this._analysers.forEach(t=>t.disconnect()),this._split.dispose(),this._gain.dispose(),this}}class _s extends Ct{constructor(){super(q(_s.getDefaults(),arguments)),this.name="MeterBase",this.input=this.output=this._analyser=new fs({context:this.context,size:256,type:"waveform"})}dispose(){return super.dispose(),this._analyser.dispose(),this}}class ms extends _s{constructor(){super(q(ms.getDefaults(),arguments,["smoothing"])),this.name="Meter",this._rms=0;const t=q(ms.getDefaults(),arguments,["smoothing"]);this.input=this.output=this._analyser=new fs({context:this.context,size:256,type:"waveform",channels:t.channels}),this.smoothing=t.smoothing,this.normalRange=t.normalRange}static getDefaults(){return Object.assign(_s.getDefaults(),{smoothing:.8,normalRange:!1,channels:1})}getLevel(){return d("'getLevel' has been changed to 'getValue'"),this.getValue()}getValue(){const t=this._analyser.getValue(),e=(1===this.channels?[t]:t).map(t=>{const e=t.reduce((t,e)=>t+e*e,0),n=Math.sqrt(e/t.length);return this._rms=Math.max(n,this._rms*this.smoothing),this.normalRange?this._rms:ct(this._rms)});return 1===this.channels?e[0]:e}get channels(){return this._analyser.channels}dispose(){return super.dispose(),this._analyser.dispose(),this}}class gs extends _s{constructor(){super(q(gs.getDefaults(),arguments,["size"])),this.name="FFT";const t=q(gs.getDefaults(),arguments,["size"]);this.normalRange=t.normalRange,this._analyser.type="fft",this.size=t.size}static getDefaults(){return Object.assign(Ct.getDefaults(),{normalRange:!1,size:1024,smoothing:.8})}getValue(){return this._analyser.getValue().map(t=>this.normalRange?at(t):t)}get size(){return this._analyser.size}set size(t){this._analyser.size=t}get smoothing(){return this._analyser.smoothing}set smoothing(t){this._analyser.smoothing=t}getFrequencyOfIndex(t){return r(0<=t&&tt._updateSolo())}get muted(){return 0===this.input.gain.value}_addSolo(){bs._soloed.has(this.context)||bs._soloed.set(this.context,new Set),bs._soloed.get(this.context).add(this)}_removeSolo(){bs._soloed.has(this.context)&&bs._soloed.get(this.context).delete(this)}_isSoloed(){return bs._soloed.has(this.context)&&bs._soloed.get(this.context).has(this)}_noSolos(){return!bs._soloed.has(this.context)||bs._soloed.has(this.context)&&0===bs._soloed.get(this.context).size}_updateSolo(){this._isSoloed()||this._noSolos()?this.input.gain.value=1:this.input.gain.value=0}dispose(){return super.dispose(),bs._allSolos.get(this.context).delete(this),this._removeSolo(),this}}bs._allSolos=new Map,bs._soloed=new Map;class xs extends Ct{constructor(){super(q(xs.getDefaults(),arguments,["pan","volume"])),this.name="PanVol";const t=q(xs.getDefaults(),arguments,["pan","volume"]);this._panner=this.input=new Rn({context:this.context,pan:t.pan,channelCount:t.channelCount}),this.pan=this._panner.pan,this._volume=this.output=new Zt({context:this.context,volume:t.volume}),this.volume=this._volume.volume,this._panner.connect(this._volume),this.mute=t.mute,$(this,["pan","volume"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{mute:!1,pan:0,volume:0,channelCount:1})}get mute(){return this._volume.mute}set mute(t){this._volume.mute=t}dispose(){return super.dispose(),this._panner.dispose(),this.pan.dispose(),this._volume.dispose(),this.volume.dispose(),this}}class ws extends Ct{constructor(){super(q(ws.getDefaults(),arguments,["volume","pan"])),this.name="Channel";const t=q(ws.getDefaults(),arguments,["volume","pan"]);this._solo=this.input=new bs({solo:t.solo,context:this.context}),this._panVol=this.output=new xs({context:this.context,pan:t.pan,volume:t.volume,mute:t.mute,channelCount:t.channelCount}),this.pan=this._panVol.pan,this.volume=this._panVol.volume,this._solo.connect(this._panVol),$(this,["pan","volume"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{pan:0,volume:0,mute:!1,solo:!1,channelCount:1})}get solo(){return this._solo.solo}set solo(t){this._solo.solo=t}get muted(){return this._solo.muted||this.mute}get mute(){return this._panVol.mute}set mute(t){this._panVol.mute=t}_getBus(t){return ws.buses.has(t)||ws.buses.set(t,new Mt({context:this.context})),ws.buses.get(t)}send(t,e=0){const n=this._getBus(t),s=new Mt({context:this.context,units:"decibels",gain:e});return this.connect(s),s.connect(n),s}receive(t){return this._getBus(t).connect(this),this}dispose(){return super.dispose(),this._panVol.dispose(),this.pan.dispose(),this.volume.dispose(),this._solo.dispose(),this}}ws.buses=new Map;class Ts extends Ct{constructor(){super(q(Ts.getDefaults(),arguments,["lowFrequency","highFrequency"])),this.name="MultibandSplit",this.input=new Mt({context:this.context}),this.output=void 0,this.low=new Xe({context:this.context,frequency:0,type:"lowpass"}),this._lowMidFilter=new Xe({context:this.context,frequency:0,type:"highpass"}),this.mid=new Xe({context:this.context,frequency:0,type:"lowpass"}),this.high=new Xe({context:this.context,frequency:0,type:"highpass"}),this._internalChannels=[this.low,this.mid,this.high];const t=q(Ts.getDefaults(),arguments,["lowFrequency","highFrequency"]);this.lowFrequency=new Rt({context:this.context,units:"frequency",value:t.lowFrequency}),this.highFrequency=new Rt({context:this.context,units:"frequency",value:t.highFrequency}),this.Q=new Rt({context:this.context,units:"positive",value:t.Q}),this.input.fan(this.low,this.high),this.input.chain(this._lowMidFilter,this.mid),this.lowFrequency.fan(this.low.frequency,this._lowMidFilter.frequency),this.highFrequency.fan(this.mid.frequency,this.high.frequency),this.Q.connect(this.low.Q),this.Q.connect(this._lowMidFilter.Q),this.Q.connect(this.mid.Q),this.Q.connect(this.high.Q),$(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{Q:1,highFrequency:2500,lowFrequency:400})}dispose(){return super.dispose(),J(this,["high","mid","low","highFrequency","lowFrequency"]),this.low.dispose(),this._lowMidFilter.dispose(),this.mid.dispose(),this.high.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this.Q.dispose(),this}}class Os extends Ct{constructor(){super(...arguments),this.name="Listener",this.positionX=new St({context:this.context,param:this.context.rawContext.listener.positionX}),this.positionY=new St({context:this.context,param:this.context.rawContext.listener.positionY}),this.positionZ=new St({context:this.context,param:this.context.rawContext.listener.positionZ}),this.forwardX=new St({context:this.context,param:this.context.rawContext.listener.forwardX}),this.forwardY=new St({context:this.context,param:this.context.rawContext.listener.forwardY}),this.forwardZ=new St({context:this.context,param:this.context.rawContext.listener.forwardZ}),this.upX=new St({context:this.context,param:this.context.rawContext.listener.upX}),this.upY=new St({context:this.context,param:this.context.rawContext.listener.upY}),this.upZ=new St({context:this.context,param:this.context.rawContext.listener.upZ})}static getDefaults(){return Object.assign(Ct.getDefaults(),{positionX:0,positionY:0,positionZ:0,forwardX:0,forwardY:0,forwardZ:-1,upX:0,upY:1,upZ:0})}dispose(){return super.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this.forwardX.dispose(),this.forwardY.dispose(),this.forwardZ.dispose(),this.upX.dispose(),this.upY.dispose(),this.upZ.dispose(),this}}G(t=>{t.listener=new Os({context:t})}),Q(t=>{t.listener.dispose()});class Ss extends Ct{constructor(){super(q(Ss.getDefaults(),arguments,["positionX","positionY","positionZ"])),this.name="Panner3D";const t=q(Ss.getDefaults(),arguments,["positionX","positionY","positionZ"]);this._panner=this.input=this.output=this.context.createPanner(),this.panningModel=t.panningModel,this.maxDistance=t.maxDistance,this.distanceModel=t.distanceModel,this.coneOuterGain=t.coneOuterGain,this.coneOuterAngle=t.coneOuterAngle,this.coneInnerAngle=t.coneInnerAngle,this.refDistance=t.refDistance,this.rolloffFactor=t.rolloffFactor,this.positionX=new St({context:this.context,param:this._panner.positionX,value:t.positionX}),this.positionY=new St({context:this.context,param:this._panner.positionY,value:t.positionY}),this.positionZ=new St({context:this.context,param:this._panner.positionZ,value:t.positionZ}),this.orientationX=new St({context:this.context,param:this._panner.orientationX,value:t.orientationX}),this.orientationY=new St({context:this.context,param:this._panner.orientationY,value:t.orientationY}),this.orientationZ=new St({context:this.context,param:this._panner.orientationZ,value:t.orientationZ})}static getDefaults(){return Object.assign(Ct.getDefaults(),{coneInnerAngle:360,coneOuterAngle:360,coneOuterGain:0,distanceModel:"inverse",maxDistance:1e4,orientationX:0,orientationY:0,orientationZ:0,panningModel:"equalpower",positionX:0,positionY:0,positionZ:0,refDistance:1,rolloffFactor:1})}setPosition(t,e,n){return this.positionX.value=t,this.positionY.value=e,this.positionZ.value=n,this}setOrientation(t,e,n){return this.orientationX.value=t,this.orientationY.value=e,this.orientationZ.value=n,this}get panningModel(){return this._panner.panningModel}set panningModel(t){this._panner.panningModel=t}get refDistance(){return this._panner.refDistance}set refDistance(t){this._panner.refDistance=t}get rolloffFactor(){return this._panner.rolloffFactor}set rolloffFactor(t){this._panner.rolloffFactor=t}get distanceModel(){return this._panner.distanceModel}set distanceModel(t){this._panner.distanceModel=t}get coneInnerAngle(){return this._panner.coneInnerAngle}set coneInnerAngle(t){this._panner.coneInnerAngle=t}get coneOuterAngle(){return this._panner.coneOuterAngle}set coneOuterAngle(t){this._panner.coneOuterAngle=t}get coneOuterGain(){return this._panner.coneOuterGain}set coneOuterGain(t){this._panner.coneOuterGain=t}get maxDistance(){return this._panner.maxDistance}set maxDistance(t){this._panner.maxDistance=t}dispose(){return super.dispose(),this._panner.disconnect(),this.orientationX.dispose(),this.orientationY.dispose(),this.orientationZ.dispose(),this.positionX.dispose(),this.positionY.dispose(),this.positionZ.dispose(),this}}class Cs extends Ct{constructor(){super(q(Cs.getDefaults(),arguments)),this.name="Recorder";const t=q(Cs.getDefaults(),arguments);this.input=new Mt({context:this.context}),r(Cs.supported,"Media Recorder API is not available"),this._stream=this.context.createMediaStreamDestination(),this.input.connect(this._stream),this._recorder=new MediaRecorder(this._stream.stream,{mimeType:t.mimeType})}static getDefaults(){return Ct.getDefaults()}get mimeType(){return this._recorder.mimeType}static get supported(){return null!==w&&Reflect.has(w,"MediaRecorder")}get state(){return"inactive"===this._recorder.state?"stopped":"paused"===this._recorder.state?"paused":"started"}start(){return S(this,void 0,void 0,(function*(){r("started"!==this.state,"Recorder is already started");const t=new Promise(t=>{const e=()=>{this._recorder.removeEventListener("start",e,!1),t()};this._recorder.addEventListener("start",e,!1)});return this._recorder.start(),yield t}))}stop(){return S(this,void 0,void 0,(function*(){r("stopped"!==this.state,"Recorder is not started");const t=new Promise(t=>{const e=n=>{this._recorder.removeEventListener("dataavailable",e,!1),t(n.data)};this._recorder.addEventListener("dataavailable",e,!1)});return this._recorder.stop(),yield t}))}pause(){return r("started"===this.state,"Recorder must be started"),this._recorder.pause(),this}dispose(){return super.dispose(),this.input.dispose(),this._stream.disconnect(),this}}class ks extends Ct{constructor(){super(q(ks.getDefaults(),arguments,["threshold","ratio"])),this.name="Compressor",this._compressor=this.context.createDynamicsCompressor(),this.input=this._compressor,this.output=this._compressor;const t=q(ks.getDefaults(),arguments,["threshold","ratio"]);this.threshold=new St({minValue:this._compressor.threshold.minValue,maxValue:this._compressor.threshold.maxValue,context:this.context,convert:!1,param:this._compressor.threshold,units:"decibels",value:t.threshold}),this.attack=new St({minValue:this._compressor.attack.minValue,maxValue:this._compressor.attack.maxValue,context:this.context,param:this._compressor.attack,units:"time",value:t.attack}),this.release=new St({minValue:this._compressor.release.minValue,maxValue:this._compressor.release.maxValue,context:this.context,param:this._compressor.release,units:"time",value:t.release}),this.knee=new St({minValue:this._compressor.knee.minValue,maxValue:this._compressor.knee.maxValue,context:this.context,convert:!1,param:this._compressor.knee,units:"decibels",value:t.knee}),this.ratio=new St({minValue:this._compressor.ratio.minValue,maxValue:this._compressor.ratio.maxValue,context:this.context,convert:!1,param:this._compressor.ratio,units:"positive",value:t.ratio}),$(this,["knee","release","attack","ratio","threshold"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{attack:.003,knee:30,ratio:12,release:.25,threshold:-24})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.disconnect(),this.attack.dispose(),this.release.dispose(),this.threshold.dispose(),this.ratio.dispose(),this.knee.dispose(),this}}class As extends Ct{constructor(){super(Object.assign(q(As.getDefaults(),arguments,["threshold","smoothing"]))),this.name="Gate";const t=q(As.getDefaults(),arguments,["threshold","smoothing"]);this._follower=new In({context:this.context,smoothing:t.smoothing}),this._gt=new Fe({context:this.context,value:at(t.threshold)}),this.input=new Mt({context:this.context}),this._gate=this.output=new Mt({context:this.context}),this.input.connect(this._gate),this.input.chain(this._follower,this._gt,this._gate.gain)}static getDefaults(){return Object.assign(Ct.getDefaults(),{smoothing:.1,threshold:-40})}get threshold(){return ct(this._gt.value)}set threshold(t){this._gt.value=at(t)}get smoothing(){return this._follower.smoothing}set smoothing(t){this._follower.smoothing=t}dispose(){return super.dispose(),this.input.dispose(),this._follower.dispose(),this._gt.dispose(),this._gate.dispose(),this}}class Ds extends Ct{constructor(){super(Object.assign(q(Ds.getDefaults(),arguments,["threshold"]))),this.name="Limiter";const t=q(Ds.getDefaults(),arguments,["threshold"]);this._compressor=this.input=this.output=new ks({context:this.context,ratio:20,attack:0,release:0,threshold:t.threshold}),this.threshold=this._compressor.threshold,$(this,"threshold")}static getDefaults(){return Object.assign(Ct.getDefaults(),{threshold:-12})}get reduction(){return this._compressor.reduction}dispose(){return super.dispose(),this._compressor.dispose(),this.threshold.dispose(),this}}class Ms extends Ct{constructor(){super(Object.assign(q(Ms.getDefaults(),arguments))),this.name="MidSideCompressor";const t=q(Ms.getDefaults(),arguments);this._midSideSplit=this.input=new cs({context:this.context}),this._midSideMerge=this.output=new us({context:this.context}),this.mid=new ks(Object.assign(t.mid,{context:this.context})),this.side=new ks(Object.assign(t.side,{context:this.context})),this._midSideSplit.mid.chain(this.mid,this._midSideMerge.mid),this._midSideSplit.side.chain(this.side,this._midSideMerge.side),$(this,["mid","side"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},side:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10}})}dispose(){return super.dispose(),this.mid.dispose(),this.side.dispose(),this._midSideSplit.dispose(),this._midSideMerge.dispose(),this}}class js extends Ct{constructor(){super(Object.assign(q(js.getDefaults(),arguments))),this.name="MultibandCompressor";const t=q(js.getDefaults(),arguments);this._splitter=this.input=new Ts({context:this.context,lowFrequency:t.lowFrequency,highFrequency:t.highFrequency}),this.lowFrequency=this._splitter.lowFrequency,this.highFrequency=this._splitter.highFrequency,this.output=new Mt({context:this.context}),this.low=new ks(Object.assign(t.low,{context:this.context})),this.mid=new ks(Object.assign(t.mid,{context:this.context})),this.high=new ks(Object.assign(t.high,{context:this.context})),this._splitter.low.chain(this.low,this.output),this._splitter.mid.chain(this.mid,this.output),this._splitter.high.chain(this.high,this.output),$(this,["high","mid","low","highFrequency","lowFrequency"])}static getDefaults(){return Object.assign(Ct.getDefaults(),{lowFrequency:250,highFrequency:2e3,low:{ratio:6,threshold:-30,release:.25,attack:.03,knee:10},mid:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16},high:{ratio:3,threshold:-24,release:.03,attack:.02,knee:16}})}dispose(){return super.dispose(),this._splitter.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.output.dispose(),this}}class Es extends Ct{constructor(){super(q(Es.getDefaults(),arguments,["low","mid","high"])),this.name="EQ3",this.output=new Mt({context:this.context}),this._internalChannels=[];const t=q(Es.getDefaults(),arguments,["low","mid","high"]);this.input=this._multibandSplit=new Ts({context:this.context,highFrequency:t.highFrequency,lowFrequency:t.lowFrequency}),this._lowGain=new Mt({context:this.context,gain:t.low,units:"decibels"}),this._midGain=new Mt({context:this.context,gain:t.mid,units:"decibels"}),this._highGain=new Mt({context:this.context,gain:t.high,units:"decibels"}),this.low=this._lowGain.gain,this.mid=this._midGain.gain,this.high=this._highGain.gain,this.Q=this._multibandSplit.Q,this.lowFrequency=this._multibandSplit.lowFrequency,this.highFrequency=this._multibandSplit.highFrequency,this._multibandSplit.low.chain(this._lowGain,this.output),this._multibandSplit.mid.chain(this._midGain,this.output),this._multibandSplit.high.chain(this._highGain,this.output),$(this,["low","mid","high","lowFrequency","highFrequency"]),this._internalChannels=[this._multibandSplit]}static getDefaults(){return Object.assign(Ct.getDefaults(),{high:0,highFrequency:2500,low:0,lowFrequency:400,mid:0})}dispose(){return super.dispose(),J(this,["low","mid","high","lowFrequency","highFrequency"]),this._multibandSplit.dispose(),this.lowFrequency.dispose(),this.highFrequency.dispose(),this._lowGain.dispose(),this._midGain.dispose(),this._highGain.dispose(),this.low.dispose(),this.mid.dispose(),this.high.dispose(),this.Q.dispose(),this}}class Rs extends Ct{constructor(){super(q(Rs.getDefaults(),arguments,["url","onload"])),this.name="Convolver",this._convolver=this.context.createConvolver();const t=q(Rs.getDefaults(),arguments,["url","onload"]);this._buffer=new tt(t.url,e=>{this.buffer=e,t.onload()}),this.input=new Mt({context:this.context}),this.output=new Mt({context:this.context}),this._buffer.loaded&&(this.buffer=this._buffer),this.normalize=t.normalize,this.input.chain(this._convolver,this.output)}static getDefaults(){return Object.assign(Ct.getDefaults(),{normalize:!0,onload:K})}load(t){return S(this,void 0,void 0,(function*(){this.buffer=yield this._buffer.load(t)}))}get buffer(){return this._buffer.length?this._buffer:null}set buffer(t){t&&this._buffer.set(t),this._convolver.buffer&&(this.input.disconnect(),this._convolver.disconnect(),this._convolver=this.context.createConvolver(),this.input.chain(this._convolver,this.output));const e=this._buffer.get();this._convolver.buffer=e||null}get normalize(){return this._convolver.normalize}set normalize(t){this._convolver.normalize=t}dispose(){return super.dispose(),this._buffer.dispose(),this._convolver.disconnect(),this}}function qs(){return it().now()}function Is(){return it().immediate()}const Fs=it().transport;function Vs(){return it().transport}const Ns=it().destination,Ps=it().destination;function Ls(){return it().destination}const zs=it().listener;function Bs(){return it().listener}const Ws=it().draw;function Us(){return it().draw}const Gs=it();function Ys(){return tt.loaded()}const Qs=tt,Zs=$t,Xs=se}])}));
-//# sourceMappingURL=Tone.js.map
\ No newline at end of file
diff --git a/lib/howler.js b/lib/howler.js
deleted file mode 100644
index d0022fc..0000000
--- a/lib/howler.js
+++ /dev/null
@@ -1,3157 +0,0 @@
-/*!
- *  howler.js v2.1.2
- *  howlerjs.com
- *
- *  (c) 2013-2019, James Simpson of GoldFire Studios
- *  goldfirestudios.com
- *
- *  MIT License
- */
-
-(function() {
-
-  'use strict';
-
-  /** Global Methods **/
-  /***************************************************************************/
-
-  /**
-   * Create the global controller. All contained methods and properties apply
-   * to all sounds that are currently playing or will be in the future.
-   */
-  var HowlerGlobal = function() {
-    this.init();
-  };
-  HowlerGlobal.prototype = {
-    /**
-     * Initialize the global Howler object.
-     * @return {Howler}
-     */
-    init: function() {
-      var self = this || Howler;
-
-      // Create a global ID counter.
-      self._counter = 1000;
-
-      // Pool of unlocked HTML5 Audio objects.
-      self._html5AudioPool = [];
-      self.html5PoolSize = 10;
-
-      // Internal properties.
-      self._codecs = {};
-      self._howls = [];
-      self._muted = false;
-      self._volume = 1;
-      self._canPlayEvent = 'canplaythrough';
-      self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null;
-
-      // Public properties.
-      self.masterGain = null;
-      self.noAudio = false;
-      self.usingWebAudio = true;
-      self.autoSuspend = true;
-      self.ctx = null;
-
-      // Set to false to disable the auto audio unlocker.
-      self.autoUnlock = true;
-
-      // Setup the various state values for global tracking.
-      self._setup();
-
-      return self;
-    },
-
-    /**
-     * Get/set the global volume for all sounds.
-     * @param  {Float} vol Volume from 0.0 to 1.0.
-     * @return {Howler/Float}     Returns self or current volume.
-     */
-    volume: function(vol) {
-      var self = this || Howler;
-      vol = parseFloat(vol);
-
-      // If we don't have an AudioContext created yet, run the setup.
-      if (!self.ctx) {
-        setupAudioContext();
-      }
-
-      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
-        self._volume = vol;
-
-        // Don't update any of the nodes if we are muted.
-        if (self._muted) {
-          return self;
-        }
-
-        // When using Web Audio, we just need to adjust the master gain.
-        if (self.usingWebAudio) {
-          self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime);
-        }
-
-        // Loop through and change volume for all HTML5 audio nodes.
-        for (var i=0; i=0; i--) {
-        self._howls[i].unload();
-      }
-
-      // Create a new AudioContext to make sure it is fully reset.
-      if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') {
-        self.ctx.close();
-        self.ctx = null;
-        setupAudioContext();
-      }
-
-      return self;
-    },
-
-    /**
-     * Check for codec support of specific extension.
-     * @param  {String} ext Audio file extention.
-     * @return {Boolean}
-     */
-    codecs: function(ext) {
-      return (this || Howler)._codecs[ext.replace(/^x-/, '')];
-    },
-
-    /**
-     * Setup various state values for global tracking.
-     * @return {Howler}
-     */
-    _setup: function() {
-      var self = this || Howler;
-
-      // Keeps track of the suspend/resume state of the AudioContext.
-      self.state = self.ctx ? self.ctx.state || 'suspended' : 'suspended';
-
-      // Automatically begin the 30-second suspend process
-      self._autoSuspend();
-
-      // Check if audio is available.
-      if (!self.usingWebAudio) {
-        // No audio is available on this system if noAudio is set to true.
-        if (typeof Audio !== 'undefined') {
-          try {
-            var test = new Audio();
-
-            // Check if the canplaythrough event is available.
-            if (typeof test.oncanplaythrough === 'undefined') {
-              self._canPlayEvent = 'canplay';
-            }
-          } catch(e) {
-            self.noAudio = true;
-          }
-        } else {
-          self.noAudio = true;
-        }
-      }
-
-      // Test to make sure audio isn't disabled in Internet Explorer.
-      try {
-        var test = new Audio();
-        if (test.muted) {
-          self.noAudio = true;
-        }
-      } catch (e) {}
-
-      // Check for supported codecs.
-      if (!self.noAudio) {
-        self._setupCodecs();
-      }
-
-      return self;
-    },
-
-    /**
-     * Check for browser support for various codecs and cache the results.
-     * @return {Howler}
-     */
-    _setupCodecs: function() {
-      var self = this || Howler;
-      var audioTest = null;
-
-      // Must wrap in a try/catch because IE11 in server mode throws an error.
-      try {
-        audioTest = (typeof Audio !== 'undefined') ? new Audio() : null;
-      } catch (err) {
-        return self;
-      }
-
-      if (!audioTest || typeof audioTest.canPlayType !== 'function') {
-        return self;
-      }
-
-      var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
-
-      // Opera version <33 has mixed MP3 support, so we need to check for and block it.
-      var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g);
-      var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33);
-
-      self._codecs = {
-        mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))),
-        mpeg: !!mpegTest,
-        opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''),
-        ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
-        oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
-        wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''),
-        aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''),
-        caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''),
-        m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
-        mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''),
-        weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
-        webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''),
-        dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''),
-        flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '')
-      };
-
-      return self;
-    },
-
-    /**
-     * Some browsers/devices will only allow audio to be played after a user interaction.
-     * Attempt to automatically unlock audio on the first user interaction.
-     * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
-     * @return {Howler}
-     */
-    _unlockAudio: function() {
-      var self = this || Howler;
-
-      // Only run this if Web Audio is supported and it hasn't already been unlocked.
-      if (self._audioUnlocked || !self.ctx) {
-        return;
-      }
-
-      self._audioUnlocked = false;
-      self.autoUnlock = false;
-
-      // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views.
-      // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000.
-      // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate.
-      if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) {
-        self._mobileUnloaded = true;
-        self.unload();
-      }
-
-      // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per:
-      // http://stackoverflow.com/questions/24119684
-      self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050);
-
-      // Call this method on touch start to create and play a buffer,
-      // then check if the audio actually played to determine if
-      // audio has now been unlocked on iOS, Android, etc.
-      var unlock = function(e) {
-        // Create a pool of unlocked HTML5 Audio objects that can
-        // be used for playing sounds without user interaction. HTML5
-        // Audio objects must be individually unlocked, as opposed
-        // to the WebAudio API which only needs a single activation.
-        // This must occur before WebAudio setup or the source.onended
-        // event will not fire.
-        for (var i=0; i= 55.
-        if (typeof self.ctx.resume === 'function') {
-          self.ctx.resume();
-        }
-
-        // Setup a timeout to check that we are unlocked on the next event loop.
-        source.onended = function() {
-          source.disconnect(0);
-
-          // Update the unlocked state and prevent this check from happening again.
-          self._audioUnlocked = true;
-
-          // Remove the touch start listener.
-          document.removeEventListener('touchstart', unlock, true);
-          document.removeEventListener('touchend', unlock, true);
-          document.removeEventListener('click', unlock, true);
-
-          // Let all sounds know that audio has been unlocked.
-          for (var i=0; i 0 ? sound._seek : self._sprite[sprite][0] / 1000);
-      var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek);
-      var timeout = (duration * 1000) / Math.abs(sound._rate);
-      var start = self._sprite[sprite][0] / 1000;
-      var stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000;
-      var loop = !!(sound._loop || self._sprite[sprite][2]);
-      sound._sprite = sprite;
-
-      // Mark the sound as ended instantly so that this async playback
-      // doesn't get grabbed by another call to play while this one waits to start.
-      sound._ended = false;
-
-      // Update the parameters of the sound.
-      var setParams = function() {
-        sound._paused = false;
-        sound._seek = seek;
-        sound._start = start;
-        sound._stop = stop;
-        sound._loop = loop;
-      };
-
-      // End the sound instantly if seek is at the end.
-      if (seek >= stop) {
-        self._ended(sound);
-        return;
-      }
-
-      // Begin the actual playback.
-      var node = sound._node;
-      if (self._webAudio) {
-        // Fire this when the sound is ready to play to begin Web Audio playback.
-        var playWebAudio = function() {
-          self._playLock = false;
-          setParams();
-          self._refreshBuffer(sound);
-
-          // Setup the playback params.
-          var vol = (sound._muted || self._muted) ? 0 : sound._volume;
-          node.gain.setValueAtTime(vol, Howler.ctx.currentTime);
-          sound._playStart = Howler.ctx.currentTime;
-
-          // Play the sound using the supported method.
-          if (typeof node.bufferSource.start === 'undefined') {
-            sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration);
-          } else {
-            sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration);
-          }
-
-          // Start a new timer if none is present.
-          if (timeout !== Infinity) {
-            self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
-          }
-
-          if (!internal) {
-            setTimeout(function() {
-              self._emit('play', sound._id);
-              self._loadQueue();
-            }, 0);
-          }
-        };
-
-        if (Howler.state === 'running') {
-          playWebAudio();
-        } else {
-          self._playLock = true;
-
-          // Wait for the audio context to resume before playing.
-          self.once('resume', playWebAudio);
-
-          // Cancel the end timer.
-          self._clearTimer(sound._id);
-        }
-      } else {
-        // Fire this when the sound is ready to play to begin HTML5 Audio playback.
-        var playHtml5 = function() {
-          node.currentTime = seek;
-          node.muted = sound._muted || self._muted || Howler._muted || node.muted;
-          node.volume = sound._volume * Howler.volume();
-          node.playbackRate = sound._rate;
-
-          // Some browsers will throw an error if this is called without user interaction.
-          try {
-            var play = node.play();
-
-            // Support older browsers that don't support promises, and thus don't have this issue.
-            if (play && typeof Promise !== 'undefined' && (play instanceof Promise || typeof play.then === 'function')) {
-              // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause().
-              self._playLock = true;
-
-              // Set param values immediately.
-              setParams();
-
-              // Releases the lock and executes queued actions.
-              play
-                .then(function() {
-                  self._playLock = false;
-                  node._unlocked = true;
-                  if (!internal) {
-                    self._emit('play', sound._id);
-                    self._loadQueue();
-                  }
-                })
-                .catch(function() {
-                  self._playLock = false;
-                  self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
-                    'on mobile devices and Chrome where playback was not within a user interaction.');
-
-                  // Reset the ended and paused values.
-                  sound._ended = true;
-                  sound._paused = true;
-                });
-            } else if (!internal) {
-              self._playLock = false;
-              setParams();
-              self._emit('play', sound._id);
-              self._loadQueue();
-            }
-
-            // Setting rate before playing won't work in IE, so we set it again here.
-            node.playbackRate = sound._rate;
-
-            // If the node is still paused, then we can assume there was a playback issue.
-            if (node.paused) {
-              self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' +
-                'on mobile devices and Chrome where playback was not within a user interaction.');
-              return;
-            }
-
-            // Setup the end timer on sprites or listen for the ended event.
-            if (sprite !== '__default' || sound._loop) {
-              self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
-            } else {
-              self._endTimers[sound._id] = function() {
-                // Fire ended on this audio node.
-                self._ended(sound);
-
-                // Clear this listener.
-                node.removeEventListener('ended', self._endTimers[sound._id], false);
-              };
-              node.addEventListener('ended', self._endTimers[sound._id], false);
-            }
-          } catch (err) {
-            self._emit('playerror', sound._id, err);
-          }
-        };
-
-        // If this is streaming audio, make sure the src is set and load again.
-        if (node.src === 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA') {
-          node.src = self._src;
-          node.load();
-        }
-
-        // Play immediately if ready, or wait for the 'canplaythrough'e vent.
-        var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS);
-        if (node.readyState >= 3 || loadedNoReadyState) {
-          playHtml5();
-        } else {
-          self._playLock = true;
-
-          var listener = function() {
-            // Begin playback.
-            playHtml5();
-
-            // Clear this listener.
-            node.removeEventListener(Howler._canPlayEvent, listener, false);
-          };
-          node.addEventListener(Howler._canPlayEvent, listener, false);
-
-          // Cancel the end timer.
-          self._clearTimer(sound._id);
-        }
-      }
-
-      return sound._id;
-    },
-
-    /**
-     * Pause playback and save current position.
-     * @param  {Number} id The sound ID (empty to pause all in group).
-     * @return {Howl}
-     */
-    pause: function(id) {
-      var self = this;
-
-      // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable.
-      if (self._state !== 'loaded' || self._playLock) {
-        self._queue.push({
-          event: 'pause',
-          action: function() {
-            self.pause(id);
-          }
-        });
-
-        return self;
-      }
-
-      // If no id is passed, get all ID's to be paused.
-      var ids = self._getSoundIds(id);
-
-      for (var i=0; i Returns the group's volume value.
-     *   volume(id) -> Returns the sound id's current volume.
-     *   volume(vol) -> Sets the volume of all sounds in this Howl group.
-     *   volume(vol, id) -> Sets the volume of passed sound id.
-     * @return {Howl/Number} Returns self or current volume.
-     */
-    volume: function() {
-      var self = this;
-      var args = arguments;
-      var vol, id;
-
-      // Determine the values based on arguments.
-      if (args.length === 0) {
-        // Return the value of the groups' volume.
-        return self._volume;
-      } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') {
-        // First check if this is an ID, and if not, assume it is a new volume.
-        var ids = self._getSoundIds();
-        var index = ids.indexOf(args[0]);
-        if (index >= 0) {
-          id = parseInt(args[0], 10);
-        } else {
-          vol = parseFloat(args[0]);
-        }
-      } else if (args.length >= 2) {
-        vol = parseFloat(args[0]);
-        id = parseInt(args[1], 10);
-      }
-
-      // Update the volume or return the current volume.
-      var sound;
-      if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) {
-        // If the sound hasn't loaded, add it to the load queue to change volume when capable.
-        if (self._state !== 'loaded'|| self._playLock) {
-          self._queue.push({
-            event: 'volume',
-            action: function() {
-              self.volume.apply(self, args);
-            }
-          });
-
-          return self;
-        }
-
-        // Set the group volume.
-        if (typeof id === 'undefined') {
-          self._volume = vol;
-        }
-
-        // Update one or all volumes.
-        id = self._getSoundIds(id);
-        for (var i=0; i 0) ? len / steps : len);
-      var lastTick = Date.now();
-
-      // Store the value being faded to.
-      sound._fadeTo = to;
-
-      // Update the volume value on each interval tick.
-      sound._interval = setInterval(function() {
-        // Update the volume based on the time since the last tick.
-        var tick = (Date.now() - lastTick) / len;
-        lastTick = Date.now();
-        vol += diff * tick;
-
-        // Make sure the volume is in the right bounds.
-        vol = Math.max(0, vol);
-        vol = Math.min(1, vol);
-
-        // Round to within 2 decimal points.
-        vol = Math.round(vol * 100) / 100;
-
-        // Change the volume.
-        if (self._webAudio) {
-          sound._volume = vol;
-        } else {
-          self.volume(vol, sound._id, true);
-        }
-
-        // Set the group's volume.
-        if (isGroup) {
-          self._volume = vol;
-        }
-
-        // When the fade is complete, stop it and fire event.
-        if ((to < from && vol <= to) || (to > from && vol >= to)) {
-          clearInterval(sound._interval);
-          sound._interval = null;
-          sound._fadeTo = null;
-          self.volume(to, sound._id);
-          self._emit('fade', sound._id);
-        }
-      }, stepLen);
-    },
-
-    /**
-     * Internal method that stops the currently playing fade when
-     * a new fade starts, volume is changed or the sound is stopped.
-     * @param  {Number} id The sound id.
-     * @return {Howl}
-     */
-    _stopFade: function(id) {
-      var self = this;
-      var sound = self._soundById(id);
-
-      if (sound && sound._interval) {
-        if (self._webAudio) {
-          sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime);
-        }
-
-        clearInterval(sound._interval);
-        sound._interval = null;
-        self.volume(sound._fadeTo, id);
-        sound._fadeTo = null;
-        self._emit('fade', id);
-      }
-
-      return self;
-    },
-
-    /**
-     * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments.
-     *   loop() -> Returns the group's loop value.
-     *   loop(id) -> Returns the sound id's loop value.
-     *   loop(loop) -> Sets the loop value for all sounds in this Howl group.
-     *   loop(loop, id) -> Sets the loop value of passed sound id.
-     * @return {Howl/Boolean} Returns self or current loop value.
-     */
-    loop: function() {
-      var self = this;
-      var args = arguments;
-      var loop, id, sound;
-
-      // Determine the values for loop and id.
-      if (args.length === 0) {
-        // Return the grou's loop value.
-        return self._loop;
-      } else if (args.length === 1) {
-        if (typeof args[0] === 'boolean') {
-          loop = args[0];
-          self._loop = loop;
-        } else {
-          // Return this sound's loop value.
-          sound = self._soundById(parseInt(args[0], 10));
-          return sound ? sound._loop : false;
-        }
-      } else if (args.length === 2) {
-        loop = args[0];
-        id = parseInt(args[1], 10);
-      }
-
-      // If no id is passed, get all ID's to be looped.
-      var ids = self._getSoundIds(id);
-      for (var i=0; i Returns the first sound node's current playback rate.
-     *   rate(id) -> Returns the sound id's current playback rate.
-     *   rate(rate) -> Sets the playback rate of all sounds in this Howl group.
-     *   rate(rate, id) -> Sets the playback rate of passed sound id.
-     * @return {Howl/Number} Returns self or the current playback rate.
-     */
-    rate: function() {
-      var self = this;
-      var args = arguments;
-      var rate, id;
-
-      // Determine the values based on arguments.
-      if (args.length === 0) {
-        // We will simply return the current rate of the first node.
-        id = self._sounds[0]._id;
-      } else if (args.length === 1) {
-        // First check if this is an ID, and if not, assume it is a new rate value.
-        var ids = self._getSoundIds();
-        var index = ids.indexOf(args[0]);
-        if (index >= 0) {
-          id = parseInt(args[0], 10);
-        } else {
-          rate = parseFloat(args[0]);
-        }
-      } else if (args.length === 2) {
-        rate = parseFloat(args[0]);
-        id = parseInt(args[1], 10);
-      }
-
-      // Update the playback rate or return the current value.
-      var sound;
-      if (typeof rate === 'number') {
-        // If the sound hasn't loaded, add it to the load queue to change playback rate when capable.
-        if (self._state !== 'loaded' || self._playLock) {
-          self._queue.push({
-            event: 'rate',
-            action: function() {
-              self.rate.apply(self, args);
-            }
-          });
-
-          return self;
-        }
-
-        // Set the group rate.
-        if (typeof id === 'undefined') {
-          self._rate = rate;
-        }
-
-        // Update one or all volumes.
-        id = self._getSoundIds(id);
-        for (var i=0; i Returns the first sound node's current seek position.
-     *   seek(id) -> Returns the sound id's current seek position.
-     *   seek(seek) -> Sets the seek position of the first sound node.
-     *   seek(seek, id) -> Sets the seek position of passed sound id.
-     * @return {Howl/Number} Returns self or the current seek position.
-     */
-    seek: function() {
-      var self = this;
-      var args = arguments;
-      var seek, id;
-
-      // Determine the values based on arguments.
-      if (args.length === 0) {
-        // We will simply return the current position of the first node.
-        id = self._sounds[0]._id;
-      } else if (args.length === 1) {
-        // First check if this is an ID, and if not, assume it is a new seek position.
-        var ids = self._getSoundIds();
-        var index = ids.indexOf(args[0]);
-        if (index >= 0) {
-          id = parseInt(args[0], 10);
-        } else if (self._sounds.length) {
-          id = self._sounds[0]._id;
-          seek = parseFloat(args[0]);
-        }
-      } else if (args.length === 2) {
-        seek = parseFloat(args[0]);
-        id = parseInt(args[1], 10);
-      }
-
-      // If there is no ID, bail out.
-      if (typeof id === 'undefined') {
-        return self;
-      }
-
-      // If the sound hasn't loaded, add it to the load queue to seek when capable.
-      if (self._state !== 'loaded' || self._playLock) {
-        self._queue.push({
-          event: 'seek',
-          action: function() {
-            self.seek.apply(self, args);
-          }
-        });
-
-        return self;
-      }
-
-      // Get the sound.
-      var sound = self._soundById(id);
-
-      if (sound) {
-        if (typeof seek === 'number' && seek >= 0) {
-          // Pause the sound and update position for restarting playback.
-          var playing = self.playing(id);
-          if (playing) {
-            self.pause(id, true);
-          }
-
-          // Move the position of the track and cancel timer.
-          sound._seek = seek;
-          sound._ended = false;
-          self._clearTimer(id);
-
-          // Update the seek position for HTML5 Audio.
-          if (!self._webAudio && sound._node && !isNaN(sound._node.duration)) {
-            sound._node.currentTime = seek;
-          }
-
-          // Seek and emit when ready.
-          var seekAndEmit = function() {
-            self._emit('seek', id);
-
-            // Restart the playback if the sound was playing.
-            if (playing) {
-              self.play(id, true);
-            }
-          };
-
-          // Wait for the play lock to be unset before emitting (HTML5 Audio).
-          if (playing && !self._webAudio) {
-            var emitSeek = function() {
-              if (!self._playLock) {
-                seekAndEmit();
-              } else {
-                setTimeout(emitSeek, 0);
-              }
-            };
-            setTimeout(emitSeek, 0);
-          } else {
-            seekAndEmit();
-          }
-        } else {
-          if (self._webAudio) {
-            var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0;
-            var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0;
-            return sound._seek + (rateSeek + realTime * Math.abs(sound._rate));
-          } else {
-            return sound._node.currentTime;
-          }
-        }
-      }
-
-      return self;
-    },
-
-    /**
-     * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not.
-     * @param  {Number}  id The sound id to check. If none is passed, the whole sound group is checked.
-     * @return {Boolean} True if playing and false if not.
-     */
-    playing: function(id) {
-      var self = this;
-
-      // Check the passed sound ID (if any).
-      if (typeof id === 'number') {
-        var sound = self._soundById(id);
-        return sound ? !sound._paused : false;
-      }
-
-      // Otherwise, loop through all sounds and check if any are playing.
-      for (var i=0; i= 0) {
-        Howler._howls.splice(index, 1);
-      }
-
-      // Delete this sound from the cache (if no other Howl is using it).
-      var remCache = true;
-      for (i=0; i= 0) {
-          remCache = false;
-          break;
-        }
-      }
-
-      if (cache && remCache) {
-        delete cache[self._src];
-      }
-
-      // Clear global errors.
-      Howler.noAudio = false;
-
-      // Clear out `self`.
-      self._state = 'unloaded';
-      self._sounds = [];
-      self = null;
-
-      return null;
-    },
-
-    /**
-     * Listen to a custom event.
-     * @param  {String}   event Event name.
-     * @param  {Function} fn    Listener to call.
-     * @param  {Number}   id    (optional) Only listen to events for this sound.
-     * @param  {Number}   once  (INTERNAL) Marks event to fire only once.
-     * @return {Howl}
-     */
-    on: function(event, fn, id, once) {
-      var self = this;
-      var events = self['_on' + event];
-
-      if (typeof fn === 'function') {
-        events.push(once ? {id: id, fn: fn, once: once} : {id: id, fn: fn});
-      }
-
-      return self;
-    },
-
-    /**
-     * Remove a custom event. Call without parameters to remove all events.
-     * @param  {String}   event Event name.
-     * @param  {Function} fn    Listener to remove. Leave empty to remove all.
-     * @param  {Number}   id    (optional) Only remove events for this sound.
-     * @return {Howl}
-     */
-    off: function(event, fn, id) {
-      var self = this;
-      var events = self['_on' + event];
-      var i = 0;
-
-      // Allow passing just an event and ID.
-      if (typeof fn === 'number') {
-        id = fn;
-        fn = null;
-      }
-
-      if (fn || id) {
-        // Loop through event store and remove the passed function.
-        for (i=0; i=0; i--) {
-        // Only fire the listener if the correct ID is used.
-        if (!events[i].id || events[i].id === id || event === 'load') {
-          setTimeout(function(fn) {
-            fn.call(this, id, msg);
-          }.bind(self, events[i].fn), 0);
-
-          // If this event was setup with `once`, remove it.
-          if (events[i].once) {
-            self.off(event, events[i].fn, events[i].id);
-          }
-        }
-      }
-
-      // Pass the event type into load queue so that it can continue stepping.
-      self._loadQueue(event);
-
-      return self;
-    },
-
-    /**
-     * Queue of actions initiated before the sound has loaded.
-     * These will be called in sequence, with the next only firing
-     * after the previous has finished executing (even if async like play).
-     * @return {Howl}
-     */
-    _loadQueue: function(event) {
-      var self = this;
-
-      if (self._queue.length > 0) {
-        var task = self._queue[0];
-
-        // Remove this task if a matching event was passed.
-        if (task.event === event) {
-          self._queue.shift();
-          self._loadQueue();
-        }
-
-        // Run the task if no event type is passed.
-        if (!event) {
-          task.action();
-        }
-      }
-
-      return self;
-    },
-
-    /**
-     * Fired when playback ends at the end of the duration.
-     * @param  {Sound} sound The sound object to work with.
-     * @return {Howl}
-     */
-    _ended: function(sound) {
-      var self = this;
-      var sprite = sound._sprite;
-
-      // If we are using IE and there was network latency we may be clipping
-      // audio before it completes playing. Lets check the node to make sure it
-      // believes it has completed, before ending the playback.
-      if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) {
-        setTimeout(self._ended.bind(self, sound), 100);
-        return self;
-      }
-
-      // Should this sound loop?
-      var loop = !!(sound._loop || self._sprite[sprite][2]);
-
-      // Fire the ended event.
-      self._emit('end', sound._id);
-
-      // Restart the playback for HTML5 Audio loop.
-      if (!self._webAudio && loop) {
-        self.stop(sound._id, true).play(sound._id);
-      }
-
-      // Restart this timer if on a Web Audio loop.
-      if (self._webAudio && loop) {
-        self._emit('play', sound._id);
-        sound._seek = sound._start || 0;
-        sound._rateSeek = 0;
-        sound._playStart = Howler.ctx.currentTime;
-
-        var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate);
-        self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout);
-      }
-
-      // Mark the node as paused.
-      if (self._webAudio && !loop) {
-        sound._paused = true;
-        sound._ended = true;
-        sound._seek = sound._start || 0;
-        sound._rateSeek = 0;
-        self._clearTimer(sound._id);
-
-        // Clean up the buffer source.
-        self._cleanBuffer(sound._node);
-
-        // Attempt to auto-suspend AudioContext if no sounds are still playing.
-        Howler._autoSuspend();
-      }
-
-      // When using a sprite, end the track.
-      if (!self._webAudio && !loop) {
-        self.stop(sound._id, true);
-      }
-
-      return self;
-    },
-
-    /**
-     * Clear the end timer for a sound playback.
-     * @param  {Number} id The sound ID.
-     * @return {Howl}
-     */
-    _clearTimer: function(id) {
-      var self = this;
-
-      if (self._endTimers[id]) {
-        // Clear the timeout or remove the ended listener.
-        if (typeof self._endTimers[id] !== 'function') {
-          clearTimeout(self._endTimers[id]);
-        } else {
-          var sound = self._soundById(id);
-          if (sound && sound._node) {
-            sound._node.removeEventListener('ended', self._endTimers[id], false);
-          }
-        }
-
-        delete self._endTimers[id];
-      }
-
-      return self;
-    },
-
-    /**
-     * Return the sound identified by this ID, or return null.
-     * @param  {Number} id Sound ID
-     * @return {Object}    Sound object or null.
-     */
-    _soundById: function(id) {
-      var self = this;
-
-      // Loop through all sounds and find the one with this ID.
-      for (var i=0; i=0; i--) {
-        if (cnt <= limit) {
-          return;
-        }
-
-        if (self._sounds[i]._ended) {
-          // Disconnect the audio source when using Web Audio.
-          if (self._webAudio && self._sounds[i]._node) {
-            self._sounds[i]._node.disconnect(0);
-          }
-
-          // Remove sounds until we have the pool size.
-          self._sounds.splice(i, 1);
-          cnt--;
-        }
-      }
-    },
-
-    /**
-     * Get all ID's from the sounds pool.
-     * @param  {Number} id Only return one ID if one is passed.
-     * @return {Array}    Array of IDs.
-     */
-    _getSoundIds: function(id) {
-      var self = this;
-
-      if (typeof id === 'undefined') {
-        var ids = [];
-        for (var i=0; i= 0;
-
-      if (Howler._scratchBuffer && node.bufferSource) {
-        node.bufferSource.onended = null;
-        node.bufferSource.disconnect(0);
-        if (isIOS) {
-          try { node.bufferSource.buffer = Howler._scratchBuffer; } catch(e) {}
-        }
-      }
-      node.bufferSource = null;
-
-      return self;
-    },
-
-    /**
-     * Set the source to a 0-second silence to stop any downloading (except in IE).
-     * @param  {Object} node Audio node to clear.
-     */
-    _clearSound: function(node) {
-      var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
-      if (!checkIE) {
-        node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
-      }
-    }
-  };
-
-  /** Single Sound Methods **/
-  /***************************************************************************/
-
-  /**
-   * Setup the sound object, which each node attached to a Howl group is contained in.
-   * @param {Object} howl The Howl parent group.
-   */
-  var Sound = function(howl) {
-    this._parent = howl;
-    this.init();
-  };
-  Sound.prototype = {
-    /**
-     * Initialize a new Sound object.
-     * @return {Sound}
-     */
-    init: function() {
-      var self = this;
-      var parent = self._parent;
-
-      // Setup the default parameters.
-      self._muted = parent._muted;
-      self._loop = parent._loop;
-      self._volume = parent._volume;
-      self._rate = parent._rate;
-      self._seek = 0;
-      self._paused = true;
-      self._ended = true;
-      self._sprite = '__default';
-
-      // Generate a unique ID for this sound.
-      self._id = ++Howler._counter;
-
-      // Add itself to the parent's pool.
-      parent._sounds.push(self);
-
-      // Create the new node.
-      self.create();
-
-      return self;
-    },
-
-    /**
-     * Create and setup a new sound object, whether HTML5 Audio or Web Audio.
-     * @return {Sound}
-     */
-    create: function() {
-      var self = this;
-      var parent = self._parent;
-      var volume = (Howler._muted || self._muted || self._parent._muted) ? 0 : self._volume;
-
-      if (parent._webAudio) {
-        // Create the gain node for controlling volume (the source will connect to this).
-        self._node = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
-        self._node.gain.setValueAtTime(volume, Howler.ctx.currentTime);
-        self._node.paused = true;
-        self._node.connect(Howler.masterGain);
-      } else {
-        // Get an unlocked Audio object from the pool.
-        self._node = Howler._obtainHtml5Audio();
-
-        // Listen for errors (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror).
-        self._errorFn = self._errorListener.bind(self);
-        self._node.addEventListener('error', self._errorFn, false);
-
-        // Listen for 'canplaythrough' event to let us know the sound is ready.
-        self._loadFn = self._loadListener.bind(self);
-        self._node.addEventListener(Howler._canPlayEvent, self._loadFn, false);
-
-        // Setup the new audio node.
-        self._node.src = parent._src;
-        self._node.preload = 'auto';
-        self._node.volume = volume * Howler.volume();
-
-        // Begin loading the source.
-        self._node.load();
-      }
-
-      return self;
-    },
-
-    /**
-     * Reset the parameters of this sound to the original state (for recycle).
-     * @return {Sound}
-     */
-    reset: function() {
-      var self = this;
-      var parent = self._parent;
-
-      // Reset all of the parameters of this sound.
-      self._muted = parent._muted;
-      self._loop = parent._loop;
-      self._volume = parent._volume;
-      self._rate = parent._rate;
-      self._seek = 0;
-      self._rateSeek = 0;
-      self._paused = true;
-      self._ended = true;
-      self._sprite = '__default';
-
-      // Generate a new ID so that it isn't confused with the previous sound.
-      self._id = ++Howler._counter;
-
-      return self;
-    },
-
-    /**
-     * HTML5 Audio error listener callback.
-     */
-    _errorListener: function() {
-      var self = this;
-
-      // Fire an error event and pass back the code.
-      self._parent._emit('loaderror', self._id, self._node.error ? self._node.error.code : 0);
-
-      // Clear the event listener.
-      self._node.removeEventListener('error', self._errorFn, false);
-    },
-
-    /**
-     * HTML5 Audio canplaythrough listener callback.
-     */
-    _loadListener: function() {
-      var self = this;
-      var parent = self._parent;
-
-      // Round up the duration to account for the lower precision in HTML5 Audio.
-      parent._duration = Math.ceil(self._node.duration * 10) / 10;
-
-      // Setup a sprite if none is defined.
-      if (Object.keys(parent._sprite).length === 0) {
-        parent._sprite = {__default: [0, parent._duration * 1000]};
-      }
-
-      if (parent._state !== 'loaded') {
-        parent._state = 'loaded';
-        parent._emit('load');
-        parent._loadQueue();
-      }
-
-      // Clear the event listener.
-      self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
-    }
-  };
-
-  /** Helper Methods **/
-  /***************************************************************************/
-
-  var cache = {};
-
-  /**
-   * Buffer a sound from URL, Data URI or cache and decode to audio source (Web Audio API).
-   * @param  {Howl} self
-   */
-  var loadBuffer = function(self) {
-    var url = self._src;
-
-    // Check if the buffer has already been cached and use it instead.
-    if (cache[url]) {
-      // Set the duration from the cache.
-      self._duration = cache[url].duration;
-
-      // Load the sound into this Howl.
-      loadSound(self);
-
-      return;
-    }
-
-    if (/^data:[^;]+;base64,/.test(url)) {
-      // Decode the base64 data URI without XHR, since some browsers don't support it.
-      var data = atob(url.split(',')[1]);
-      var dataView = new Uint8Array(data.length);
-      for (var i=0; i 0) {
-        cache[self._src] = buffer;
-        loadSound(self, buffer);
-      } else {
-        error();
-      }
-    };
-
-    // Decode the buffer into an audio source.
-    if (typeof Promise !== 'undefined' && Howler.ctx.decodeAudioData.length === 1) {
-      Howler.ctx.decodeAudioData(arraybuffer).then(success).catch(error);
-    } else {
-      Howler.ctx.decodeAudioData(arraybuffer, success, error);
-    }
-  }
-
-  /**
-   * Sound is now loaded, so finish setting everything up and fire the loaded event.
-   * @param  {Howl} self
-   * @param  {Object} buffer The decoded buffer sound source.
-   */
-  var loadSound = function(self, buffer) {
-    // Set the duration.
-    if (buffer && !self._duration) {
-      self._duration = buffer.duration;
-    }
-
-    // Setup a sprite if none is defined.
-    if (Object.keys(self._sprite).length === 0) {
-      self._sprite = {__default: [0, self._duration * 1000]};
-    }
-
-    // Fire the loaded event.
-    if (self._state !== 'loaded') {
-      self._state = 'loaded';
-      self._emit('load');
-      self._loadQueue();
-    }
-  };
-
-  /**
-   * Setup the audio context when available, or switch to HTML5 Audio mode.
-   */
-  var setupAudioContext = function() {
-    // If we have already detected that Web Audio isn't supported, don't run this step again.
-    if (!Howler.usingWebAudio) {
-      return;
-    }
-
-    // Check if we are using Web Audio and setup the AudioContext if we are.
-    try {
-      if (typeof AudioContext !== 'undefined') {
-        Howler.ctx = new AudioContext();
-      } else if (typeof webkitAudioContext !== 'undefined') {
-        Howler.ctx = new webkitAudioContext();
-      } else {
-        Howler.usingWebAudio = false;
-      }
-    } catch(e) {
-      Howler.usingWebAudio = false;
-    }
-
-    // If the audio context creation still failed, set using web audio to false.
-    if (!Howler.ctx) {
-      Howler.usingWebAudio = false;
-    }
-
-    // Check if a webview is being used on iOS8 or earlier (rather than the browser).
-    // If it is, disable Web Audio as it causes crashing.
-    var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform));
-    var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
-    var version = appVersion ? parseInt(appVersion[1], 10) : null;
-    if (iOS && version && version < 9) {
-      var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase());
-      if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) {
-        Howler.usingWebAudio = false;
-      }
-    }
-
-    // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage).
-    if (Howler.usingWebAudio) {
-      Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain();
-      Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime);
-      Howler.masterGain.connect(Howler.ctx.destination);
-    }
-
-    // Re-run the setup on Howler.
-    Howler._setup();
-  };
-
-  // Add support for AMD (Asynchronous Module Definition) libraries such as require.js.
-  if (typeof define === 'function' && define.amd) {
-    define([], function() {
-      return {
-        Howler: Howler,
-        Howl: Howl
-      };
-    });
-  }
-
-  // Add support for CommonJS libraries such as browserify.
-  if (typeof exports !== 'undefined') {
-    exports.Howler = Howler;
-    exports.Howl = Howl;
-  }
-
-  // Define globally in case AMD is not available or unused.
-  if (typeof window !== 'undefined') {
-    window.HowlerGlobal = HowlerGlobal;
-    window.Howler = Howler;
-    window.Howl = Howl;
-    window.Sound = Sound;
-  } else if (typeof global !== 'undefined') { // Add to global in Node.js (for testing, etc).
-    global.HowlerGlobal = HowlerGlobal;
-    global.Howler = Howler;
-    global.Howl = Howl;
-    global.Sound = Sound;
-  }
-})();
-
-
-/*!
- *  Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported.
- *  
- *  howler.js v2.1.2
- *  howlerjs.com
- *
- *  (c) 2013-2019, James Simpson of GoldFire Studios
- *  goldfirestudios.com
- *
- *  MIT License
- */
-
-(function() {
-
-  'use strict';
-
-  // Setup default properties.
-  HowlerGlobal.prototype._pos = [0, 0, 0];
-  HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0];
-
-  /** Global Methods **/
-  /***************************************************************************/
-
-  /**
-   * Helper method to update the stereo panning position of all current Howls.
-   * Future Howls will not use this value unless explicitly set.
-   * @param  {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right.
-   * @return {Howler/Number}     Self or current stereo panning value.
-   */
-  HowlerGlobal.prototype.stereo = function(pan) {
-    var self = this;
-
-    // Stop right here if not using Web Audio.
-    if (!self.ctx || !self.ctx.listener) {
-      return self;
-    }
-
-    // Loop through all Howls and update their stereo panning.
-    for (var i=self._howls.length-1; i>=0; i--) {
-      self._howls[i].stereo(pan);
-    }
-
-    return self;
-  };
-
-  /**
-   * Get/set the position of the listener in 3D cartesian space. Sounds using
-   * 3D position will be relative to the listener's position.
-   * @param  {Number} x The x-position of the listener.
-   * @param  {Number} y The y-position of the listener.
-   * @param  {Number} z The z-position of the listener.
-   * @return {Howler/Array}   Self or current listener position.
-   */
-  HowlerGlobal.prototype.pos = function(x, y, z) {
-    var self = this;
-
-    // Stop right here if not using Web Audio.
-    if (!self.ctx || !self.ctx.listener) {
-      return self;
-    }
-
-    // Set the defaults for optional 'y' & 'z'.
-    y = (typeof y !== 'number') ? self._pos[1] : y;
-    z = (typeof z !== 'number') ? self._pos[2] : z;
-
-    if (typeof x === 'number') {
-      self._pos = [x, y, z];
-
-      if (typeof self.ctx.listener.positionX !== 'undefined') {
-        self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1);
-      } else {
-        self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]);
-      }
-    } else {
-      return self._pos;
-    }
-
-    return self;
-  };
-
-  /**
-   * Get/set the direction the listener is pointing in the 3D cartesian space.
-   * A front and up vector must be provided. The front is the direction the
-   * face of the listener is pointing, and up is the direction the top of the
-   * listener is pointing. Thus, these values are expected to be at right angles
-   * from each other.
-   * @param  {Number} x   The x-orientation of the listener.
-   * @param  {Number} y   The y-orientation of the listener.
-   * @param  {Number} z   The z-orientation of the listener.
-   * @param  {Number} xUp The x-orientation of the top of the listener.
-   * @param  {Number} yUp The y-orientation of the top of the listener.
-   * @param  {Number} zUp The z-orientation of the top of the listener.
-   * @return {Howler/Array}     Returns self or the current orientation vectors.
-   */
-  HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) {
-    var self = this;
-
-    // Stop right here if not using Web Audio.
-    if (!self.ctx || !self.ctx.listener) {
-      return self;
-    }
-
-    // Set the defaults for optional 'y' & 'z'.
-    var or = self._orientation;
-    y = (typeof y !== 'number') ? or[1] : y;
-    z = (typeof z !== 'number') ? or[2] : z;
-    xUp = (typeof xUp !== 'number') ? or[3] : xUp;
-    yUp = (typeof yUp !== 'number') ? or[4] : yUp;
-    zUp = (typeof zUp !== 'number') ? or[5] : zUp;
-
-    if (typeof x === 'number') {
-      self._orientation = [x, y, z, xUp, yUp, zUp];
-
-      if (typeof self.ctx.listener.forwardX !== 'undefined') {
-        self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.upX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.upY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1);
-        self.ctx.listener.upZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1);
-      } else {
-        self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp);
-      }
-    } else {
-      return or;
-    }
-
-    return self;
-  };
-
-  /** Group Methods **/
-  /***************************************************************************/
-
-  /**
-   * Add new properties to the core init.
-   * @param  {Function} _super Core init method.
-   * @return {Howl}
-   */
-  Howl.prototype.init = (function(_super) {
-    return function(o) {
-      var self = this;
-
-      // Setup user-defined default properties.
-      self._orientation = o.orientation || [1, 0, 0];
-      self._stereo = o.stereo || null;
-      self._pos = o.pos || null;
-      self._pannerAttr = {
-        coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360,
-        coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360,
-        coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0,
-        distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse',
-        maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000,
-        panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF',
-        refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1,
-        rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1
-      };
-
-      // Setup event listeners.
-      self._onstereo = o.onstereo ? [{fn: o.onstereo}] : [];
-      self._onpos = o.onpos ? [{fn: o.onpos}] : [];
-      self._onorientation = o.onorientation ? [{fn: o.onorientation}] : [];
-
-      // Complete initilization with howler.js core's init function.
-      return _super.call(this, o);
-    };
-  })(Howl.prototype.init);
-
-  /**
-   * Get/set the stereo panning of the audio source for this sound or all in the group.
-   * @param  {Number} pan  A value of -1.0 is all the way left and 1.0 is all the way right.
-   * @param  {Number} id (optional) The sound ID. If none is passed, all in group will be updated.
-   * @return {Howl/Number}    Returns self or the current stereo panning value.
-   */
-  Howl.prototype.stereo = function(pan, id) {
-    var self = this;
-
-    // Stop right here if not using Web Audio.
-    if (!self._webAudio) {
-      return self;
-    }
-
-    // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable.
-    if (self._state !== 'loaded') {
-      self._queue.push({
-        event: 'stereo',
-        action: function() {
-          self.stereo(pan, id);
-        }
-      });
-
-      return self;
-    }
-
-    // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist.
-    var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo';
-
-    // Setup the group's stereo panning if no ID is passed.
-    if (typeof id === 'undefined') {
-      // Return the group's stereo panning if no parameters are passed.
-      if (typeof pan === 'number') {
-        self._stereo = pan;
-        self._pos = [pan, 0, 0];
-      } else {
-        return self._stereo;
-      }
-    }
-
-    // Change the streo panning of one or all sounds in group.
-    var ids = self._getSoundIds(id);
-    for (var i=0; i Returns the group's values.
-   *   pannerAttr(id) -> Returns the sound id's values.
-   *   pannerAttr(o) -> Set's the values of all sounds in this Howl group.
-   *   pannerAttr(o, id) -> Set's the values of passed sound id.
-   *
-   *   Attributes:
-   *     coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
-   *                      inside of which there will be no volume reduction.
-   *     coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees,
-   *                      outside of which the volume will be reduced to a constant value of `coneOuterGain`.
-   *     coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the
-   *                     `coneOuterAngle`. It is a linear value in the range `[0, 1]`.
-   *     distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from
-   *                     listener. Can be `linear`, `inverse` or `exponential.
-   *     maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume
-   *                   will not be reduced any further.
-   *     refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener.
-   *                   This is simply a variable of the distance model and has a different effect depending on which model
-   *                   is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance.
-   *     rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a
-   *                     variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]`
-   *                     with `inverse` and `exponential`.
-   *     panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio.
-   *                     Can be `HRTF` or `equalpower`.
-   *
-   * @return {Howl/Object} Returns self or current panner attributes.
-   */
-  Howl.prototype.pannerAttr = function() {
-    var self = this;
-    var args = arguments;
-    var o, id, sound;
-
-    // Stop right here if not using Web Audio.
-    if (!self._webAudio) {
-      return self;
-    }
-
-    // Determine the values based on arguments.
-    if (args.length === 0) {
-      // Return the group's panner attribute values.
-      return self._pannerAttr;
-    } else if (args.length === 1) {
-      if (typeof args[0] === 'object') {
-        o = args[0];
-
-        // Set the grou's panner attribute values.
-        if (typeof id === 'undefined') {
-          if (!o.pannerAttr) {
-            o.pannerAttr = {
-              coneInnerAngle: o.coneInnerAngle,
-              coneOuterAngle: o.coneOuterAngle,
-              coneOuterGain: o.coneOuterGain,
-              distanceModel: o.distanceModel,
-              maxDistance: o.maxDistance,
-              refDistance: o.refDistance,
-              rolloffFactor: o.rolloffFactor,
-              panningModel: o.panningModel
-            };
-          }
-
-          self._pannerAttr = {
-            coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle,
-            coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle,
-            coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain,
-            distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel,
-            maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance,
-            refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance,
-            rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor,
-            panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel
-          };
-        }
-      } else {
-        // Return this sound's panner attribute values.
-        sound = self._soundById(parseInt(args[0], 10));
-        return sound ? sound._pannerAttr : self._pannerAttr;
-      }
-    } else if (args.length === 2) {
-      o = args[0];
-      id = parseInt(args[1], 10);
-    }
-
-    // Update the values of the specified sounds.
-    var ids = self._getSoundIds(id);
-    for (var i=0; i
- * Released under the MIT License.
- * https://raw.github.com/taye/interact.js/master/LICENSE
- */
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.interact = f()}})(function(){var define,module,exports;
-var createModuleFactory = function createModuleFactory(t){var e;return function(r){return e||t(e={exports:{},parent:r},e.exports),e.exports}};
-var _$scope_24 = createModuleFactory(function (module, exports) {
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
-  value: true
-});
-/* common-shake removed: exports.createScope = */ void createScope;
-/* common-shake removed: exports.initScope = */ void initScope;
-exports.Scope = exports.ActionName = void 0;
-
-var utils = _interopRequireWildcard(_$utils_56);
-
-var _domObjects = _interopRequireDefault(_$domObjects_50);
-
-var _defaultOptions = _interopRequireDefault(_$defaultOptions_20);
-
-var _Eventable = _interopRequireDefault(_$Eventable_14);
-
-var _Interactable = _interopRequireDefault(_$Interactable_16);
-
-var _InteractableSet = _interopRequireDefault(_$InteractableSet_17);
-
-var _InteractEvent = _interopRequireDefault(_$InteractEvent_15);
-
-var _interactions = _interopRequireDefault(_$interactions_23({}));
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
-
-function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-
-var win = utils.win,
-    browser = utils.browser,
-    raf = utils.raf,
-    Signals = utils.Signals,
-    events = utils.events;
-var ActionName;
-exports.ActionName = ActionName;
-
-(function (ActionName) {})(ActionName || (exports.ActionName = ActionName = {}));
-
-function createScope() {
-  return new Scope();
-}
-
-var Scope =
-/*#__PURE__*/
-function () {
-  function Scope() {
-    var _this = this;
-
-    _classCallCheck(this, Scope);
-
-    this.id = "__interact_scope_".concat(Math.floor(Math.random() * 100));
-    this.signals = new Signals();
-    this.browser = browser;
-    this.events = events;
-    this.utils = utils;
-    this.defaults = utils.clone(_defaultOptions["default"]);
-    this.Eventable = _Eventable["default"];
-    this.actions = {
-      names: [],
-      methodDict: {},
-      eventTypes: []
-    };
-    this.InteractEvent = _InteractEvent["default"];
-    this.interactables = new _InteractableSet["default"](this); // all documents being listened to
-
-    this.documents = [];
-    this._plugins = [];
-    this._pluginMap = {};
-
-    this.onWindowUnload = function (event) {
-      return _this.removeDocument(event.target);
-    };
-
-    var scope = this;
-
-    this.Interactable =
-    /*#__PURE__*/
-    function (_InteractableBase) {
-      _inherits(Interactable, _InteractableBase);
-
-      function Interactable() {
-        _classCallCheck(this, Interactable);
-
-        return _possibleConstructorReturn(this, _getPrototypeOf(Interactable).apply(this, arguments));
-      }
-
-      _createClass(Interactable, [{
-        key: "set",
-        value: function set(options) {
-          _get(_getPrototypeOf(Interactable.prototype), "set", this).call(this, options);
-
-          scope.interactables.signals.fire('set', {
-            options: options,
-            interactable: this
-          });
-          return this;
-        }
-      }, {
-        key: "unset",
-        value: function unset() {
-          _get(_getPrototypeOf(Interactable.prototype), "unset", this).call(this);
-
-          for (var i = scope.interactions.list.length - 1; i >= 0; i--) {
-            var interaction = scope.interactions.list[i];
-
-            if (interaction.interactable === this) {
-              interaction.stop();
-              scope.interactions.signals.fire('destroy', {
-                interaction: interaction
-              });
-              interaction.destroy();
-
-              if (scope.interactions.list.length > 2) {
-                scope.interactions.list.splice(i, 1);
-              }
-            }
-          }
-
-          scope.interactables.signals.fire('unset', {
-            interactable: this
-          });
-        }
-      }, {
-        key: "_defaults",
-        get: function get() {
-          return scope.defaults;
-        }
-      }]);
-
-      return Interactable;
-    }(_Interactable["default"]);
-  }
-
-  _createClass(Scope, [{
-    key: "init",
-    value: function init(window) {
-      return initScope(this, window);
-    }
-  }, {
-    key: "pluginIsInstalled",
-    value: function pluginIsInstalled(plugin) {
-      return this._pluginMap[plugin.id] || this._plugins.indexOf(plugin) !== -1;
-    }
-  }, {
-    key: "usePlugin",
-    value: function usePlugin(plugin, options) {
-      if (this.pluginIsInstalled(plugin)) {
-        return this;
-      }
-
-      if (plugin.id) {
-        this._pluginMap[plugin.id] = plugin;
-      }
-
-      plugin.install(this, options);
-
-      this._plugins.push(plugin);
-
-      return this;
-    }
-  }, {
-    key: "addDocument",
-    value: function addDocument(doc, options) {
-      // do nothing if document is already known
-      if (this.getDocIndex(doc) !== -1) {
-        return false;
-      }
-
-      var window = win.getWindow(doc);
-      options = options ? utils.extend({}, options) : {};
-      this.documents.push({
-        doc: doc,
-        options: options
-      });
-      events.documents.push(doc); // don't add an unload event for the main document
-      // so that the page may be cached in browser history
-
-      if (doc !== this.document) {
-        events.add(window, 'unload', this.onWindowUnload);
-      }
-
-      this.signals.fire('add-document', {
-        doc: doc,
-        window: window,
-        scope: this,
-        options: options
-      });
-    }
-  }, {
-    key: "removeDocument",
-    value: function removeDocument(doc) {
-      var index = this.getDocIndex(doc);
-      var window = win.getWindow(doc);
-      var options = this.documents[index].options;
-      events.remove(window, 'unload', this.onWindowUnload);
-      this.documents.splice(index, 1);
-      events.documents.splice(index, 1);
-      this.signals.fire('remove-document', {
-        doc: doc,
-        window: window,
-        scope: this,
-        options: options
-      });
-    }
-  }, {
-    key: "getDocIndex",
-    value: function getDocIndex(doc) {
-      for (var i = 0; i < this.documents.length; i++) {
-        if (this.documents[i].doc === doc) {
-          return i;
-        }
-      }
-
-      return -1;
-    }
-  }, {
-    key: "getDocOptions",
-    value: function getDocOptions(doc) {
-      var docIndex = this.getDocIndex(doc);
-      return docIndex === -1 ? null : this.documents[docIndex].options;
-    }
-  }, {
-    key: "now",
-    value: function now() {
-      return (this.window.Date || Date).now();
-    }
-  }]);
-
-  return Scope;
-}();
-
-exports.Scope = Scope;
-
-function initScope(scope, window) {
-  win.init(window);
-
-  _domObjects["default"].init(window);
-
-  browser.init(window);
-  raf.init(window);
-  events.init(window);
-  scope.usePlugin(_interactions["default"]);
-  scope.document = window.document;
-  scope.window = window;
-  return scope;
-}
-
-});
-var _$interactions_23 = createModuleFactory(function (module, exports) {
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
-  value: true
-});
-exports["default"] = void 0;
-
-var _browser = _interopRequireDefault(_$browser_48);
-
-var _domObjects = _interopRequireDefault(_$domObjects_50);
-
-/* removed: var _$domUtils_51 = require("@interactjs/utils/domUtils"); */;
-
-var _events = _interopRequireDefault(_$events_52);
-
-var _pointerUtils = _interopRequireDefault(_$pointerUtils_61);
-
-var _Signals = _interopRequireDefault(_$Signals_46);
-
-var _Interaction = _interopRequireDefault(_$Interaction_18({}));
-
-var _interactionFinder = _interopRequireDefault(_$interactionFinder_22);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-
-function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
-
-function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
-
-function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
-
-function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-var methodNames = ['pointerDown', 'pointerMove', 'pointerUp', 'updatePointer', 'removePointer', 'windowBlur'];
-
-function install(scope) {
-  var signals = new _Signals["default"]();
-  var listeners = {};
-
-  for (var _i = 0; _i < methodNames.length; _i++) {
-    var method = methodNames[_i];
-    listeners[method] = doOnInteractions(method, scope);
-  }
-
-  var pEventTypes = _browser["default"].pEventTypes;
-  var docEvents;
-
-  if (_domObjects["default"].PointerEvent) {
-    docEvents = [{
-      type: pEventTypes.down,
-      listener: releasePointersOnRemovedEls
-    }, {
-      type: pEventTypes.down,
-      listener: listeners.pointerDown
-    }, {
-      type: pEventTypes.move,
-      listener: listeners.pointerMove
-    }, {
-      type: pEventTypes.up,
-      listener: listeners.pointerUp
-    }, {
-      type: pEventTypes.cancel,
-      listener: listeners.pointerUp
-    }];
-  } else {
-    docEvents = [{
-      type: 'mousedown',
-      listener: listeners.pointerDown
-    }, {
-      type: 'mousemove',
-      listener: listeners.pointerMove
-    }, {
-      type: 'mouseup',
-      listener: listeners.pointerUp
-    }, {
-      type: 'touchstart',
-      listener: releasePointersOnRemovedEls
-    }, {
-      type: 'touchstart',
-      listener: listeners.pointerDown
-    }, {
-      type: 'touchmove',
-      listener: listeners.pointerMove
-    }, {
-      type: 'touchend',
-      listener: listeners.pointerUp
-    }, {
-      type: 'touchcancel',
-      listener: listeners.pointerUp
-    }];
-  }
-
-  docEvents.push({
-    type: 'blur',
-    listener: function listener(event) {
-      for (var _i2 = 0; _i2 < scope.interactions.list.length; _i2++) {
-        var _ref;
-
-        _ref = scope.interactions.list[_i2];
-        var interaction = _ref;
-        interaction.documentBlur(event);
-      }
-    }
-  });
-  scope.signals.on('add-document', onDocSignal);
-  scope.signals.on('remove-document', onDocSignal); // for ignoring browser's simulated mouse events
-
-  scope.prevTouchTime = 0;
-
-  scope.Interaction =
-  /*#__PURE__*/
-  function (_InteractionBase) {
-    _inherits(Interaction, _InteractionBase);
-
-    function Interaction() {
-      _classCallCheck(this, Interaction);
-
-      return _possibleConstructorReturn(this, _getPrototypeOf(Interaction).apply(this, arguments));
-    }
-
-    _createClass(Interaction, [{
-      key: "_now",
-      value: function _now() {
-        return scope.now();
-      }
-    }, {
-      key: "pointerMoveTolerance",
-      get: function get() {
-        return scope.interactions.pointerMoveTolerance;
-      },
-      set: function set(value) {
-        scope.interactions.pointerMoveTolerance = value;
-      }
-    }]);
-
-    return Interaction;
-  }(_Interaction["default"]);
-
-  scope.interactions = {
-    signals: signals,
-    // all active and idle interactions
-    list: [],
-    "new": function _new(options) {
-      options.signals = signals;
-      var interaction = new scope.Interaction(options);
-      scope.interactions.list.push(interaction);
-      return interaction;
-    },
-    listeners: listeners,
-    docEvents: docEvents,
-    pointerMoveTolerance: 1
-  };
-
-  function releasePointersOnRemovedEls() {
-    // for all inactive touch interactions with pointers down
-    for (var _i3 = 0; _i3 < scope.interactions.list.length; _i3++) {
-      var _ref2;
-
-      _ref2 = scope.interactions.list[_i3];
-      var interaction = _ref2;
-
-      if (!interaction.pointerIsDown || interaction.pointerType !== 'touch' || interaction._interacting) {
-        continue;
-      } // if a pointer is down on an element that is no longer in the DOM tree
-
-
-      var _loop = function _loop() {
-        _ref3 = interaction.pointers[_i4];
-        var pointer = _ref3;
-
-        if (!scope.documents.some(function (_ref4) {
-          var doc = _ref4.doc;
-          return (0, _$domUtils_51.nodeContains)(doc, pointer.downTarget);
-        })) {
-          // remove the pointer from the interaction
-          interaction.removePointer(pointer.pointer, pointer.event);
-        }
-      };
-
-      for (var _i4 = 0; _i4 < interaction.pointers.length; _i4++) {
-        var _ref3;
-
-        _loop();
-      }
-    }
-  }
-}
-
-function doOnInteractions(method, scope) {
-  return function (event) {
-    var interactions = scope.interactions.list;
-
-    var pointerType = _pointerUtils["default"].getPointerType(event);
-
-    var _pointerUtils$getEven = _pointerUtils["default"].getEventTargets(event),
-        _pointerUtils$getEven2 = _slicedToArray(_pointerUtils$getEven, 2),
-        eventTarget = _pointerUtils$getEven2[0],
-        curEventTarget = _pointerUtils$getEven2[1];
-
-    var matches = []; // [ [pointer, interaction], ...]
-
-    if (/^touch/.test(event.type)) {
-      scope.prevTouchTime = scope.now();
-
-      for (var _i5 = 0; _i5 < event.changedTouches.length; _i5++) {
-        var _ref5;
-
-        _ref5 = event.changedTouches[_i5];
-        var changedTouch = _ref5;
-        var pointer = changedTouch;
-
-        var pointerId = _pointerUtils["default"].getPointerId(pointer);
-
-        var searchDetails = {
-          pointer: pointer,
-          pointerId: pointerId,
-          pointerType: pointerType,
-          eventType: event.type,
-          eventTarget: eventTarget,
-          curEventTarget: curEventTarget,
-          scope: scope
-        };
-        var interaction = getInteraction(searchDetails);
-        matches.push([searchDetails.pointer, searchDetails.eventTarget, searchDetails.curEventTarget, interaction]);
-      }
-    } else {
-      var invalidPointer = false;
-
-      if (!_browser["default"].supportsPointerEvent && /mouse/.test(event.type)) {
-        // ignore mouse events while touch interactions are active
-        for (var i = 0; i < interactions.length && !invalidPointer; i++) {
-          invalidPointer = interactions[i].pointerType !== 'mouse' && interactions[i].pointerIsDown;
-        } // try to ignore mouse events that are simulated by the browser
-        // after a touch event
-
-
-        invalidPointer = invalidPointer || scope.now() - scope.prevTouchTime < 500 || // on iOS and Firefox Mobile, MouseEvent.timeStamp is zero if simulated
-        event.timeStamp === 0;
-      }
-
-      if (!invalidPointer) {
-        var _searchDetails = {
-          pointer: event,
-          pointerId: _pointerUtils["default"].getPointerId(event),
-          pointerType: pointerType,
-          eventType: event.type,
-          curEventTarget: curEventTarget,
-          eventTarget: eventTarget,
-          scope: scope
-        };
-
-        var _interaction = getInteraction(_searchDetails);
-
-        matches.push([_searchDetails.pointer, _searchDetails.eventTarget, _searchDetails.curEventTarget, _interaction]);
-      }
-    } // eslint-disable-next-line no-shadow
-
-
-    for (var _i6 = 0; _i6 < matches.length; _i6++) {
-      var _matches$_i = _slicedToArray(matches[_i6], 4),
-          _pointer = _matches$_i[0],
-          _eventTarget = _matches$_i[1],
-          _curEventTarget = _matches$_i[2],
-          _interaction2 = _matches$_i[3];
-
-      _interaction2[method](_pointer, event, _eventTarget, _curEventTarget);
-    }
-  };
-}
-
-function getInteraction(searchDetails) {
-  var pointerType = searchDetails.pointerType,
-      scope = searchDetails.scope;
-
-  var foundInteraction = _interactionFinder["default"].search(searchDetails);
-
-  var signalArg = {
-    interaction: foundInteraction,
-    searchDetails: searchDetails
-  };
-  scope.interactions.signals.fire('find', signalArg);
-  return signalArg.interaction || scope.interactions["new"]({
-    pointerType: pointerType
-  });
-}
-
-function onDocSignal(_ref6, signalName) {
-  var doc = _ref6.doc,
-      scope = _ref6.scope,
-      options = _ref6.options;
-  var docEvents = scope.interactions.docEvents;
-  var eventMethod = signalName.indexOf('add') === 0 ? _events["default"].add : _events["default"].remove;
-
-  if (scope.browser.isIOS && !options.events) {
-    options.events = {
-      passive: false
-    };
-  } // delegate event listener
-
-
-  for (var eventType in _events["default"].delegatedEvents) {
-    eventMethod(doc, eventType, _events["default"].delegateListener);
-    eventMethod(doc, eventType, _events["default"].delegateUseCapture, true);
-  }
-
-  var eventOptions = options && options.events;
-
-  for (var _i7 = 0; _i7 < docEvents.length; _i7++) {
-    var _ref7;
-
-    _ref7 = docEvents[_i7];
-    var _ref8 = _ref7,
-        type = _ref8.type,
-        listener = _ref8.listener;
-    eventMethod(doc, type, listener, eventOptions);
-  }
-}
-
-var _default = {
-  id: 'core/interactions',
-  install: install,
-  onDocSignal: onDocSignal,
-  doOnInteractions: doOnInteractions,
-  methodNames: methodNames
-};
-exports["default"] = _default;
-
-});
-var _$Interaction_18 = createModuleFactory(function (module, exports) {
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
-  value: true
-});
-Object.defineProperty(exports, "PointerInfo", {
-  enumerable: true,
-  get: function get() {
-    return _PointerInfo["default"];
-  }
-});
-exports["default"] = exports.Interaction = exports._ProxyMethods = exports._ProxyValues = void 0;
-
-var utils = _interopRequireWildcard(_$utils_56);
-
-var _InteractEvent = _interopRequireWildcard(_$InteractEvent_15);
-
-var _PointerInfo = _interopRequireDefault(_$PointerInfo_19);
-
-var _scope = _$scope_24({});
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-
-var _ProxyValues;
-
-exports._ProxyValues = _ProxyValues;
-
-(function (_ProxyValues) {
-  _ProxyValues["interactable"] = "";
-  _ProxyValues["element"] = "";
-  _ProxyValues["prepared"] = "";
-  _ProxyValues["pointerIsDown"] = "";
-  _ProxyValues["pointerWasMoved"] = "";
-  _ProxyValues["_proxy"] = "";
-})(_ProxyValues || (exports._ProxyValues = _ProxyValues = {}));
-
-var _ProxyMethods;
-
-exports._ProxyMethods = _ProxyMethods;
-
-(function (_ProxyMethods) {
-  _ProxyMethods["start"] = "";
-  _ProxyMethods["move"] = "";
-  _ProxyMethods["end"] = "";
-  _ProxyMethods["stop"] = "";
-  _ProxyMethods["interacting"] = "";
-})(_ProxyMethods || (exports._ProxyMethods = _ProxyMethods = {}));
-
-var Interaction =
-/*#__PURE__*/
-function () {
-  /** */
-  function Interaction(_ref) {
-    var _this = this;
-
-    var pointerType = _ref.pointerType,
-        signals = _ref.signals;
-
-    _classCallCheck(this, Interaction);
-
-    // current interactable being interacted with
-    this.interactable = null; // the target element of the interactable
-
-    this.element = null; // action that's ready to be fired on next move event
-
-    this.prepared = {
-      name: null,
-      axis: null,
-      edges: null
-    }; // keep track of added pointers
-
-    this.pointers = []; // pointerdown/mousedown/touchstart event
-
-    this.downEvent = null;
-    this.downPointer = {};
-    this._latestPointer = {
-      pointer: null,
-      event: null,
-      eventTarget: null
-    }; // previous action event
-
-    this.prevEvent = null;
-    this.pointerIsDown = false;
-    this.pointerWasMoved = false;
-    this._interacting = false;
-    this._ending = false;
-    this._stopped = true;
-    this._proxy = null;
-    this.simulation = null;
-    /**
-     * @alias Interaction.prototype.move
-     */
-
-    this.doMove = utils.warnOnce(function (signalArg) {
-      this.move(signalArg);
-    }, 'The interaction.doMove() method has been renamed to interaction.move()');
-    this.coords = {
-      // Starting InteractEvent pointer coordinates
-      start: utils.pointer.newCoords(),
-      // Previous native pointer move event coordinates
-      prev: utils.pointer.newCoords(),
-      // current native pointer move event coordinates
-      cur: utils.pointer.newCoords(),
-      // Change in coordinates and time of the pointer
-      delta: utils.pointer.newCoords(),
-      // pointer velocity
-      velocity: utils.pointer.newCoords()
-    };
-    this._signals = signals;
-    this.pointerType = pointerType;
-    var that = this;
-    this._proxy = {};
-
-    var _loop = function _loop(key) {
-      Object.defineProperty(_this._proxy, key, {
-        get: function get() {
-          return that[key];
-        }
-      });
-    };
-
-    for (var key in _ProxyValues) {
-      _loop(key);
-    }
-
-    var _loop2 = function _loop2(key) {
-      Object.defineProperty(_this._proxy, key, {
-        value: function value() {
-          return that[key].apply(that, arguments);
-        }
-      });
-    };
-
-    for (var key in _ProxyMethods) {
-      _loop2(key);
-    }
-
-    this._signals.fire('new', {
-      interaction: this
-    });
-  }
-
-  _createClass(Interaction, [{
-    key: "pointerDown",
-    value: function pointerDown(pointer, event, eventTarget) {
-      var pointerIndex = this.updatePointer(pointer, event, eventTarget, true);
-
-      this._signals.fire('down', {
-        pointer: pointer,
-        event: event,
-        eventTarget: eventTarget,
-        pointerIndex: pointerIndex,
-        interaction: this
-      });
-    }
-    /**
-     * ```js
-     * interact(target)
-     *   .draggable({
-     *     // disable the default drag start by down->move
-     *     manualStart: true
-     *   })
-     *   // start dragging after the user holds the pointer down
-     *   .on('hold', function (event) {
-     *     var interaction = event.interaction
-     *
-     *     if (!interaction.interacting()) {
-     *       interaction.start({ name: 'drag' },
-     *                         event.interactable,
-     *                         event.currentTarget)
-     *     }
-     * })
-     * ```
-     *
-     * Start an action with the given Interactable and Element as tartgets. The
-     * action must be enabled for the target Interactable and an appropriate
-     * number of pointers must be held down - 1 for drag/resize, 2 for gesture.
-     *
-     * Use it with `interactable.able({ manualStart: false })` to always
-     * [start actions manually](https://github.com/taye/interact.js/issues/114)
-     *
-     * @param {object} action   The action to be performed - drag, resize, etc.
-     * @param {Interactable} target  The Interactable to target
-     * @param {Element} element The DOM Element to target
-     * @return {object} interact
-     */
-
-  }, {
-    key: "start",
-    value: function start(action, interactable, element) {
-      if (this.interacting() || !this.pointerIsDown || this.pointers.length < (action.name === _scope.ActionName.Gesture ? 2 : 1) || !interactable.options[action.name].enabled) {
-        return false;
-      }
-
-      utils.copyAction(this.prepared, action);
-      this.interactable = interactable;
-      this.element = element;
-      this.rect = interactable.getRect(element);
-      this.edges = this.prepared.edges;
-      this._stopped = false;
-      this._interacting = this._doPhase({
-        interaction: this,
-        event: this.downEvent,
-        phase: _InteractEvent.EventPhase.Start
-      }) && !this._stopped;
-      return this._interacting;
-    }
-  }, {
-    key: "pointerMove",
-    value: function pointerMove(pointer, event, eventTarget) {
-      if (!this.simulation && !(this.modifiers && this.modifiers.endPrevented)) {
-        this.updatePointer(pointer, event, eventTarget, false);
-        utils.pointer.setCoords(this.coords.cur, this.pointers.map(function (p) {
-          return p.pointer;
-        }), this._now());
-      }
-
-      var duplicateMove = this.coords.cur.page.x === this.coords.prev.page.x && this.coords.cur.page.y === this.coords.prev.page.y && this.coords.cur.client.x === this.coords.prev.client.x && this.coords.cur.client.y === this.coords.prev.client.y;
-      var dx;
-      var dy; // register movement greater than pointerMoveTolerance
-
-      if (this.pointerIsDown && !this.pointerWasMoved) {
-        dx = this.coords.cur.client.x - this.coords.start.client.x;
-        dy = this.coords.cur.client.y - this.coords.start.client.y;
-        this.pointerWasMoved = utils.hypot(dx, dy) > this.pointerMoveTolerance;
-      }
-
-      var signalArg = {
-        pointer: pointer,
-        pointerIndex: this.getPointerIndex(pointer),
-        event: event,
-        eventTarget: eventTarget,
-        dx: dx,
-        dy: dy,
-        duplicate: duplicateMove,
-        interaction: this
-      };
-
-      if (!duplicateMove) {
-        // set pointer coordinate, time changes and velocity
-        utils.pointer.setCoordDeltas(this.coords.delta, this.coords.prev, this.coords.cur);
-        utils.pointer.setCoordVelocity(this.coords.velocity, this.coords.delta);
-      }
-
-      this._signals.fire('move', signalArg);
-
-      if (!duplicateMove) {
-        // if interacting, fire an 'action-move' signal etc
-        if (this.interacting()) {
-          this.move(signalArg);
-        }
-
-        if (this.pointerWasMoved) {
-          utils.pointer.copyCoords(this.coords.prev, this.coords.cur);
-        }
-      }
-    }
-    /**
-     * ```js
-     * interact(target)
-     *   .draggable(true)
-     *   .on('dragmove', function (event) {
-     *     if (someCondition) {
-     *       // change the snap settings
-     *       event.interactable.draggable({ snap: { targets: [] }})
-     *       // fire another move event with re-calculated snap
-     *       event.interaction.move()
-     *     }
-     *   })
-     * ```
-     *
-     * Force a move of the current action at the same coordinates. Useful if
-     * snap/restrict has been changed and you want a movement with the new
-     * settings.
-     */
-
-  }, {
-    key: "move",
-    value: function move(signalArg) {
-      signalArg = utils.extend({
-        pointer: this._latestPointer.pointer,
-        event: this._latestPointer.event,
-        eventTarget: this._latestPointer.eventTarget,
-        interaction: this
-      }, signalArg || {});
-      signalArg.phase = _InteractEvent.EventPhase.Move;
-
-      this._doPhase(signalArg);
-    } // End interact move events and stop auto-scroll unless simulation is running
-
-  }, {
-    key: "pointerUp",
-    value: function pointerUp(pointer, event, eventTarget, curEventTarget) {
-      var pointerIndex = this.getPointerIndex(pointer);
-
-      if (pointerIndex === -1) {
-        pointerIndex = this.updatePointer(pointer, event, eventTarget, false);
-      }
-
-      this._signals.fire(/cancel$/i.test(event.type) ? 'cancel' : 'up', {
-        pointer: pointer,
-        pointerIndex: pointerIndex,
-        event: event,
-        eventTarget: eventTarget,
-        curEventTarget: curEventTarget,
-        interaction: this
-      });
-
-      if (!this.simulation) {
-        this.end(event);
-      }
-
-      this.pointerIsDown = false;
-      this.removePointer(pointer, event);
-    }
-  }, {
-    key: "documentBlur",
-    value: function documentBlur(event) {
-      this.end(event);
-
-      this._signals.fire('blur', {
-        event: event,
-        interaction: this
-      });
-    }
-    /**
-     * ```js
-     * interact(target)
-     *   .draggable(true)
-     *   .on('move', function (event) {
-     *     if (event.pageX > 1000) {
-     *       // end the current action
-     *       event.interaction.end()
-     *       // stop all further listeners from being called
-     *       event.stopImmediatePropagation()
-     *     }
-     *   })
-     * ```
-     *
-     * @param {PointerEvent} [event]
-     */
-
-  }, {
-    key: "end",
-    value: function end(event) {
-      this._ending = true;
-      event = event || this._latestPointer.event;
-      var endPhaseResult;
-
-      if (this.interacting()) {
-        endPhaseResult = this._doPhase({
-          event: event,
-          interaction: this,
-          phase: _InteractEvent.EventPhase.End
-        });
-      }
-
-      this._ending = false;
-
-      if (endPhaseResult === true) {
-        this.stop();
-      }
-    }
-  }, {
-    key: "currentAction",
-    value: function currentAction() {
-      return this._interacting ? this.prepared.name : null;
-    }
-  }, {
-    key: "interacting",
-    value: function interacting() {
-      return this._interacting;
-    }
-    /** */
-
-  }, {
-    key: "stop",
-    value: function stop() {
-      this._signals.fire('stop', {
-        interaction: this
-      });
-
-      this.interactable = this.element = null;
-      this._interacting = false;
-      this._stopped = true;
-      this.prepared.name = this.prevEvent = null;
-    }
-  }, {
-    key: "getPointerIndex",
-    value: function getPointerIndex(pointer) {
-      var pointerId = utils.pointer.getPointerId(pointer); // mouse and pen interactions may have only one pointer
-
-      return this.pointerType === 'mouse' || this.pointerType === 'pen' ? this.pointers.length - 1 : utils.arr.findIndex(this.pointers, function (curPointer) {
-        return curPointer.id === pointerId;
-      });
-    }
-  }, {
-    key: "getPointerInfo",
-    value: function getPointerInfo(pointer) {
-      return this.pointers[this.getPointerIndex(pointer)];
-    }
-  }, {
-    key: "updatePointer",
-    value: function updatePointer(pointer, event, eventTarget, down) {
-      var id = utils.pointer.getPointerId(pointer);
-      var pointerIndex = this.getPointerIndex(pointer);
-      var pointerInfo = this.pointers[pointerIndex];
-      down = down === false ? false : down || /(down|start)$/i.test(event.type);
-
-      if (!pointerInfo) {
-        pointerInfo = new _PointerInfo["default"](id, pointer, event, null, null);
-        pointerIndex = this.pointers.length;
-        this.pointers.push(pointerInfo);
-      } else {
-        pointerInfo.pointer = pointer;
-      }
-
-      if (down) {
-        this.pointerIsDown = true;
-
-        if (!this.interacting()) {
-          utils.pointer.setCoords(this.coords.start, this.pointers.map(function (p) {
-            return p.pointer;
-          }), this._now());
-          utils.pointer.copyCoords(this.coords.cur, this.coords.start);
-          utils.pointer.copyCoords(this.coords.prev, this.coords.start);
-          utils.pointer.pointerExtend(this.downPointer, pointer);
-          this.downEvent = event;
-          pointerInfo.downTime = this.coords.cur.timeStamp;
-          pointerInfo.downTarget = eventTarget;
-          this.pointerWasMoved = false;
-        }
-      }
-
-      this._updateLatestPointer(pointer, event, eventTarget);
-
-      this._signals.fire('update-pointer', {
-        pointer: pointer,
-        event: event,
-        eventTarget: eventTarget,
-        down: down,
-        pointerInfo: pointerInfo,
-        pointerIndex: pointerIndex,
-        interaction: this
-      });
-
-      return pointerIndex;
-    }
-  }, {
-    key: "removePointer",
-    value: function removePointer(pointer, event) {
-      var pointerIndex = this.getPointerIndex(pointer);
-
-      if (pointerIndex === -1) {
-        return;
-      }
-
-      var pointerInfo = this.pointers[pointerIndex];
-
-      this._signals.fire('remove-pointer', {
-        pointer: pointer,
-        event: event,
-        pointerIndex: pointerIndex,
-        pointerInfo: pointerInfo,
-        interaction: this
-      });
-
-      this.pointers.splice(pointerIndex, 1);
-    }
-  }, {
-    key: "_updateLatestPointer",
-    value: function _updateLatestPointer(pointer, event, eventTarget) {
-      this._latestPointer.pointer = pointer;
-      this._latestPointer.event = event;
-      this._latestPointer.eventTarget = eventTarget;
-    }
-  }, {
-    key: "destroy",
-    value: function destroy() {
-      this._latestPointer.pointer = null;
-      this._latestPointer.event = null;
-      this._latestPointer.eventTarget = null;
-    }
-  }, {
-    key: "_createPreparedEvent",
-    value: function _createPreparedEvent(event, phase, preEnd, type) {
-      var actionName = this.prepared.name;
-      return new _InteractEvent["default"](this, event, actionName, phase, this.element, null, preEnd, type);
-    }
-  }, {
-    key: "_fireEvent",
-    value: function _fireEvent(iEvent) {
-      this.interactable.fire(iEvent);
-
-      if (!this.prevEvent || iEvent.timeStamp >= this.prevEvent.timeStamp) {
-        this.prevEvent = iEvent;
-      }
-    }
-  }, {
-    key: "_doPhase",
-    value: function _doPhase(signalArg) {
-      var event = signalArg.event,
-          phase = signalArg.phase,
-          preEnd = signalArg.preEnd,
-          type = signalArg.type;
-
-      var beforeResult = this._signals.fire("before-action-".concat(phase), signalArg);
-
-      if (beforeResult === false) {
-        return false;
-      }
-
-      var iEvent = signalArg.iEvent = this._createPreparedEvent(event, phase, preEnd, type);
-
-      var rect = this.rect;
-
-      if (rect) {
-        // update the rect modifications
-        var edges = this.edges || this.prepared.edges || {
-          left: true,
-          right: true,
-          top: true,
-          bottom: true
-        };
-
-        if (edges.top) {
-          rect.top += iEvent.delta.y;
-        }
-
-        if (edges.bottom) {
-          rect.bottom += iEvent.delta.y;
-        }
-
-        if (edges.left) {
-          rect.left += iEvent.delta.x;
-        }
-
-        if (edges.right) {
-          rect.right += iEvent.delta.x;
-        }
-
-        rect.width = rect.right - rect.left;
-        rect.height = rect.bottom - rect.top;
-      }
-
-      this._signals.fire("action-".concat(phase), signalArg);
-
-      this._fireEvent(iEvent);
-
-      this._signals.fire("after-action-".concat(phase), signalArg);
-
-      return true;
-    }
-  }, {
-    key: "_now",
-    value: function _now() {
-      return Date.now();
-    }
-  }, {
-    key: "pointerMoveTolerance",
-    get: function get() {
-      return 1;
-    }
-  }]);
-
-  return Interaction;
-}();
-
-exports.Interaction = Interaction;
-var _default = Interaction;
-exports["default"] = _default;
-
-});
-var _$arr_47 = {};
-"use strict";
-
-Object.defineProperty(_$arr_47, "__esModule", {
-  value: true
-});
-_$arr_47.contains = contains;
-_$arr_47.remove = remove;
-_$arr_47.merge = merge;
-_$arr_47.from = from;
-_$arr_47.findIndex = findIndex;
-_$arr_47.find = find;
-
-function contains(array, target) {
-  return array.indexOf(target) !== -1;
-}
-
-function remove(array, target) {
-  return array.splice(array.indexOf(target), 1);
-}
-
-function merge(target, source) {
-  for (var _i = 0; _i < source.length; _i++) {
-    var _ref;
-
-    _ref = source[_i];
-    var item = _ref;
-    target.push(item);
-  }
-
-  return target;
-}
-
-function from(source) {
-  return merge([], source);
-}
-
-function findIndex(array, func) {
-  for (var i = 0; i < array.length; i++) {
-    if (func(array[i], i, array)) {
-      return i;
-    }
-  }
-
-  return -1;
-}
-
-function find(array, func) {
-  return array[findIndex(array, func)];
-}
-
-var _$domObjects_50 = {};
-"use strict";
-
-Object.defineProperty(_$domObjects_50, "__esModule", {
-  value: true
-});
-_$domObjects_50["default"] = void 0;
-var domObjects = {
-  init: init,
-  document: null,
-  DocumentFragment: null,
-  SVGElement: null,
-  SVGSVGElement: null,
-  // eslint-disable-next-line no-undef
-  SVGElementInstance: null,
-  Element: null,
-  HTMLElement: null,
-  Event: null,
-  Touch: null,
-  PointerEvent: null
-};
-
-function blank() {}
-
-var _default = domObjects;
-_$domObjects_50["default"] = _default;
-
-function init(window) {
-  var win = window;
-  domObjects.document = win.document;
-  domObjects.DocumentFragment = win.DocumentFragment || blank;
-  domObjects.SVGElement = win.SVGElement || blank;
-  domObjects.SVGSVGElement = win.SVGSVGElement || blank;
-  domObjects.SVGElementInstance = win.SVGElementInstance || blank;
-  domObjects.Element = win.Element || blank;
-  domObjects.HTMLElement = win.HTMLElement || domObjects.Element;
-  domObjects.Event = win.Event;
-  domObjects.Touch = win.Touch || blank;
-  domObjects.PointerEvent = win.PointerEvent || win.MSPointerEvent;
-}
-
-var _$isWindow_58 = {};
-"use strict";
-
-Object.defineProperty(_$isWindow_58, "__esModule", {
-  value: true
-});
-_$isWindow_58["default"] = void 0;
-
-var ___default_58 = function _default(thing) {
-  return !!(thing && thing.Window) && thing instanceof thing.Window;
-};
-
-_$isWindow_58["default"] = ___default_58;
-
-var _$window_66 = {};
-"use strict";
-
-Object.defineProperty(_$window_66, "__esModule", {
-  value: true
-});
-_$window_66.init = __init_66;
-_$window_66.getWindow = getWindow;
-_$window_66["default"] = void 0;
-
-var _isWindow = _interopRequireDefault(_$isWindow_58);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var win = {
-  realWindow: undefined,
-  window: undefined,
-  getWindow: getWindow,
-  init: __init_66
-};
-
-function __init_66(window) {
-  // get wrapped window if using Shadow DOM polyfill
-  win.realWindow = window; // create a TextNode
-
-  var el = window.document.createTextNode(''); // check if it's wrapped by a polyfill
-
-  if (el.ownerDocument !== window.document && typeof window.wrap === 'function' && window.wrap(el) === el) {
-    // use wrapped window
-    window = window.wrap(window);
-  }
-
-  win.window = window;
-}
-
-if (typeof window === 'undefined') {
-  win.window = undefined;
-  win.realWindow = undefined;
-} else {
-  __init_66(window);
-}
-
-function getWindow(node) {
-  if ((0, _isWindow["default"])(node)) {
-    return node;
-  }
-
-  var rootNode = node.ownerDocument || node;
-  return rootNode.defaultView || win.window;
-}
-
-win.init = __init_66;
-var ___default_66 = win;
-_$window_66["default"] = ___default_66;
-
-var _$is_57 = {};
-"use strict";
-
-Object.defineProperty(_$is_57, "__esModule", {
-  value: true
-});
-_$is_57.array = _$is_57.plainObject = _$is_57.element = _$is_57.string = _$is_57.bool = _$is_57.number = _$is_57.func = _$is_57.object = _$is_57.docFrag = _$is_57.window = void 0;
-
-var ___isWindow_57 = ___interopRequireDefault_57(_$isWindow_58);
-
-var _window2 = ___interopRequireDefault_57(_$window_66);
-
-function ___interopRequireDefault_57(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
-
-var __window_57 = function window(thing) {
-  return thing === _window2["default"].window || (0, ___isWindow_57["default"])(thing);
-};
-
-_$is_57.window = __window_57;
-
-var docFrag = function docFrag(thing) {
-  return object(thing) && thing.nodeType === 11;
-};
-
-_$is_57.docFrag = docFrag;
-
-var object = function object(thing) {
-  return !!thing && _typeof(thing) === 'object';
-};
-
-_$is_57.object = object;
-
-var func = function func(thing) {
-  return typeof thing === 'function';
-};
-
-_$is_57.func = func;
-
-var number = function number(thing) {
-  return typeof thing === 'number';
-};
-
-_$is_57.number = number;
-
-var bool = function bool(thing) {
-  return typeof thing === 'boolean';
-};
-
-_$is_57.bool = bool;
-
-var string = function string(thing) {
-  return typeof thing === 'string';
-};
-
-_$is_57.string = string;
-
-var element = function element(thing) {
-  if (!thing || _typeof(thing) !== 'object') {
-    return false;
-  }
-
-  var _window = _window2["default"].getWindow(thing) || _window2["default"].window;
-
-  return /object|function/.test(_typeof(_window.Element)) ? thing instanceof _window.Element // DOM2
-  : thing.nodeType === 1 && typeof thing.nodeName === 'string';
-};
-
-_$is_57.element = element;
-
-var plainObject = function plainObject(thing) {
-  return object(thing) && !!thing.constructor && /function Object\b/.test(thing.constructor.toString());
-};
-
-_$is_57.plainObject = plainObject;
-
-var array = function array(thing) {
-  return object(thing) && typeof thing.length !== 'undefined' && func(thing.splice);
-};
-
-_$is_57.array = array;
-
-var _$browser_48 = {};
-"use strict";
-
-Object.defineProperty(_$browser_48, "__esModule", {
-  value: true
-});
-_$browser_48["default"] = void 0;
-
-var _domObjects = ___interopRequireDefault_48(_$domObjects_50);
-
-var is = _interopRequireWildcard(_$is_57);
-
-var _window = ___interopRequireDefault_48(_$window_66);
-
-function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_48(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var browser = {
-  init: __init_48,
-  supportsTouch: null,
-  supportsPointerEvent: null,
-  isIOS7: null,
-  isIOS: null,
-  isIe9: null,
-  isOperaMobile: null,
-  prefixedMatchesSelector: null,
-  pEventTypes: null,
-  wheelEvent: null
-};
-
-function __init_48(window) {
-  var Element = _domObjects["default"].Element;
-  var navigator = _window["default"].window.navigator; // Does the browser support touch input?
-
-  browser.supportsTouch = 'ontouchstart' in window || is.func(window.DocumentTouch) && _domObjects["default"].document instanceof window.DocumentTouch; // Does the browser support PointerEvents
-
-  browser.supportsPointerEvent = navigator.pointerEnabled !== false && !!_domObjects["default"].PointerEvent;
-  browser.isIOS = /iP(hone|od|ad)/.test(navigator.platform); // scrolling doesn't change the result of getClientRects on iOS 7
-
-  browser.isIOS7 = /iP(hone|od|ad)/.test(navigator.platform) && /OS 7[^\d]/.test(navigator.appVersion);
-  browser.isIe9 = /MSIE 9/.test(navigator.userAgent); // Opera Mobile must be handled differently
-
-  browser.isOperaMobile = navigator.appName === 'Opera' && browser.supportsTouch && /Presto/.test(navigator.userAgent); // prefix matchesSelector
-
-  browser.prefixedMatchesSelector = 'matches' in Element.prototype ? 'matches' : 'webkitMatchesSelector' in Element.prototype ? 'webkitMatchesSelector' : 'mozMatchesSelector' in Element.prototype ? 'mozMatchesSelector' : 'oMatchesSelector' in Element.prototype ? 'oMatchesSelector' : 'msMatchesSelector';
-  browser.pEventTypes = browser.supportsPointerEvent ? _domObjects["default"].PointerEvent === window.MSPointerEvent ? {
-    up: 'MSPointerUp',
-    down: 'MSPointerDown',
-    over: 'mouseover',
-    out: 'mouseout',
-    move: 'MSPointerMove',
-    cancel: 'MSPointerCancel'
-  } : {
-    up: 'pointerup',
-    down: 'pointerdown',
-    over: 'pointerover',
-    out: 'pointerout',
-    move: 'pointermove',
-    cancel: 'pointercancel'
-  } : null; // because Webkit and Opera still use 'mousewheel' event type
-
-  browser.wheelEvent = 'onmousewheel' in _domObjects["default"].document ? 'mousewheel' : 'wheel';
-}
-
-var ___default_48 = browser;
-_$browser_48["default"] = ___default_48;
-
-var _$domUtils_51 = {};
-"use strict";
-
-Object.defineProperty(_$domUtils_51, "__esModule", {
-  value: true
-});
-_$domUtils_51.nodeContains = nodeContains;
-_$domUtils_51.closest = closest;
-_$domUtils_51.parentNode = parentNode;
-_$domUtils_51.matchesSelector = matchesSelector;
-_$domUtils_51.indexOfDeepestElement = indexOfDeepestElement;
-_$domUtils_51.matchesUpTo = matchesUpTo;
-_$domUtils_51.getActualElement = getActualElement;
-_$domUtils_51.getScrollXY = getScrollXY;
-_$domUtils_51.getElementClientRect = getElementClientRect;
-_$domUtils_51.getElementRect = getElementRect;
-_$domUtils_51.getPath = getPath;
-_$domUtils_51.trySelector = trySelector;
-
-var _browser = ___interopRequireDefault_51(_$browser_48);
-
-var ___domObjects_51 = ___interopRequireDefault_51(_$domObjects_50);
-
-var __is_51 = ___interopRequireWildcard_51(_$is_57);
-
-var ___window_51 = ___interopRequireWildcard_51(_$window_66);
-
-function ___interopRequireWildcard_51(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_51(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function nodeContains(parent, child) {
-  while (child) {
-    if (child === parent) {
-      return true;
-    }
-
-    child = child.parentNode;
-  }
-
-  return false;
-}
-
-function closest(element, selector) {
-  while (__is_51.element(element)) {
-    if (matchesSelector(element, selector)) {
-      return element;
-    }
-
-    element = parentNode(element);
-  }
-
-  return null;
-}
-
-function parentNode(node) {
-  var parent = node.parentNode;
-
-  if (__is_51.docFrag(parent)) {
-    // skip past #shado-root fragments
-    // tslint:disable-next-line
-    while ((parent = parent.host) && __is_51.docFrag(parent)) {
-      continue;
-    }
-
-    return parent;
-  }
-
-  return parent;
-}
-
-function matchesSelector(element, selector) {
-  // remove /deep/ from selectors if shadowDOM polyfill is used
-  if (___window_51["default"].window !== ___window_51["default"].realWindow) {
-    selector = selector.replace(/\/deep\//g, ' ');
-  }
-
-  return element[_browser["default"].prefixedMatchesSelector](selector);
-}
-
-var getParent = function getParent(el) {
-  return el.parentNode ? el.parentNode : el.host;
-}; // Test for the element that's "above" all other qualifiers
-
-
-function indexOfDeepestElement(elements) {
-  var deepestZoneParents = [];
-  var deepestZone = elements[0];
-  var index = deepestZone ? 0 : -1;
-  var i;
-  var n;
-
-  for (i = 1; i < elements.length; i++) {
-    var dropzone = elements[i]; // an element might belong to multiple selector dropzones
-
-    if (!dropzone || dropzone === deepestZone) {
-      continue;
-    }
-
-    if (!deepestZone) {
-      deepestZone = dropzone;
-      index = i;
-      continue;
-    } // check if the deepest or current are document.documentElement or document.rootElement
-    // - if the current dropzone is, do nothing and continue
-
-
-    if (dropzone.parentNode === dropzone.ownerDocument) {
-      continue;
-    } // - if deepest is, update with the current dropzone and continue to next
-    else if (deepestZone.parentNode === dropzone.ownerDocument) {
-        deepestZone = dropzone;
-        index = i;
-        continue;
-      } // compare zIndex of siblings
-
-
-    if (dropzone.parentNode === deepestZone.parentNode) {
-      var deepestZIndex = parseInt((0, ___window_51.getWindow)(deepestZone).getComputedStyle(deepestZone).zIndex, 10) || 0;
-      var dropzoneZIndex = parseInt((0, ___window_51.getWindow)(dropzone).getComputedStyle(dropzone).zIndex, 10) || 0;
-
-      if (dropzoneZIndex >= deepestZIndex) {
-        deepestZone = dropzone;
-        index = i;
-      }
-
-      continue;
-    } // populate the ancestry array for the latest deepest dropzone
-
-
-    if (!deepestZoneParents.length) {
-      var _parent = deepestZone;
-      var parentParent = void 0;
-
-      while ((parentParent = getParent(_parent)) && parentParent !== _parent.ownerDocument) {
-        deepestZoneParents.unshift(_parent);
-        _parent = parentParent;
-      }
-    }
-
-    var parent = void 0; // if this element is an svg element and the current deepest is an
-    // HTMLElement
-
-    if (deepestZone instanceof ___domObjects_51["default"].HTMLElement && dropzone instanceof ___domObjects_51["default"].SVGElement && !(dropzone instanceof ___domObjects_51["default"].SVGSVGElement)) {
-      if (dropzone === deepestZone.parentNode) {
-        continue;
-      }
-
-      parent = dropzone.ownerSVGElement;
-    } else {
-      parent = dropzone;
-    }
-
-    var dropzoneParents = [];
-
-    while (parent.parentNode !== parent.ownerDocument) {
-      dropzoneParents.unshift(parent);
-      parent = getParent(parent);
-    }
-
-    n = 0; // get (position of last common ancestor) + 1
-
-    while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
-      n++;
-    }
-
-    var parents = [dropzoneParents[n - 1], dropzoneParents[n], deepestZoneParents[n]];
-    var child = parents[0].lastChild;
-
-    while (child) {
-      if (child === parents[1]) {
-        deepestZone = dropzone;
-        index = i;
-        deepestZoneParents = dropzoneParents;
-        break;
-      } else if (child === parents[2]) {
-        break;
-      }
-
-      child = child.previousSibling;
-    }
-  }
-
-  return index;
-}
-
-function matchesUpTo(element, selector, limit) {
-  while (__is_51.element(element)) {
-    if (matchesSelector(element, selector)) {
-      return true;
-    }
-
-    element = parentNode(element);
-
-    if (element === limit) {
-      return matchesSelector(element, selector);
-    }
-  }
-
-  return false;
-}
-
-function getActualElement(element) {
-  return element instanceof ___domObjects_51["default"].SVGElementInstance ? element.correspondingUseElement : element;
-}
-
-function getScrollXY(relevantWindow) {
-  relevantWindow = relevantWindow || ___window_51["default"].window;
-  return {
-    x: relevantWindow.scrollX || relevantWindow.document.documentElement.scrollLeft,
-    y: relevantWindow.scrollY || relevantWindow.document.documentElement.scrollTop
-  };
-}
-
-function getElementClientRect(element) {
-  var clientRect = element instanceof ___domObjects_51["default"].SVGElement ? element.getBoundingClientRect() : element.getClientRects()[0];
-  return clientRect && {
-    left: clientRect.left,
-    right: clientRect.right,
-    top: clientRect.top,
-    bottom: clientRect.bottom,
-    width: clientRect.width || clientRect.right - clientRect.left,
-    height: clientRect.height || clientRect.bottom - clientRect.top
-  };
-}
-
-function getElementRect(element) {
-  var clientRect = getElementClientRect(element);
-
-  if (!_browser["default"].isIOS7 && clientRect) {
-    var scroll = getScrollXY(___window_51["default"].getWindow(element));
-    clientRect.left += scroll.x;
-    clientRect.right += scroll.x;
-    clientRect.top += scroll.y;
-    clientRect.bottom += scroll.y;
-  }
-
-  return clientRect;
-}
-
-function getPath(node) {
-  var path = [];
-
-  while (node) {
-    path.push(node);
-    node = parentNode(node);
-  }
-
-  return path;
-}
-
-function trySelector(value) {
-  if (!__is_51.string(value)) {
-    return false;
-  } // an exception will be raised if it is invalid
-
-
-  ___domObjects_51["default"].document.querySelector(value);
-
-  return true;
-}
-
-var _$clone_49 = {};
-"use strict";
-
-Object.defineProperty(_$clone_49, "__esModule", {
-  value: true
-});
-_$clone_49["default"] = clone;
-
-var arr = ___interopRequireWildcard_49(_$arr_47);
-
-var __is_49 = ___interopRequireWildcard_49(_$is_57);
-
-function ___interopRequireWildcard_49(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function clone(source) {
-  var dest = {};
-
-  for (var prop in source) {
-    var value = source[prop];
-
-    if (__is_49.plainObject(value)) {
-      dest[prop] = clone(value);
-    } else if (__is_49.array(value)) {
-      dest[prop] = arr.from(value);
-    } else {
-      dest[prop] = value;
-    }
-  }
-
-  return dest;
-}
-
-var _$pointerExtend_60 = {};
-"use strict";
-
-Object.defineProperty(_$pointerExtend_60, "__esModule", {
-  value: true
-});
-_$pointerExtend_60["default"] = void 0;
-
-function pointerExtend(dest, source) {
-  for (var prop in source) {
-    var prefixedPropREs = pointerExtend.prefixedPropREs;
-    var deprecated = false; // skip deprecated prefixed properties
-
-    for (var vendor in prefixedPropREs) {
-      if (prop.indexOf(vendor) === 0 && prefixedPropREs[vendor].test(prop)) {
-        deprecated = true;
-        break;
-      }
-    }
-
-    if (!deprecated && typeof source[prop] !== 'function') {
-      dest[prop] = source[prop];
-    }
-  }
-
-  return dest;
-}
-
-pointerExtend.prefixedPropREs = {
-  webkit: /(Movement[XY]|Radius[XY]|RotationAngle|Force)$/,
-  moz: /(Pressure)$/
-};
-var ___default_60 = pointerExtend;
-_$pointerExtend_60["default"] = ___default_60;
-
-var _$hypot_55 = {};
-"use strict";
-
-Object.defineProperty(_$hypot_55, "__esModule", {
-  value: true
-});
-_$hypot_55["default"] = void 0;
-
-var ___default_55 = function _default(x, y) {
-  return Math.sqrt(x * x + y * y);
-};
-
-_$hypot_55["default"] = ___default_55;
-
-var _$pointerUtils_61 = {};
-"use strict";
-
-Object.defineProperty(_$pointerUtils_61, "__esModule", {
-  value: true
-});
-_$pointerUtils_61["default"] = void 0;
-
-var ___browser_61 = ___interopRequireDefault_61(_$browser_48);
-
-var ___domObjects_61 = ___interopRequireDefault_61(_$domObjects_50);
-
-var domUtils = ___interopRequireWildcard_61(_$domUtils_51);
-
-var _hypot = ___interopRequireDefault_61(_$hypot_55);
-
-var __is_61 = ___interopRequireWildcard_61(_$is_57);
-
-var _pointerExtend = ___interopRequireDefault_61(_$pointerExtend_60);
-
-function ___interopRequireWildcard_61(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_61(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var pointerUtils = {
-  copyCoords: function copyCoords(dest, src) {
-    dest.page = dest.page || {};
-    dest.page.x = src.page.x;
-    dest.page.y = src.page.y;
-    dest.client = dest.client || {};
-    dest.client.x = src.client.x;
-    dest.client.y = src.client.y;
-    dest.timeStamp = src.timeStamp;
-  },
-  setCoordDeltas: function setCoordDeltas(targetObj, prev, cur) {
-    targetObj.page.x = cur.page.x - prev.page.x;
-    targetObj.page.y = cur.page.y - prev.page.y;
-    targetObj.client.x = cur.client.x - prev.client.x;
-    targetObj.client.y = cur.client.y - prev.client.y;
-    targetObj.timeStamp = cur.timeStamp - prev.timeStamp;
-  },
-  setCoordVelocity: function setCoordVelocity(targetObj, delta) {
-    var dt = Math.max(delta.timeStamp / 1000, 0.001);
-    targetObj.page.x = delta.page.x / dt;
-    targetObj.page.y = delta.page.y / dt;
-    targetObj.client.x = delta.client.x / dt;
-    targetObj.client.y = delta.client.y / dt;
-    targetObj.timeStamp = dt;
-  },
-  isNativePointer: function isNativePointer(pointer) {
-    return pointer instanceof ___domObjects_61["default"].Event || pointer instanceof ___domObjects_61["default"].Touch;
-  },
-  // Get specified X/Y coords for mouse or event.touches[0]
-  getXY: function getXY(type, pointer, xy) {
-    xy = xy || {};
-    type = type || 'page';
-    xy.x = pointer[type + 'X'];
-    xy.y = pointer[type + 'Y'];
-    return xy;
-  },
-  getPageXY: function getPageXY(pointer, page) {
-    page = page || {
-      x: 0,
-      y: 0
-    }; // Opera Mobile handles the viewport and scrolling oddly
-
-    if (___browser_61["default"].isOperaMobile && pointerUtils.isNativePointer(pointer)) {
-      pointerUtils.getXY('screen', pointer, page);
-      page.x += window.scrollX;
-      page.y += window.scrollY;
-    } else {
-      pointerUtils.getXY('page', pointer, page);
-    }
-
-    return page;
-  },
-  getClientXY: function getClientXY(pointer, client) {
-    client = client || {};
-
-    if (___browser_61["default"].isOperaMobile && pointerUtils.isNativePointer(pointer)) {
-      // Opera Mobile handles the viewport and scrolling oddly
-      pointerUtils.getXY('screen', pointer, client);
-    } else {
-      pointerUtils.getXY('client', pointer, client);
-    }
-
-    return client;
-  },
-  getPointerId: function getPointerId(pointer) {
-    return __is_61.number(pointer.pointerId) ? pointer.pointerId : pointer.identifier;
-  },
-  setCoords: function setCoords(targetObj, pointers, timeStamp) {
-    var pointer = pointers.length > 1 ? pointerUtils.pointerAverage(pointers) : pointers[0];
-    var tmpXY = {};
-    pointerUtils.getPageXY(pointer, tmpXY);
-    targetObj.page.x = tmpXY.x;
-    targetObj.page.y = tmpXY.y;
-    pointerUtils.getClientXY(pointer, tmpXY);
-    targetObj.client.x = tmpXY.x;
-    targetObj.client.y = tmpXY.y;
-    targetObj.timeStamp = timeStamp;
-  },
-  pointerExtend: _pointerExtend["default"],
-  getTouchPair: function getTouchPair(event) {
-    var touches = []; // array of touches is supplied
-
-    if (__is_61.array(event)) {
-      touches[0] = event[0];
-      touches[1] = event[1];
-    } // an event
-    else {
-        if (event.type === 'touchend') {
-          if (event.touches.length === 1) {
-            touches[0] = event.touches[0];
-            touches[1] = event.changedTouches[0];
-          } else if (event.touches.length === 0) {
-            touches[0] = event.changedTouches[0];
-            touches[1] = event.changedTouches[1];
-          }
-        } else {
-          touches[0] = event.touches[0];
-          touches[1] = event.touches[1];
-        }
-      }
-
-    return touches;
-  },
-  pointerAverage: function pointerAverage(pointers) {
-    var average = {
-      pageX: 0,
-      pageY: 0,
-      clientX: 0,
-      clientY: 0,
-      screenX: 0,
-      screenY: 0
-    };
-
-    for (var _i = 0; _i < pointers.length; _i++) {
-      var _ref;
-
-      _ref = pointers[_i];
-      var pointer = _ref;
-
-      for (var _prop in average) {
-        average[_prop] += pointer[_prop];
-      }
-    }
-
-    for (var prop in average) {
-      average[prop] /= pointers.length;
-    }
-
-    return average;
-  },
-  touchBBox: function touchBBox(event) {
-    if (!event.length && !(event.touches && event.touches.length > 1)) {
-      return null;
-    }
-
-    var touches = pointerUtils.getTouchPair(event);
-    var minX = Math.min(touches[0].pageX, touches[1].pageX);
-    var minY = Math.min(touches[0].pageY, touches[1].pageY);
-    var maxX = Math.max(touches[0].pageX, touches[1].pageX);
-    var maxY = Math.max(touches[0].pageY, touches[1].pageY);
-    return {
-      x: minX,
-      y: minY,
-      left: minX,
-      top: minY,
-      right: maxX,
-      bottom: maxY,
-      width: maxX - minX,
-      height: maxY - minY
-    };
-  },
-  touchDistance: function touchDistance(event, deltaSource) {
-    var sourceX = deltaSource + 'X';
-    var sourceY = deltaSource + 'Y';
-    var touches = pointerUtils.getTouchPair(event);
-    var dx = touches[0][sourceX] - touches[1][sourceX];
-    var dy = touches[0][sourceY] - touches[1][sourceY];
-    return (0, _hypot["default"])(dx, dy);
-  },
-  touchAngle: function touchAngle(event, deltaSource) {
-    var sourceX = deltaSource + 'X';
-    var sourceY = deltaSource + 'Y';
-    var touches = pointerUtils.getTouchPair(event);
-    var dx = touches[1][sourceX] - touches[0][sourceX];
-    var dy = touches[1][sourceY] - touches[0][sourceY];
-    var angle = 180 * Math.atan2(dy, dx) / Math.PI;
-    return angle;
-  },
-  getPointerType: function getPointerType(pointer) {
-    return __is_61.string(pointer.pointerType) ? pointer.pointerType : __is_61.number(pointer.pointerType) ? [undefined, undefined, 'touch', 'pen', 'mouse'][pointer.pointerType] // if the PointerEvent API isn't available, then the "pointer" must
-    // be either a MouseEvent, TouchEvent, or Touch object
-    : /touch/.test(pointer.type) || pointer instanceof ___domObjects_61["default"].Touch ? 'touch' : 'mouse';
-  },
-  // [ event.target, event.currentTarget ]
-  getEventTargets: function getEventTargets(event) {
-    var path = __is_61.func(event.composedPath) ? event.composedPath() : event.path;
-    return [domUtils.getActualElement(path ? path[0] : event.target), domUtils.getActualElement(event.currentTarget)];
-  },
-  newCoords: function newCoords() {
-    return {
-      page: {
-        x: 0,
-        y: 0
-      },
-      client: {
-        x: 0,
-        y: 0
-      },
-      timeStamp: 0
-    };
-  },
-  coordsToEvent: function coordsToEvent(coords) {
-    var event = {
-      coords: coords,
-
-      get page() {
-        return this.coords.page;
-      },
-
-      get client() {
-        return this.coords.client;
-      },
-
-      get timeStamp() {
-        return this.coords.timeStamp;
-      },
-
-      get pageX() {
-        return this.coords.page.x;
-      },
-
-      get pageY() {
-        return this.coords.page.y;
-      },
-
-      get clientX() {
-        return this.coords.client.x;
-      },
-
-      get clientY() {
-        return this.coords.client.y;
-      },
-
-      get pointerId() {
-        return this.coords.pointerId;
-      },
-
-      get target() {
-        return this.coords.target;
-      },
-
-      get type() {
-        return this.coords.type;
-      },
-
-      get pointerType() {
-        return this.coords.pointerType;
-      },
-
-      get buttons() {
-        return this.coords.buttons;
-      }
-
-    };
-    return event;
-  }
-};
-var ___default_61 = pointerUtils;
-_$pointerUtils_61["default"] = ___default_61;
-
-var _$events_52 = {};
-"use strict";
-
-Object.defineProperty(_$events_52, "__esModule", {
-  value: true
-});
-_$events_52["default"] = _$events_52.FakeEvent = void 0;
-
-/* removed: var _$arr_47 = require("./arr"); */;
-
-var __domUtils_52 = ___interopRequireWildcard_52(_$domUtils_51);
-
-var __is_52 = ___interopRequireWildcard_52(_$is_57);
-
-var ___pointerExtend_52 = ___interopRequireDefault_52(_$pointerExtend_60);
-
-var _pointerUtils = ___interopRequireDefault_52(_$pointerUtils_61);
-
-function ___interopRequireDefault_52(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_52(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-
-function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
-
-function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
-
-function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
-
-function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
-
-var elements = [];
-var targets = [];
-var delegatedEvents = {};
-var documents = [];
-
-function add(element, type, listener, optionalArg) {
-  var options = getOptions(optionalArg);
-  var elementIndex = elements.indexOf(element);
-  var target = targets[elementIndex];
-
-  if (!target) {
-    target = {
-      events: {},
-      typeCount: 0
-    };
-    elementIndex = elements.push(element) - 1;
-    targets.push(target);
-  }
-
-  if (!target.events[type]) {
-    target.events[type] = [];
-    target.typeCount++;
-  }
-
-  if (!(0, _$arr_47.contains)(target.events[type], listener)) {
-    element.addEventListener(type, listener, events.supportsOptions ? options : !!options.capture);
-    target.events[type].push(listener);
-  }
-}
-
-function __remove_52(element, type, listener, optionalArg) {
-  var options = getOptions(optionalArg);
-  var elementIndex = elements.indexOf(element);
-  var target = targets[elementIndex];
-
-  if (!target || !target.events) {
-    return;
-  }
-
-  if (type === 'all') {
-    for (type in target.events) {
-      if (target.events.hasOwnProperty(type)) {
-        __remove_52(element, type, 'all');
-      }
-    }
-
-    return;
-  }
-
-  if (target.events[type]) {
-    var len = target.events[type].length;
-
-    if (listener === 'all') {
-      for (var i = 0; i < len; i++) {
-        __remove_52(element, type, target.events[type][i], options);
-      }
-
-      return;
-    } else {
-      for (var _i = 0; _i < len; _i++) {
-        if (target.events[type][_i] === listener) {
-          element.removeEventListener(type, listener, events.supportsOptions ? options : !!options.capture);
-          target.events[type].splice(_i, 1);
-          break;
-        }
-      }
-    }
-
-    if (target.events[type] && target.events[type].length === 0) {
-      target.events[type] = null;
-      target.typeCount--;
-    }
-  }
-
-  if (!target.typeCount) {
-    targets.splice(elementIndex, 1);
-    elements.splice(elementIndex, 1);
-  }
-}
-
-function addDelegate(selector, context, type, listener, optionalArg) {
-  var options = getOptions(optionalArg);
-
-  if (!delegatedEvents[type]) {
-    delegatedEvents[type] = {
-      contexts: [],
-      listeners: [],
-      selectors: []
-    }; // add delegate listener functions
-
-    for (var _i2 = 0; _i2 < documents.length; _i2++) {
-      var doc = documents[_i2];
-      add(doc, type, delegateListener);
-      add(doc, type, delegateUseCapture, true);
-    }
-  }
-
-  var delegated = delegatedEvents[type];
-  var index;
-
-  for (index = delegated.selectors.length - 1; index >= 0; index--) {
-    if (delegated.selectors[index] === selector && delegated.contexts[index] === context) {
-      break;
-    }
-  }
-
-  if (index === -1) {
-    index = delegated.selectors.length;
-    delegated.selectors.push(selector);
-    delegated.contexts.push(context);
-    delegated.listeners.push([]);
-  } // keep listener and capture and passive flags
-
-
-  delegated.listeners[index].push([listener, !!options.capture, options.passive]);
-}
-
-function removeDelegate(selector, context, type, listener, optionalArg) {
-  var options = getOptions(optionalArg);
-  var delegated = delegatedEvents[type];
-  var matchFound = false;
-  var index;
-
-  if (!delegated) {
-    return;
-  } // count from last index of delegated to 0
-
-
-  for (index = delegated.selectors.length - 1; index >= 0; index--) {
-    // look for matching selector and context Node
-    if (delegated.selectors[index] === selector && delegated.contexts[index] === context) {
-      var listeners = delegated.listeners[index]; // each item of the listeners array is an array: [function, capture, passive]
-
-      for (var i = listeners.length - 1; i >= 0; i--) {
-        var _listeners$i = _slicedToArray(listeners[i], 3),
-            fn = _listeners$i[0],
-            capture = _listeners$i[1],
-            passive = _listeners$i[2]; // check if the listener functions and capture and passive flags match
-
-
-        if (fn === listener && capture === !!options.capture && passive === options.passive) {
-          // remove the listener from the array of listeners
-          listeners.splice(i, 1); // if all listeners for this interactable have been removed
-          // remove the interactable from the delegated arrays
-
-          if (!listeners.length) {
-            delegated.selectors.splice(index, 1);
-            delegated.contexts.splice(index, 1);
-            delegated.listeners.splice(index, 1); // remove delegate function from context
-
-            __remove_52(context, type, delegateListener);
-            __remove_52(context, type, delegateUseCapture, true); // remove the arrays if they are empty
-
-            if (!delegated.selectors.length) {
-              delegatedEvents[type] = null;
-            }
-          } // only remove one listener
-
-
-          matchFound = true;
-          break;
-        }
-      }
-
-      if (matchFound) {
-        break;
-      }
-    }
-  }
-} // bound to the interactable context when a DOM event
-// listener is added to a selector interactable
-
-
-function delegateListener(event, optionalArg) {
-  var options = getOptions(optionalArg);
-  var fakeEvent = new FakeEvent(event);
-  var delegated = delegatedEvents[event.type];
-
-  var _pointerUtils$getEven = _pointerUtils["default"].getEventTargets(event),
-      _pointerUtils$getEven2 = _slicedToArray(_pointerUtils$getEven, 1),
-      eventTarget = _pointerUtils$getEven2[0];
-
-  var element = eventTarget; // climb up document tree looking for selector matches
-
-  while (__is_52.element(element)) {
-    for (var i = 0; i < delegated.selectors.length; i++) {
-      var selector = delegated.selectors[i];
-      var context = delegated.contexts[i];
-
-      if (__domUtils_52.matchesSelector(element, selector) && __domUtils_52.nodeContains(context, eventTarget) && __domUtils_52.nodeContains(context, element)) {
-        var listeners = delegated.listeners[i];
-        fakeEvent.currentTarget = element;
-
-        for (var _i3 = 0; _i3 < listeners.length; _i3++) {
-          var _ref;
-
-          _ref = listeners[_i3];
-
-          var _ref2 = _ref,
-              _ref3 = _slicedToArray(_ref2, 3),
-              fn = _ref3[0],
-              capture = _ref3[1],
-              passive = _ref3[2];
-
-          if (capture === !!options.capture && passive === options.passive) {
-            fn(fakeEvent);
-          }
-        }
-      }
-    }
-
-    element = __domUtils_52.parentNode(element);
-  }
-}
-
-function delegateUseCapture(event) {
-  return delegateListener.call(this, event, true);
-}
-
-function getOptions(param) {
-  return __is_52.object(param) ? param : {
-    capture: param
-  };
-}
-
-var FakeEvent =
-/*#__PURE__*/
-function () {
-  function FakeEvent(originalEvent) {
-    _classCallCheck(this, FakeEvent);
-
-    this.originalEvent = originalEvent; // duplicate the event so that currentTarget can be changed
-
-    (0, ___pointerExtend_52["default"])(this, originalEvent);
-  }
-
-  _createClass(FakeEvent, [{
-    key: "preventOriginalDefault",
-    value: function preventOriginalDefault() {
-      this.originalEvent.preventDefault();
-    }
-  }, {
-    key: "stopPropagation",
-    value: function stopPropagation() {
-      this.originalEvent.stopPropagation();
-    }
-  }, {
-    key: "stopImmediatePropagation",
-    value: function stopImmediatePropagation() {
-      this.originalEvent.stopImmediatePropagation();
-    }
-  }]);
-
-  return FakeEvent;
-}();
-
-_$events_52.FakeEvent = FakeEvent;
-var events = {
-  add: add,
-  remove: __remove_52,
-  addDelegate: addDelegate,
-  removeDelegate: removeDelegate,
-  delegateListener: delegateListener,
-  delegateUseCapture: delegateUseCapture,
-  delegatedEvents: delegatedEvents,
-  documents: documents,
-  supportsOptions: false,
-  supportsPassive: false,
-  _elements: elements,
-  _targets: targets,
-  init: function init(window) {
-    window.document.createElement('div').addEventListener('test', null, {
-      get capture() {
-        return events.supportsOptions = true;
-      },
-
-      get passive() {
-        return events.supportsPassive = true;
-      }
-
-    });
-  }
-};
-var ___default_52 = events;
-_$events_52["default"] = ___default_52;
-
-var _$extend_53 = {};
-"use strict";
-
-Object.defineProperty(_$extend_53, "__esModule", {
-  value: true
-});
-_$extend_53["default"] = extend;
-
-function extend(dest, source) {
-  for (var prop in source) {
-    dest[prop] = source[prop];
-  }
-
-  return dest;
-}
-
-var _$rect_63 = {};
-"use strict";
-
-Object.defineProperty(_$rect_63, "__esModule", {
-  value: true
-});
-_$rect_63.getStringOptionResult = getStringOptionResult;
-_$rect_63.resolveRectLike = resolveRectLike;
-_$rect_63.rectToXY = rectToXY;
-_$rect_63.xywhToTlbr = xywhToTlbr;
-_$rect_63.tlbrToXywh = tlbrToXywh;
-_$rect_63["default"] = void 0;
-
-/* removed: var _$domUtils_51 = require("./domUtils"); */;
-
-var _extend = ___interopRequireDefault_63(_$extend_53);
-
-var __is_63 = ___interopRequireWildcard_63(_$is_57);
-
-function ___interopRequireWildcard_63(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_63(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
-
-function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
-
-function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
-
-function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
-
-function getStringOptionResult(value, interactable, element) {
-  if (value === 'parent') {
-    return (0, _$domUtils_51.parentNode)(element);
-  }
-
-  if (value === 'self') {
-    return interactable.getRect(element);
-  }
-
-  return (0, _$domUtils_51.closest)(element, value);
-}
-
-function resolveRectLike(value, interactable, element, functionArgs) {
-  if (__is_63.string(value)) {
-    value = getStringOptionResult(value, interactable, element);
-  } else if (__is_63.func(value)) {
-    value = value.apply(void 0, _toConsumableArray(functionArgs));
-  }
-
-  if (__is_63.element(value)) {
-    value = (0, _$domUtils_51.getElementRect)(value);
-  }
-
-  return value;
-}
-
-function rectToXY(rect) {
-  return rect && {
-    x: 'x' in rect ? rect.x : rect.left,
-    y: 'y' in rect ? rect.y : rect.top
-  };
-}
-
-function xywhToTlbr(rect) {
-  if (rect && !('left' in rect && 'top' in rect)) {
-    rect = (0, _extend["default"])({}, rect);
-    rect.left = rect.x || 0;
-    rect.top = rect.y || 0;
-    rect.right = rect.right || rect.left + rect.width;
-    rect.bottom = rect.bottom || rect.top + rect.height;
-  }
-
-  return rect;
-}
-
-function tlbrToXywh(rect) {
-  if (rect && !('x' in rect && 'y' in rect)) {
-    rect = (0, _extend["default"])({}, rect);
-    rect.x = rect.left || 0;
-    rect.y = rect.top || 0;
-    rect.width = rect.width || rect.right - rect.x;
-    rect.height = rect.height || rect.bottom - rect.y;
-  }
-
-  return rect;
-}
-
-var ___default_63 = {
-  getStringOptionResult: getStringOptionResult,
-  resolveRectLike: resolveRectLike,
-  rectToXY: rectToXY,
-  xywhToTlbr: xywhToTlbr,
-  tlbrToXywh: tlbrToXywh
-};
-_$rect_63["default"] = ___default_63;
-
-var _$getOriginXY_54 = {};
-"use strict";
-
-Object.defineProperty(_$getOriginXY_54, "__esModule", {
-  value: true
-});
-_$getOriginXY_54["default"] = ___default_54;
-
-/* removed: var _$rect_63 = require("./rect"); */;
-
-function ___default_54(target, element, action) {
-  var actionOptions = target.options[action];
-  var actionOrigin = actionOptions && actionOptions.origin;
-  var origin = actionOrigin || target.options.origin;
-  var originRect = (0, _$rect_63.resolveRectLike)(origin, target, element, [target && element]);
-  return (0, _$rect_63.rectToXY)(originRect) || {
-    x: 0,
-    y: 0
-  };
-}
-
-var _$normalizeListeners_59 = {};
-"use strict";
-
-Object.defineProperty(_$normalizeListeners_59, "__esModule", {
-  value: true
-});
-_$normalizeListeners_59["default"] = normalize;
-
-var ___extend_59 = ___interopRequireDefault_59(_$extend_53);
-
-var __is_59 = ___interopRequireWildcard_59(_$is_57);
-
-function ___interopRequireWildcard_59(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_59(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function normalize(type, listeners, result) {
-  result = result || {};
-
-  if (__is_59.string(type) && type.search(' ') !== -1) {
-    type = split(type);
-  }
-
-  if (__is_59.array(type)) {
-    return type.reduce(function (acc, t) {
-      return (0, ___extend_59["default"])(acc, normalize(t, listeners, result));
-    }, result);
-  } // ({ type: fn }) -> ('', { type: fn })
-
-
-  if (__is_59.object(type)) {
-    listeners = type;
-    type = '';
-  }
-
-  if (__is_59.func(listeners)) {
-    result[type] = result[type] || [];
-    result[type].push(listeners);
-  } else if (__is_59.array(listeners)) {
-    for (var _i = 0; _i < listeners.length; _i++) {
-      var _ref;
-
-      _ref = listeners[_i];
-      var l = _ref;
-      normalize(type, l, result);
-    }
-  } else if (__is_59.object(listeners)) {
-    for (var prefix in listeners) {
-      var combinedTypes = split(prefix).map(function (p) {
-        return "".concat(type).concat(p);
-      });
-      normalize(combinedTypes, listeners[prefix], result);
-    }
-  }
-
-  return result;
-}
-
-function split(type) {
-  return type.trim().split(/ +/);
-}
-
-var _$raf_62 = {};
-"use strict";
-
-Object.defineProperty(_$raf_62, "__esModule", {
-  value: true
-});
-_$raf_62["default"] = void 0;
-var lastTime = 0;
-
-var _request;
-
-var _cancel;
-
-function __init_62(window) {
-  _request = window.requestAnimationFrame;
-  _cancel = window.cancelAnimationFrame;
-
-  if (!_request) {
-    var vendors = ['ms', 'moz', 'webkit', 'o'];
-
-    for (var _i = 0; _i < vendors.length; _i++) {
-      var vendor = vendors[_i];
-      _request = window["".concat(vendor, "RequestAnimationFrame")];
-      _cancel = window["".concat(vendor, "CancelAnimationFrame")] || window["".concat(vendor, "CancelRequestAnimationFrame")];
-    }
-  }
-
-  if (!_request) {
-    _request = function request(callback) {
-      var currTime = Date.now();
-      var timeToCall = Math.max(0, 16 - (currTime - lastTime)); // eslint-disable-next-line standard/no-callback-literal
-
-      var token = setTimeout(function () {
-        callback(currTime + timeToCall);
-      }, timeToCall);
-      lastTime = currTime + timeToCall;
-      return token;
-    };
-
-    _cancel = function cancel(token) {
-      return clearTimeout(token);
-    };
-  }
-}
-
-var ___default_62 = {
-  request: function request(callback) {
-    return _request(callback);
-  },
-  cancel: function cancel(token) {
-    return _cancel(token);
-  },
-  init: __init_62
-};
-_$raf_62["default"] = ___default_62;
-
-var _$Signals_46 = {};
-"use strict";
-
-Object.defineProperty(_$Signals_46, "__esModule", {
-  value: true
-});
-_$Signals_46["default"] = void 0;
-
-function ___classCallCheck_46(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_46(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_46(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_46(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_46(Constructor, staticProps); return Constructor; }
-
-var Signals =
-/*#__PURE__*/
-function () {
-  function Signals() {
-    ___classCallCheck_46(this, Signals);
-
-    this.listeners = {};
-  }
-
-  ___createClass_46(Signals, [{
-    key: "on",
-    value: function on(name, listener) {
-      if (!this.listeners[name]) {
-        this.listeners[name] = [listener];
-        return;
-      }
-
-      this.listeners[name].push(listener);
-    }
-  }, {
-    key: "off",
-    value: function off(name, listener) {
-      if (!this.listeners[name]) {
-        return;
-      }
-
-      var index = this.listeners[name].indexOf(listener);
-
-      if (index !== -1) {
-        this.listeners[name].splice(index, 1);
-      }
-    }
-  }, {
-    key: "fire",
-    value: function fire(name, arg) {
-      var targetListeners = this.listeners[name];
-
-      if (!targetListeners) {
-        return;
-      }
-
-      for (var _i = 0; _i < targetListeners.length; _i++) {
-        var _ref;
-
-        _ref = targetListeners[_i];
-        var listener = _ref;
-
-        if (listener(arg, name) === false) {
-          return false;
-        }
-      }
-    }
-  }]);
-
-  return Signals;
-}();
-
-var ___default_46 = Signals;
-_$Signals_46["default"] = ___default_46;
-
-var _$utils_56 = {};
-"use strict";
-
-Object.defineProperty(_$utils_56, "__esModule", {
-  value: true
-});
-_$utils_56.warnOnce = warnOnce;
-_$utils_56._getQBezierValue = _getQBezierValue;
-_$utils_56.getQuadraticCurvePoint = getQuadraticCurvePoint;
-_$utils_56.easeOutQuad = easeOutQuad;
-_$utils_56.copyAction = copyAction;
-Object.defineProperty(_$utils_56, "win", {
-  enumerable: true,
-  get: function get() {
-    return ___window_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "browser", {
-  enumerable: true,
-  get: function get() {
-    return ___browser_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "clone", {
-  enumerable: true,
-  get: function get() {
-    return _clone["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "events", {
-  enumerable: true,
-  get: function get() {
-    return _events["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "extend", {
-  enumerable: true,
-  get: function get() {
-    return ___extend_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "getOriginXY", {
-  enumerable: true,
-  get: function get() {
-    return _getOriginXY["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "hypot", {
-  enumerable: true,
-  get: function get() {
-    return ___hypot_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "normalizeListeners", {
-  enumerable: true,
-  get: function get() {
-    return _normalizeListeners["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "pointer", {
-  enumerable: true,
-  get: function get() {
-    return ___pointerUtils_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "raf", {
-  enumerable: true,
-  get: function get() {
-    return _raf["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "rect", {
-  enumerable: true,
-  get: function get() {
-    return ___rect_56["default"];
-  }
-});
-Object.defineProperty(_$utils_56, "Signals", {
-  enumerable: true,
-  get: function get() {
-    return _Signals["default"];
-  }
-});
-_$utils_56.is = _$utils_56.dom = _$utils_56.arr = void 0;
-
-var __arr_56 = ___interopRequireWildcard_56(_$arr_47);
-
-_$utils_56.arr = __arr_56;
-
-var dom = ___interopRequireWildcard_56(_$domUtils_51);
-
-_$utils_56.dom = dom;
-
-var __is_56 = ___interopRequireWildcard_56(_$is_57);
-
-_$utils_56.is = __is_56;
-
-var ___window_56 = ___interopRequireDefault_56(_$window_66);
-
-var ___browser_56 = ___interopRequireDefault_56(_$browser_48);
-
-var _clone = ___interopRequireDefault_56(_$clone_49);
-
-var _events = ___interopRequireDefault_56(_$events_52);
-
-var ___extend_56 = ___interopRequireDefault_56(_$extend_53);
-
-var _getOriginXY = ___interopRequireDefault_56(_$getOriginXY_54);
-
-var ___hypot_56 = ___interopRequireDefault_56(_$hypot_55);
-
-var _normalizeListeners = ___interopRequireDefault_56(_$normalizeListeners_59);
-
-var ___pointerUtils_56 = ___interopRequireDefault_56(_$pointerUtils_61);
-
-var _raf = ___interopRequireDefault_56(_$raf_62);
-
-var ___rect_56 = ___interopRequireDefault_56(_$rect_63);
-
-var _Signals = ___interopRequireDefault_56(_$Signals_46);
-
-function ___interopRequireDefault_56(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_56(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function warnOnce(method, message) {
-  var warned = false; // eslint-disable-next-line no-shadow
-
-  return function () {
-    if (!warned) {
-      ___window_56["default"].window.console.warn(message);
-
-      warned = true;
-    }
-
-    return method.apply(this, arguments);
-  };
-} // http://stackoverflow.com/a/5634528/2280888
-
-
-function _getQBezierValue(t, p1, p2, p3) {
-  var iT = 1 - t;
-  return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
-}
-
-function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
-  return {
-    x: _getQBezierValue(position, startX, cpX, endX),
-    y: _getQBezierValue(position, startY, cpY, endY)
-  };
-} // http://gizma.com/easing/
-
-
-function easeOutQuad(t, b, c, d) {
-  t /= d;
-  return -c * t * (t - 2) + b;
-}
-
-function copyAction(dest, src) {
-  dest.name = src.name;
-  dest.axis = src.axis;
-  dest.edges = src.edges;
-  return dest;
-}
-
-var _$defaultOptions_20 = {};
-"use strict";
-
-Object.defineProperty(_$defaultOptions_20, "__esModule", {
-  value: true
-});
-_$defaultOptions_20["default"] = _$defaultOptions_20.defaults = void 0;
-// tslint:disable no-empty-interface
-var defaults = {
-  base: {
-    preventDefault: 'auto',
-    deltaSource: 'page'
-  },
-  perAction: {
-    enabled: false,
-    origin: {
-      x: 0,
-      y: 0
-    }
-  },
-  actions: {}
-};
-_$defaultOptions_20.defaults = defaults;
-var ___default_20 = defaults;
-_$defaultOptions_20["default"] = ___default_20;
-
-var _$Eventable_14 = {};
-"use strict";
-
-Object.defineProperty(_$Eventable_14, "__esModule", {
-  value: true
-});
-_$Eventable_14["default"] = void 0;
-
-var __arr_14 = ___interopRequireWildcard_14(_$arr_47);
-
-var ___extend_14 = ___interopRequireDefault_14(_$extend_53);
-
-var ___normalizeListeners_14 = ___interopRequireDefault_14(_$normalizeListeners_59);
-
-function ___interopRequireDefault_14(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_14(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___classCallCheck_14(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_14(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_14(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_14(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_14(Constructor, staticProps); return Constructor; }
-
-function fireUntilImmediateStopped(event, listeners) {
-  for (var _i = 0; _i < listeners.length; _i++) {
-    var _ref;
-
-    _ref = listeners[_i];
-    var listener = _ref;
-
-    if (event.immediatePropagationStopped) {
-      break;
-    }
-
-    listener(event);
-  }
-}
-
-var Eventable =
-/*#__PURE__*/
-function () {
-  function Eventable(options) {
-    ___classCallCheck_14(this, Eventable);
-
-    this.types = {};
-    this.propagationStopped = false;
-    this.immediatePropagationStopped = false;
-    this.options = (0, ___extend_14["default"])({}, options || {});
-  }
-
-  ___createClass_14(Eventable, [{
-    key: "fire",
-    value: function fire(event) {
-      var listeners;
-      var global = this.global; // Interactable#on() listeners
-      // tslint:disable no-conditional-assignment
-
-      if (listeners = this.types[event.type]) {
-        fireUntilImmediateStopped(event, listeners);
-      } // interact.on() listeners
-
-
-      if (!event.propagationStopped && global && (listeners = global[event.type])) {
-        fireUntilImmediateStopped(event, listeners);
-      }
-    }
-  }, {
-    key: "on",
-    value: function on(type, listener) {
-      var listeners = (0, ___normalizeListeners_14["default"])(type, listener);
-
-      for (type in listeners) {
-        this.types[type] = __arr_14.merge(this.types[type] || [], listeners[type]);
-      }
-    }
-  }, {
-    key: "off",
-    value: function off(type, listener) {
-      var listeners = (0, ___normalizeListeners_14["default"])(type, listener);
-
-      for (type in listeners) {
-        var eventList = this.types[type];
-
-        if (!eventList || !eventList.length) {
-          continue;
-        }
-
-        for (var _i2 = 0; _i2 < listeners[type].length; _i2++) {
-          var _ref2;
-
-          _ref2 = listeners[type][_i2];
-          var subListener = _ref2;
-          var index = eventList.indexOf(subListener);
-
-          if (index !== -1) {
-            eventList.splice(index, 1);
-          }
-        }
-      }
-    }
-  }]);
-
-  return Eventable;
-}();
-
-var ___default_14 = Eventable;
-_$Eventable_14["default"] = ___default_14;
-
-var _$Interactable_16 = {};
-"use strict";
-
-Object.defineProperty(_$Interactable_16, "__esModule", {
-  value: true
-});
-_$Interactable_16["default"] = _$Interactable_16.Interactable = void 0;
-
-var __arr_16 = ___interopRequireWildcard_16(_$arr_47);
-
-var ___browser_16 = ___interopRequireDefault_16(_$browser_48);
-
-var ___clone_16 = ___interopRequireDefault_16(_$clone_49);
-
-/* removed: var _$domUtils_51 = require("@interactjs/utils/domUtils"); */;
-
-var ___events_16 = ___interopRequireDefault_16(_$events_52);
-
-var ___extend_16 = ___interopRequireDefault_16(_$extend_53);
-
-var __is_16 = ___interopRequireWildcard_16(_$is_57);
-
-var ___normalizeListeners_16 = ___interopRequireDefault_16(_$normalizeListeners_59);
-
-/* removed: var _$window_66 = require("@interactjs/utils/window"); */;
-
-var _Eventable = ___interopRequireDefault_16(_$Eventable_14);
-
-function ___interopRequireDefault_16(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_16(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___classCallCheck_16(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_16(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_16(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_16(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_16(Constructor, staticProps); return Constructor; }
-
-/** */
-var Interactable =
-/*#__PURE__*/
-function () {
-  /** */
-  function Interactable(target, options, defaultContext) {
-    ___classCallCheck_16(this, Interactable);
-
-    this.events = new _Eventable["default"]();
-    this._actions = options.actions;
-    this.target = target;
-    this._context = options.context || defaultContext;
-    this._win = (0, _$window_66.getWindow)((0, _$domUtils_51.trySelector)(target) ? this._context : target);
-    this._doc = this._win.document;
-    this.set(options);
-  }
-
-  ___createClass_16(Interactable, [{
-    key: "setOnEvents",
-    value: function setOnEvents(actionName, phases) {
-      if (__is_16.func(phases.onstart)) {
-        this.on("".concat(actionName, "start"), phases.onstart);
-      }
-
-      if (__is_16.func(phases.onmove)) {
-        this.on("".concat(actionName, "move"), phases.onmove);
-      }
-
-      if (__is_16.func(phases.onend)) {
-        this.on("".concat(actionName, "end"), phases.onend);
-      }
-
-      if (__is_16.func(phases.oninertiastart)) {
-        this.on("".concat(actionName, "inertiastart"), phases.oninertiastart);
-      }
-
-      return this;
-    }
-  }, {
-    key: "updatePerActionListeners",
-    value: function updatePerActionListeners(actionName, prev, cur) {
-      if (__is_16.array(prev) || __is_16.object(prev)) {
-        this.off(actionName, prev);
-      }
-
-      if (__is_16.array(cur) || __is_16.object(cur)) {
-        this.on(actionName, cur);
-      }
-    }
-  }, {
-    key: "setPerAction",
-    value: function setPerAction(actionName, options) {
-      var defaults = this._defaults; // for all the default per-action options
-
-      for (var optionName in options) {
-        var actionOptions = this.options[actionName];
-        var optionValue = options[optionName];
-        var isArray = __is_16.array(optionValue); // remove old event listeners and add new ones
-
-        if (optionName === 'listeners') {
-          this.updatePerActionListeners(actionName, actionOptions.listeners, optionValue);
-        } // if the option value is an array
-
-
-        if (isArray) {
-          actionOptions[optionName] = __arr_16.from(optionValue);
-        } // if the option value is an object
-        else if (!isArray && __is_16.plainObject(optionValue)) {
-            // copy the object
-            actionOptions[optionName] = (0, ___extend_16["default"])(actionOptions[optionName] || {}, (0, ___clone_16["default"])(optionValue)); // set anabled field to true if it exists in the defaults
-
-            if (__is_16.object(defaults.perAction[optionName]) && 'enabled' in defaults.perAction[optionName]) {
-              actionOptions[optionName].enabled = optionValue.enabled !== false;
-            }
-          } // if the option value is a boolean and the default is an object
-          else if (__is_16.bool(optionValue) && __is_16.object(defaults.perAction[optionName])) {
-              actionOptions[optionName].enabled = optionValue;
-            } // if it's anything else, do a plain assignment
-            else {
-                actionOptions[optionName] = optionValue;
-              }
-      }
-    }
-    /**
-     * The default function to get an Interactables bounding rect. Can be
-     * overridden using {@link Interactable.rectChecker}.
-     *
-     * @param {Element} [element] The element to measure.
-     * @return {object} The object's bounding rectangle.
-     */
-
-  }, {
-    key: "getRect",
-    value: function getRect(element) {
-      element = element || (__is_16.element(this.target) ? this.target : null);
-
-      if (__is_16.string(this.target)) {
-        element = element || this._context.querySelector(this.target);
-      }
-
-      return (0, _$domUtils_51.getElementRect)(element);
-    }
-    /**
-     * Returns or sets the function used to calculate the interactable's
-     * element's rectangle
-     *
-     * @param {function} [checker] A function which returns this Interactable's
-     * bounding rectangle. See {@link Interactable.getRect}
-     * @return {function | object} The checker function or this Interactable
-     */
-
-  }, {
-    key: "rectChecker",
-    value: function rectChecker(checker) {
-      if (__is_16.func(checker)) {
-        this.getRect = checker;
-        return this;
-      }
-
-      if (checker === null) {
-        delete this.getRect;
-        return this;
-      }
-
-      return this.getRect;
-    }
-  }, {
-    key: "_backCompatOption",
-    value: function _backCompatOption(optionName, newValue) {
-      if ((0, _$domUtils_51.trySelector)(newValue) || __is_16.object(newValue)) {
-        this.options[optionName] = newValue;
-
-        for (var _i = 0; _i < this._actions.names.length; _i++) {
-          var _ref;
-
-          _ref = this._actions.names[_i];
-          var action = _ref;
-          this.options[action][optionName] = newValue;
-        }
-
-        return this;
-      }
-
-      return this.options[optionName];
-    }
-    /**
-     * Gets or sets the origin of the Interactable's element.  The x and y
-     * of the origin will be subtracted from action event coordinates.
-     *
-     * @param {Element | object | string} [origin] An HTML or SVG Element whose
-     * rect will be used, an object eg. { x: 0, y: 0 } or string 'parent', 'self'
-     * or any CSS selector
-     *
-     * @return {object} The current origin or this Interactable
-     */
-
-  }, {
-    key: "origin",
-    value: function origin(newValue) {
-      return this._backCompatOption('origin', newValue);
-    }
-    /**
-     * Returns or sets the mouse coordinate types used to calculate the
-     * movement of the pointer.
-     *
-     * @param {string} [newValue] Use 'client' if you will be scrolling while
-     * interacting; Use 'page' if you want autoScroll to work
-     * @return {string | object} The current deltaSource or this Interactable
-     */
-
-  }, {
-    key: "deltaSource",
-    value: function deltaSource(newValue) {
-      if (newValue === 'page' || newValue === 'client') {
-        this.options.deltaSource = newValue;
-        return this;
-      }
-
-      return this.options.deltaSource;
-    }
-    /**
-     * Gets the selector context Node of the Interactable. The default is
-     * `window.document`.
-     *
-     * @return {Node} The context Node of this Interactable
-     */
-
-  }, {
-    key: "context",
-    value: function context() {
-      return this._context;
-    }
-  }, {
-    key: "inContext",
-    value: function inContext(element) {
-      return this._context === element.ownerDocument || (0, _$domUtils_51.nodeContains)(this._context, element);
-    }
-  }, {
-    key: "testIgnoreAllow",
-    value: function testIgnoreAllow(options, targetNode, eventTarget) {
-      return !this.testIgnore(options.ignoreFrom, targetNode, eventTarget) && this.testAllow(options.allowFrom, targetNode, eventTarget);
-    }
-  }, {
-    key: "testAllow",
-    value: function testAllow(allowFrom, targetNode, element) {
-      if (!allowFrom) {
-        return true;
-      }
-
-      if (!__is_16.element(element)) {
-        return false;
-      }
-
-      if (__is_16.string(allowFrom)) {
-        return (0, _$domUtils_51.matchesUpTo)(element, allowFrom, targetNode);
-      } else if (__is_16.element(allowFrom)) {
-        return (0, _$domUtils_51.nodeContains)(allowFrom, element);
-      }
-
-      return false;
-    }
-  }, {
-    key: "testIgnore",
-    value: function testIgnore(ignoreFrom, targetNode, element) {
-      if (!ignoreFrom || !__is_16.element(element)) {
-        return false;
-      }
-
-      if (__is_16.string(ignoreFrom)) {
-        return (0, _$domUtils_51.matchesUpTo)(element, ignoreFrom, targetNode);
-      } else if (__is_16.element(ignoreFrom)) {
-        return (0, _$domUtils_51.nodeContains)(ignoreFrom, element);
-      }
-
-      return false;
-    }
-    /**
-     * Calls listeners for the given InteractEvent type bound globally
-     * and directly to this Interactable
-     *
-     * @param {InteractEvent} iEvent The InteractEvent object to be fired on this
-     * Interactable
-     * @return {Interactable} this Interactable
-     */
-
-  }, {
-    key: "fire",
-    value: function fire(iEvent) {
-      this.events.fire(iEvent);
-      return this;
-    }
-  }, {
-    key: "_onOff",
-    value: function _onOff(method, typeArg, listenerArg, options) {
-      if (__is_16.object(typeArg) && !__is_16.array(typeArg)) {
-        options = listenerArg;
-        listenerArg = null;
-      }
-
-      var addRemove = method === 'on' ? 'add' : 'remove';
-      var listeners = (0, ___normalizeListeners_16["default"])(typeArg, listenerArg);
-
-      for (var type in listeners) {
-        if (type === 'wheel') {
-          type = ___browser_16["default"].wheelEvent;
-        }
-
-        for (var _i2 = 0; _i2 < listeners[type].length; _i2++) {
-          var _ref2;
-
-          _ref2 = listeners[type][_i2];
-          var listener = _ref2;
-
-          // if it is an action event type
-          if (__arr_16.contains(this._actions.eventTypes, type)) {
-            this.events[method](type, listener);
-          } // delegated event
-          else if (__is_16.string(this.target)) {
-              ___events_16["default"]["".concat(addRemove, "Delegate")](this.target, this._context, type, listener, options);
-            } // remove listener from this Interatable's element
-            else {
-                ___events_16["default"][addRemove](this.target, type, listener, options);
-              }
-        }
-      }
-
-      return this;
-    }
-    /**
-     * Binds a listener for an InteractEvent, pointerEvent or DOM event.
-     *
-     * @param {string | array | object} types The types of events to listen
-     * for
-     * @param {function | array | object} [listener] The event listener function(s)
-     * @param {object | boolean} [options] options object or useCapture flag for
-     * addEventListener
-     * @return {Interactable} This Interactable
-     */
-
-  }, {
-    key: "on",
-    value: function on(types, listener, options) {
-      return this._onOff('on', types, listener, options);
-    }
-    /**
-     * Removes an InteractEvent, pointerEvent or DOM event listener.
-     *
-     * @param {string | array | object} types The types of events that were
-     * listened for
-     * @param {function | array | object} [listener] The event listener function(s)
-     * @param {object | boolean} [options] options object or useCapture flag for
-     * removeEventListener
-     * @return {Interactable} This Interactable
-     */
-
-  }, {
-    key: "off",
-    value: function off(types, listener, options) {
-      return this._onOff('off', types, listener, options);
-    }
-    /**
-     * Reset the options of this Interactable
-     *
-     * @param {object} options The new settings to apply
-     * @return {object} This Interactable
-     */
-
-  }, {
-    key: "set",
-    value: function set(options) {
-      var defaults = this._defaults;
-
-      if (!__is_16.object(options)) {
-        options = {};
-      }
-
-      this.options = (0, ___clone_16["default"])(defaults.base);
-
-      for (var actionName in this._actions.methodDict) {
-        var methodName = this._actions.methodDict[actionName];
-        this.options[actionName] = {};
-        this.setPerAction(actionName, (0, ___extend_16["default"])((0, ___extend_16["default"])({}, defaults.perAction), defaults.actions[actionName]));
-        this[methodName](options[actionName]);
-      }
-
-      for (var setting in options) {
-        if (__is_16.func(this[setting])) {
-          this[setting](options[setting]);
-        }
-      }
-
-      return this;
-    }
-    /**
-     * Remove this interactable from the list of interactables and remove it's
-     * action capabilities and event listeners
-     *
-     * @return {interact}
-     */
-
-  }, {
-    key: "unset",
-    value: function unset() {
-      ___events_16["default"].remove(this.target, 'all');
-
-      if (__is_16.string(this.target)) {
-        // remove delegated events
-        for (var type in ___events_16["default"].delegatedEvents) {
-          var delegated = ___events_16["default"].delegatedEvents[type];
-
-          if (delegated.selectors[0] === this.target && delegated.contexts[0] === this._context) {
-            delegated.selectors.splice(0, 1);
-            delegated.contexts.splice(0, 1);
-            delegated.listeners.splice(0, 1); // remove the arrays if they are empty
-
-            if (!delegated.selectors.length) {
-              delegated[type] = null;
-            }
-          }
-
-          ___events_16["default"].remove(this._context, type, ___events_16["default"].delegateListener);
-
-          ___events_16["default"].remove(this._context, type, ___events_16["default"].delegateUseCapture, true);
-        }
-      } else {
-        ___events_16["default"].remove(this.target, 'all');
-      }
-    }
-  }, {
-    key: "_defaults",
-    get: function get() {
-      return {
-        base: {},
-        perAction: {},
-        actions: {}
-      };
-    }
-  }]);
-
-  return Interactable;
-}();
-
-_$Interactable_16.Interactable = Interactable;
-var ___default_16 = Interactable;
-_$Interactable_16["default"] = ___default_16;
-
-var _$InteractableSet_17 = {};
-"use strict";
-
-Object.defineProperty(_$InteractableSet_17, "__esModule", {
-  value: true
-});
-_$InteractableSet_17["default"] = void 0;
-
-var __arr_17 = ___interopRequireWildcard_17(_$arr_47);
-
-var __domUtils_17 = ___interopRequireWildcard_17(_$domUtils_51);
-
-var ___extend_17 = ___interopRequireDefault_17(_$extend_53);
-
-var __is_17 = ___interopRequireWildcard_17(_$is_57);
-
-var ___Signals_17 = ___interopRequireDefault_17(_$Signals_46);
-
-function ___interopRequireDefault_17(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_17(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___classCallCheck_17(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_17(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_17(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_17(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_17(Constructor, staticProps); return Constructor; }
-
-var InteractableSet =
-/*#__PURE__*/
-function () {
-  function InteractableSet(scope) {
-    var _this = this;
-
-    ___classCallCheck_17(this, InteractableSet);
-
-    this.scope = scope;
-    this.signals = new ___Signals_17["default"](); // all set interactables
-
-    this.list = [];
-    this.selectorMap = {};
-    this.signals.on('unset', function (_ref) {
-      var interactable = _ref.interactable;
-      var target = interactable.target,
-          context = interactable._context;
-      var targetMappings = __is_17.string(target) ? _this.selectorMap[target] : target[_this.scope.id];
-      var targetIndex = targetMappings.findIndex(function (m) {
-        return m.context === context;
-      });
-
-      if (targetMappings[targetIndex]) {
-        // Destroying mappingInfo's context and interactable
-        targetMappings[targetIndex].context = null;
-        targetMappings[targetIndex].interactable = null;
-      }
-
-      targetMappings.splice(targetIndex, 1);
-    });
-  }
-
-  ___createClass_17(InteractableSet, [{
-    key: "new",
-    value: function _new(target, options) {
-      options = (0, ___extend_17["default"])(options || {}, {
-        actions: this.scope.actions
-      });
-      var interactable = new this.scope.Interactable(target, options, this.scope.document);
-      var mappingInfo = {
-        context: interactable._context,
-        interactable: interactable
-      };
-      this.scope.addDocument(interactable._doc);
-      this.list.push(interactable);
-
-      if (__is_17.string(target)) {
-        if (!this.selectorMap[target]) {
-          this.selectorMap[target] = [];
-        }
-
-        this.selectorMap[target].push(mappingInfo);
-      } else {
-        if (!interactable.target[this.scope.id]) {
-          Object.defineProperty(target, this.scope.id, {
-            value: [],
-            configurable: true
-          });
-        }
-
-        target[this.scope.id].push(mappingInfo);
-      }
-
-      this.signals.fire('new', {
-        target: target,
-        options: options,
-        interactable: interactable,
-        win: this.scope._win
-      });
-      return interactable;
-    }
-  }, {
-    key: "get",
-    value: function get(target, options) {
-      var context = options && options.context || this.scope.document;
-      var isSelector = __is_17.string(target);
-      var targetMappings = isSelector ? this.selectorMap[target] : target[this.scope.id];
-
-      if (!targetMappings) {
-        return null;
-      }
-
-      var found = __arr_17.find(targetMappings, function (m) {
-        return m.context === context && (isSelector || m.interactable.inContext(target));
-      });
-      return found && found.interactable;
-    }
-  }, {
-    key: "forEachMatch",
-    value: function forEachMatch(node, callback) {
-      for (var _i = 0; _i < this.list.length; _i++) {
-        var _ref2;
-
-        _ref2 = this.list[_i];
-        var interactable = _ref2;
-        var ret = void 0;
-
-        if ((__is_17.string(interactable.target) // target is a selector and the element matches
-        ? __is_17.element(node) && __domUtils_17.matchesSelector(node, interactable.target) : // target is the element
-        node === interactable.target) && // the element is in context
-        interactable.inContext(node)) {
-          ret = callback(interactable);
-        }
-
-        if (ret !== undefined) {
-          return ret;
-        }
-      }
-    }
-  }]);
-
-  return InteractableSet;
-}();
-
-_$InteractableSet_17["default"] = InteractableSet;
-
-var _$BaseEvent_13 = {};
-"use strict";
-
-Object.defineProperty(_$BaseEvent_13, "__esModule", {
-  value: true
-});
-_$BaseEvent_13["default"] = _$BaseEvent_13.BaseEvent = _$BaseEvent_13.EventPhase = void 0;
-
-function ___classCallCheck_13(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_13(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_13(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_13(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_13(Constructor, staticProps); return Constructor; }
-
-var EventPhase;
-_$BaseEvent_13.EventPhase = EventPhase;
-
-(function (EventPhase) {
-  EventPhase["Start"] = "start";
-  EventPhase["Move"] = "move";
-  EventPhase["End"] = "end";
-  EventPhase["_NONE"] = "";
-})(EventPhase || (_$BaseEvent_13.EventPhase = EventPhase = {}));
-
-var BaseEvent =
-/*#__PURE__*/
-function () {
-  function BaseEvent(interaction) {
-    ___classCallCheck_13(this, BaseEvent);
-
-    this.immediatePropagationStopped = false;
-    this.propagationStopped = false;
-    this._interaction = interaction;
-  }
-
-  ___createClass_13(BaseEvent, [{
-    key: "preventDefault",
-    value: function preventDefault() {}
-    /**
-     * Don't call any other listeners (even on the current target)
-     */
-
-  }, {
-    key: "stopPropagation",
-    value: function stopPropagation() {
-      this.propagationStopped = true;
-    }
-    /**
-     * Don't call listeners on the remaining targets
-     */
-
-  }, {
-    key: "stopImmediatePropagation",
-    value: function stopImmediatePropagation() {
-      this.immediatePropagationStopped = this.propagationStopped = true;
-    }
-  }, {
-    key: "interaction",
-    get: function get() {
-      return this._interaction._proxy;
-    }
-  }]);
-
-  return BaseEvent;
-}();
-
-_$BaseEvent_13.BaseEvent = BaseEvent;
-var ___default_13 = BaseEvent;
-_$BaseEvent_13["default"] = ___default_13;
-
-var _$InteractEvent_15 = {};
-"use strict";
-
-Object.defineProperty(_$InteractEvent_15, "__esModule", {
-  value: true
-});
-_$InteractEvent_15["default"] = _$InteractEvent_15.InteractEvent = _$InteractEvent_15.EventPhase = void 0;
-
-var ___extend_15 = ___interopRequireDefault_15(_$extend_53);
-
-var ___getOriginXY_15 = ___interopRequireDefault_15(_$getOriginXY_54);
-
-var ___hypot_15 = ___interopRequireDefault_15(_$hypot_55);
-
-var _BaseEvent2 = ___interopRequireDefault_15(_$BaseEvent_13);
-
-var _defaultOptions = ___interopRequireDefault_15(_$defaultOptions_20);
-
-function ___interopRequireDefault_15(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___typeof_15(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ___typeof_15 = function _typeof(obj) { return typeof obj; }; } else { ___typeof_15 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ___typeof_15(obj); }
-
-function ___classCallCheck_15(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_15(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_15(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_15(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_15(Constructor, staticProps); return Constructor; }
-
-function _possibleConstructorReturn(self, call) { if (call && (___typeof_15(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-var __EventPhase_15;
-_$InteractEvent_15.EventPhase = __EventPhase_15;
-
-(function (EventPhase) {
-  EventPhase["Start"] = "start";
-  EventPhase["Move"] = "move";
-  EventPhase["End"] = "end";
-  EventPhase["_NONE"] = "";
-})(__EventPhase_15 || (_$InteractEvent_15.EventPhase = __EventPhase_15 = {}));
-
-var InteractEvent =
-/*#__PURE__*/
-function (_BaseEvent) {
-  _inherits(InteractEvent, _BaseEvent);
-
-  /** */
-  function InteractEvent(interaction, event, actionName, phase, element, related, preEnd, type) {
-    var _this;
-
-    ___classCallCheck_15(this, InteractEvent);
-
-    _this = _possibleConstructorReturn(this, _getPrototypeOf(InteractEvent).call(this, interaction));
-    element = element || interaction.element;
-    var target = interaction.interactable;
-    var deltaSource = (target && target.options || _defaultOptions["default"]).deltaSource;
-    var origin = (0, ___getOriginXY_15["default"])(target, element, actionName);
-    var starting = phase === 'start';
-    var ending = phase === 'end';
-    var prevEvent = starting ? _assertThisInitialized(_this) : interaction.prevEvent;
-    var coords = starting ? interaction.coords.start : ending ? {
-      page: prevEvent.page,
-      client: prevEvent.client,
-      timeStamp: interaction.coords.cur.timeStamp
-    } : interaction.coords.cur;
-    _this.page = (0, ___extend_15["default"])({}, coords.page);
-    _this.client = (0, ___extend_15["default"])({}, coords.client);
-    _this.rect = (0, ___extend_15["default"])({}, interaction.rect);
-    _this.timeStamp = coords.timeStamp;
-
-    if (!ending) {
-      _this.page.x -= origin.x;
-      _this.page.y -= origin.y;
-      _this.client.x -= origin.x;
-      _this.client.y -= origin.y;
-    }
-
-    _this.ctrlKey = event.ctrlKey;
-    _this.altKey = event.altKey;
-    _this.shiftKey = event.shiftKey;
-    _this.metaKey = event.metaKey;
-    _this.button = event.button;
-    _this.buttons = event.buttons;
-    _this.target = element;
-    _this.currentTarget = element;
-    _this.relatedTarget = related || null;
-    _this.preEnd = preEnd;
-    _this.type = type || actionName + (phase || '');
-    _this.interactable = target;
-    _this.t0 = starting ? interaction.pointers[interaction.pointers.length - 1].downTime : prevEvent.t0;
-    _this.x0 = interaction.coords.start.page.x - origin.x;
-    _this.y0 = interaction.coords.start.page.y - origin.y;
-    _this.clientX0 = interaction.coords.start.client.x - origin.x;
-    _this.clientY0 = interaction.coords.start.client.y - origin.y;
-
-    if (starting || ending) {
-      _this.delta = {
-        x: 0,
-        y: 0
-      };
-    } else {
-      _this.delta = {
-        x: _this[deltaSource].x - prevEvent[deltaSource].x,
-        y: _this[deltaSource].y - prevEvent[deltaSource].y
-      };
-    }
-
-    _this.dt = interaction.coords.delta.timeStamp;
-    _this.duration = _this.timeStamp - _this.t0; // velocity and speed in pixels per second
-
-    _this.velocity = (0, ___extend_15["default"])({}, interaction.coords.velocity[deltaSource]);
-    _this.speed = (0, ___hypot_15["default"])(_this.velocity.x, _this.velocity.y);
-    _this.swipe = ending || phase === 'inertiastart' ? _this.getSwipe() : null;
-    return _this;
-  }
-
-  ___createClass_15(InteractEvent, [{
-    key: "getSwipe",
-    value: function getSwipe() {
-      var interaction = this._interaction;
-
-      if (interaction.prevEvent.speed < 600 || this.timeStamp - interaction.prevEvent.timeStamp > 150) {
-        return null;
-      }
-
-      var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI;
-      var overlap = 22.5;
-
-      if (angle < 0) {
-        angle += 360;
-      }
-
-      var left = 135 - overlap <= angle && angle < 225 + overlap;
-      var up = 225 - overlap <= angle && angle < 315 + overlap;
-      var right = !left && (315 - overlap <= angle || angle < 45 + overlap);
-      var down = !up && 45 - overlap <= angle && angle < 135 + overlap;
-      return {
-        up: up,
-        down: down,
-        left: left,
-        right: right,
-        angle: angle,
-        speed: interaction.prevEvent.speed,
-        velocity: {
-          x: interaction.prevEvent.velocityX,
-          y: interaction.prevEvent.velocityY
-        }
-      };
-    }
-  }, {
-    key: "preventDefault",
-    value: function preventDefault() {}
-    /**
-     * Don't call listeners on the remaining targets
-     */
-
-  }, {
-    key: "stopImmediatePropagation",
-    value: function stopImmediatePropagation() {
-      this.immediatePropagationStopped = this.propagationStopped = true;
-    }
-    /**
-     * Don't call any other listeners (even on the current target)
-     */
-
-  }, {
-    key: "stopPropagation",
-    value: function stopPropagation() {
-      this.propagationStopped = true;
-    }
-  }, {
-    key: "pageX",
-    get: function get() {
-      return this.page.x;
-    },
-    set: function set(value) {
-      this.page.x = value;
-    }
-  }, {
-    key: "pageY",
-    get: function get() {
-      return this.page.y;
-    },
-    set: function set(value) {
-      this.page.y = value;
-    }
-  }, {
-    key: "clientX",
-    get: function get() {
-      return this.client.x;
-    },
-    set: function set(value) {
-      this.client.x = value;
-    }
-  }, {
-    key: "clientY",
-    get: function get() {
-      return this.client.y;
-    },
-    set: function set(value) {
-      this.client.y = value;
-    }
-  }, {
-    key: "dx",
-    get: function get() {
-      return this.delta.x;
-    },
-    set: function set(value) {
-      this.delta.x = value;
-    }
-  }, {
-    key: "dy",
-    get: function get() {
-      return this.delta.y;
-    },
-    set: function set(value) {
-      this.delta.y = value;
-    }
-  }, {
-    key: "velocityX",
-    get: function get() {
-      return this.velocity.x;
-    },
-    set: function set(value) {
-      this.velocity.x = value;
-    }
-  }, {
-    key: "velocityY",
-    get: function get() {
-      return this.velocity.y;
-    },
-    set: function set(value) {
-      this.velocity.y = value;
-    }
-  }]);
-
-  return InteractEvent;
-}(_BaseEvent2["default"]);
-
-_$InteractEvent_15.InteractEvent = InteractEvent;
-var ___default_15 = InteractEvent;
-_$InteractEvent_15["default"] = ___default_15;
-
-var _$PointerInfo_19 = {};
-"use strict";
-
-Object.defineProperty(_$PointerInfo_19, "__esModule", {
-  value: true
-});
-_$PointerInfo_19["default"] = _$PointerInfo_19.PointerInfo = void 0;
-
-function ___classCallCheck_19(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-/* eslint-disable @typescript-eslint/no-parameter-properties */
-var PointerInfo = function PointerInfo(id, pointer, event, downTime, downTarget) {
-  ___classCallCheck_19(this, PointerInfo);
-
-  this.id = id;
-  this.pointer = pointer;
-  this.event = event;
-  this.downTime = downTime;
-  this.downTarget = downTarget;
-};
-
-_$PointerInfo_19.PointerInfo = PointerInfo;
-var ___default_19 = PointerInfo;
-_$PointerInfo_19["default"] = ___default_19;
-
-var _$interactionFinder_22 = {};
-"use strict";
-
-Object.defineProperty(_$interactionFinder_22, "__esModule", {
-  value: true
-});
-_$interactionFinder_22["default"] = void 0;
-
-var __dom_22 = ___interopRequireWildcard_22(_$domUtils_51);
-
-function ___interopRequireWildcard_22(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-var finder = {
-  methodOrder: ['simulationResume', 'mouseOrPen', 'hasPointer', 'idle'],
-  search: function search(details) {
-    for (var _i = 0; _i < finder.methodOrder.length; _i++) {
-      var _ref;
-
-      _ref = finder.methodOrder[_i];
-      var method = _ref;
-      var interaction = finder[method](details);
-
-      if (interaction) {
-        return interaction;
-      }
-    }
-  },
-  // try to resume simulation with a new pointer
-  simulationResume: function simulationResume(_ref2) {
-    var pointerType = _ref2.pointerType,
-        eventType = _ref2.eventType,
-        eventTarget = _ref2.eventTarget,
-        scope = _ref2.scope;
-
-    if (!/down|start/i.test(eventType)) {
-      return null;
-    }
-
-    for (var _i2 = 0; _i2 < scope.interactions.list.length; _i2++) {
-      var _ref3;
-
-      _ref3 = scope.interactions.list[_i2];
-      var interaction = _ref3;
-      var element = eventTarget;
-
-      if (interaction.simulation && interaction.simulation.allowResume && interaction.pointerType === pointerType) {
-        while (element) {
-          // if the element is the interaction element
-          if (element === interaction.element) {
-            return interaction;
-          }
-
-          element = __dom_22.parentNode(element);
-        }
-      }
-    }
-
-    return null;
-  },
-  // if it's a mouse or pen interaction
-  mouseOrPen: function mouseOrPen(_ref4) {
-    var pointerId = _ref4.pointerId,
-        pointerType = _ref4.pointerType,
-        eventType = _ref4.eventType,
-        scope = _ref4.scope;
-
-    if (pointerType !== 'mouse' && pointerType !== 'pen') {
-      return null;
-    }
-
-    var firstNonActive;
-
-    for (var _i3 = 0; _i3 < scope.interactions.list.length; _i3++) {
-      var _ref5;
-
-      _ref5 = scope.interactions.list[_i3];
-      var interaction = _ref5;
-
-      if (interaction.pointerType === pointerType) {
-        // if it's a down event, skip interactions with running simulations
-        if (interaction.simulation && !hasPointerId(interaction, pointerId)) {
-          continue;
-        } // if the interaction is active, return it immediately
-
-
-        if (interaction.interacting()) {
-          return interaction;
-        } // otherwise save it and look for another active interaction
-        else if (!firstNonActive) {
-            firstNonActive = interaction;
-          }
-      }
-    } // if no active mouse interaction was found use the first inactive mouse
-    // interaction
-
-
-    if (firstNonActive) {
-      return firstNonActive;
-    } // find any mouse or pen interaction.
-    // ignore the interaction if the eventType is a *down, and a simulation
-    // is active
-
-
-    for (var _i4 = 0; _i4 < scope.interactions.list.length; _i4++) {
-      var _ref6;
-
-      _ref6 = scope.interactions.list[_i4];
-      var _interaction = _ref6;
-
-      if (_interaction.pointerType === pointerType && !(/down/i.test(eventType) && _interaction.simulation)) {
-        return _interaction;
-      }
-    }
-
-    return null;
-  },
-  // get interaction that has this pointer
-  hasPointer: function hasPointer(_ref7) {
-    var pointerId = _ref7.pointerId,
-        scope = _ref7.scope;
-
-    for (var _i5 = 0; _i5 < scope.interactions.list.length; _i5++) {
-      var _ref8;
-
-      _ref8 = scope.interactions.list[_i5];
-      var interaction = _ref8;
-
-      if (hasPointerId(interaction, pointerId)) {
-        return interaction;
-      }
-    }
-
-    return null;
-  },
-  // get first idle interaction with a matching pointerType
-  idle: function idle(_ref9) {
-    var pointerType = _ref9.pointerType,
-        scope = _ref9.scope;
-
-    for (var _i6 = 0; _i6 < scope.interactions.list.length; _i6++) {
-      var _ref10;
-
-      _ref10 = scope.interactions.list[_i6];
-      var interaction = _ref10;
-
-      // if there's already a pointer held down
-      if (interaction.pointers.length === 1) {
-        var target = interaction.interactable; // don't add this pointer if there is a target interactable and it
-        // isn't gesturable
-
-        if (target && !(target.options.gesture && target.options.gesture.enabled)) {
-          continue;
-        }
-      } // maximum of 2 pointers per interaction
-      else if (interaction.pointers.length >= 2) {
-          continue;
-        }
-
-      if (!interaction.interacting() && pointerType === interaction.pointerType) {
-        return interaction;
-      }
-    }
-
-    return null;
-  }
-};
-
-function hasPointerId(interaction, pointerId) {
-  return interaction.pointers.some(function (_ref11) {
-    var id = _ref11.id;
-    return id === pointerId;
-  });
-}
-
-var ___default_22 = finder;
-_$interactionFinder_22["default"] = ___default_22;
-
-var _$drag_1 = {};
-"use strict";
-
-Object.defineProperty(_$drag_1, "__esModule", {
-  value: true
-});
-_$drag_1["default"] = void 0;
-
-var ___scope_1 = _$scope_24({});
-
-var __arr_1 = ___interopRequireWildcard_1(_$arr_47);
-
-var __is_1 = ___interopRequireWildcard_1(_$is_57);
-
-function ___interopRequireWildcard_1(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-___scope_1.ActionName.Drag = 'drag';
-
-function __install_1(scope) {
-  var actions = scope.actions,
-      Interactable = scope.Interactable,
-      interactions = scope.interactions,
-      defaults = scope.defaults;
-  interactions.signals.on('before-action-move', beforeMove);
-  interactions.signals.on('action-resume', beforeMove); // dragmove
-
-  interactions.signals.on('action-move', move);
-  Interactable.prototype.draggable = drag.draggable;
-  actions[___scope_1.ActionName.Drag] = drag;
-  actions.names.push(___scope_1.ActionName.Drag);
-  __arr_1.merge(actions.eventTypes, ['dragstart', 'dragmove', 'draginertiastart', 'dragresume', 'dragend']);
-  actions.methodDict.drag = 'draggable';
-  defaults.actions.drag = drag.defaults;
-}
-
-function beforeMove(_ref) {
-  var interaction = _ref.interaction;
-
-  if (interaction.prepared.name !== 'drag') {
-    return;
-  }
-
-  var axis = interaction.prepared.axis;
-
-  if (axis === 'x') {
-    interaction.coords.cur.page.y = interaction.coords.start.page.y;
-    interaction.coords.cur.client.y = interaction.coords.start.client.y;
-    interaction.coords.velocity.client.y = 0;
-    interaction.coords.velocity.page.y = 0;
-  } else if (axis === 'y') {
-    interaction.coords.cur.page.x = interaction.coords.start.page.x;
-    interaction.coords.cur.client.x = interaction.coords.start.client.x;
-    interaction.coords.velocity.client.x = 0;
-    interaction.coords.velocity.page.x = 0;
-  }
-}
-
-function move(_ref2) {
-  var iEvent = _ref2.iEvent,
-      interaction = _ref2.interaction;
-
-  if (interaction.prepared.name !== 'drag') {
-    return;
-  }
-
-  var axis = interaction.prepared.axis;
-
-  if (axis === 'x' || axis === 'y') {
-    var opposite = axis === 'x' ? 'y' : 'x';
-    iEvent.page[opposite] = interaction.coords.start.page[opposite];
-    iEvent.client[opposite] = interaction.coords.start.client[opposite];
-    iEvent.delta[opposite] = 0;
-  }
-}
-/**
- * ```js
- * interact(element).draggable({
- *     onstart: function (event) {},
- *     onmove : function (event) {},
- *     onend  : function (event) {},
- *
- *     // the axis in which the first movement must be
- *     // for the drag sequence to start
- *     // 'xy' by default - any direction
- *     startAxis: 'x' || 'y' || 'xy',
- *
- *     // 'xy' by default - don't restrict to one axis (move in any direction)
- *     // 'x' or 'y' to restrict movement to either axis
- *     // 'start' to restrict movement to the axis the drag started in
- *     lockAxis: 'x' || 'y' || 'xy' || 'start',
- *
- *     // max number of drags that can happen concurrently
- *     // with elements of this Interactable. Infinity by default
- *     max: Infinity,
- *
- *     // max number of drags that can target the same element+Interactable
- *     // 1 by default
- *     maxPerElement: 2
- * })
- *
- * var isDraggable = interact('element').draggable(); // true
- * ```
- *
- * Get or set whether drag actions can be performed on the target
- *
- * @alias Interactable.prototype.draggable
- *
- * @param {boolean | object} [options] true/false or An object with event
- * listeners to be fired on drag events (object makes the Interactable
- * draggable)
- * @return {boolean | Interactable} boolean indicating if this can be the
- * target of drag events, or this Interctable
- */
-
-
-var draggable = function draggable(options) {
-  if (__is_1.object(options)) {
-    this.options.drag.enabled = options.enabled !== false;
-    this.setPerAction('drag', options);
-    this.setOnEvents('drag', options);
-
-    if (/^(xy|x|y|start)$/.test(options.lockAxis)) {
-      this.options.drag.lockAxis = options.lockAxis;
-    }
-
-    if (/^(xy|x|y)$/.test(options.startAxis)) {
-      this.options.drag.startAxis = options.startAxis;
-    }
-
-    return this;
-  }
-
-  if (__is_1.bool(options)) {
-    this.options.drag.enabled = options;
-    return this;
-  }
-
-  return this.options.drag;
-};
-
-var drag = {
-  id: 'actions/drag',
-  install: __install_1,
-  draggable: draggable,
-  beforeMove: beforeMove,
-  move: move,
-  defaults: {
-    startAxis: 'xy',
-    lockAxis: 'xy'
-  },
-  checker: function checker(_pointer, _event, interactable) {
-    var dragOptions = interactable.options.drag;
-    return dragOptions.enabled ? {
-      name: 'drag',
-      axis: dragOptions.lockAxis === 'start' ? dragOptions.startAxis : dragOptions.lockAxis
-    } : null;
-  },
-  getCursor: function getCursor() {
-    return 'move';
-  }
-};
-var ___default_1 = drag;
-_$drag_1["default"] = ___default_1;
-
-var _$DropEvent_2 = {};
-"use strict";
-
-Object.defineProperty(_$DropEvent_2, "__esModule", {
-  value: true
-});
-_$DropEvent_2["default"] = void 0;
-
-var ___BaseEvent2_2 = ___interopRequireDefault_2(_$BaseEvent_13);
-
-var __arr_2 = ___interopRequireWildcard_2(_$arr_47);
-
-function ___interopRequireWildcard_2(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_2(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___typeof_2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ___typeof_2 = function _typeof(obj) { return typeof obj; }; } else { ___typeof_2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ___typeof_2(obj); }
-
-function ___toConsumableArray_2(arr) { return ___arrayWithoutHoles_2(arr) || ___iterableToArray_2(arr) || ___nonIterableSpread_2(); }
-
-function ___nonIterableSpread_2() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
-
-function ___iterableToArray_2(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
-
-function ___arrayWithoutHoles_2(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
-
-function ___classCallCheck_2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_2(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_2(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_2(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_2(Constructor, staticProps); return Constructor; }
-
-function ___possibleConstructorReturn_2(self, call) { if (call && (___typeof_2(call) === "object" || typeof call === "function")) { return call; } return ___assertThisInitialized_2(self); }
-
-function ___assertThisInitialized_2(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function ___getPrototypeOf_2(o) { ___getPrototypeOf_2 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return ___getPrototypeOf_2(o); }
-
-function ___inherits_2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) ___setPrototypeOf_2(subClass, superClass); }
-
-function ___setPrototypeOf_2(o, p) { ___setPrototypeOf_2 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return ___setPrototypeOf_2(o, p); }
-
-var DropEvent =
-/*#__PURE__*/
-function (_BaseEvent) {
-  ___inherits_2(DropEvent, _BaseEvent);
-
-  /**
-   * Class of events fired on dropzones during drags with acceptable targets.
-   */
-  function DropEvent(dropState, dragEvent, type) {
-    var _this;
-
-    ___classCallCheck_2(this, DropEvent);
-
-    _this = ___possibleConstructorReturn_2(this, ___getPrototypeOf_2(DropEvent).call(this, dragEvent._interaction));
-    _this.propagationStopped = false;
-    _this.immediatePropagationStopped = false;
-
-    var _ref = type === 'dragleave' ? dropState.prev : dropState.cur,
-        element = _ref.element,
-        dropzone = _ref.dropzone;
-
-    _this.type = type;
-    _this.target = element;
-    _this.currentTarget = element;
-    _this.dropzone = dropzone;
-    _this.dragEvent = dragEvent;
-    _this.relatedTarget = dragEvent.target;
-    _this.draggable = dragEvent.interactable;
-    _this.timeStamp = dragEvent.timeStamp;
-    return _this;
-  }
-  /**
-   * If this is a `dropactivate` event, the dropzone element will be
-   * deactivated.
-   *
-   * If this is a `dragmove` or `dragenter`, a `dragleave` will be fired on the
-   * dropzone element and more.
-   */
-
-
-  ___createClass_2(DropEvent, [{
-    key: "reject",
-    value: function reject() {
-      var _this2 = this;
-
-      var dropState = this._interaction.dropState;
-
-      if (this.type !== 'dropactivate' && (!this.dropzone || dropState.cur.dropzone !== this.dropzone || dropState.cur.element !== this.target)) {
-        return;
-      }
-
-      dropState.prev.dropzone = this.dropzone;
-      dropState.prev.element = this.target;
-      dropState.rejected = true;
-      dropState.events.enter = null;
-      this.stopImmediatePropagation();
-
-      if (this.type === 'dropactivate') {
-        var activeDrops = dropState.activeDrops;
-        var index = __arr_2.findIndex(activeDrops, function (_ref2) {
-          var dropzone = _ref2.dropzone,
-              element = _ref2.element;
-          return dropzone === _this2.dropzone && element === _this2.target;
-        });
-        dropState.activeDrops = [].concat(___toConsumableArray_2(activeDrops.slice(0, index)), ___toConsumableArray_2(activeDrops.slice(index + 1)));
-        var deactivateEvent = new DropEvent(dropState, this.dragEvent, 'dropdeactivate');
-        deactivateEvent.dropzone = this.dropzone;
-        deactivateEvent.target = this.target;
-        this.dropzone.fire(deactivateEvent);
-      } else {
-        this.dropzone.fire(new DropEvent(dropState, this.dragEvent, 'dragleave'));
-      }
-    }
-  }, {
-    key: "preventDefault",
-    value: function preventDefault() {}
-  }, {
-    key: "stopPropagation",
-    value: function stopPropagation() {
-      this.propagationStopped = true;
-    }
-  }, {
-    key: "stopImmediatePropagation",
-    value: function stopImmediatePropagation() {
-      this.immediatePropagationStopped = this.propagationStopped = true;
-    }
-  }]);
-
-  return DropEvent;
-}(___BaseEvent2_2["default"]);
-
-var ___default_2 = DropEvent;
-_$DropEvent_2["default"] = ___default_2;
-
-var _$drop_3 = {};
-"use strict";
-
-Object.defineProperty(_$drop_3, "__esModule", {
-  value: true
-});
-_$drop_3["default"] = void 0;
-
-var __utils_3 = ___interopRequireWildcard_3(_$utils_56);
-
-var _drag = ___interopRequireDefault_3(_$drag_1);
-
-var _DropEvent = ___interopRequireDefault_3(_$DropEvent_2);
-
-function ___interopRequireDefault_3(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_3(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __install_3(scope) {
-  var actions = scope.actions,
-      interact = scope.interact,
-      Interactable = scope.Interactable,
-      interactions = scope.interactions,
-      defaults = scope.defaults;
-  scope.usePlugin(_drag["default"]);
-  interactions.signals.on('before-action-start', function (_ref) {
-    var interaction = _ref.interaction;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    }
-
-    interaction.dropState = {
-      cur: {
-        dropzone: null,
-        element: null
-      },
-      prev: {
-        dropzone: null,
-        element: null
-      },
-      rejected: null,
-      events: null,
-      activeDrops: null
-    };
-  });
-  interactions.signals.on('after-action-start', function (_ref2) {
-    var interaction = _ref2.interaction,
-        event = _ref2.event,
-        dragEvent = _ref2.iEvent;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    }
-
-    var dropState = interaction.dropState; // reset active dropzones
-
-    dropState.activeDrops = null;
-    dropState.events = null;
-    dropState.activeDrops = getActiveDrops(scope, interaction.element);
-    dropState.events = getDropEvents(interaction, event, dragEvent);
-
-    if (dropState.events.activate) {
-      fireActivationEvents(dropState.activeDrops, dropState.events.activate);
-    }
-  }); // FIXME proper signal types
-
-  interactions.signals.on('action-move', function (arg) {
-    return onEventCreated(arg, scope);
-  });
-  interactions.signals.on('action-end', function (arg) {
-    return onEventCreated(arg, scope);
-  });
-  interactions.signals.on('after-action-move', function (_ref3) {
-    var interaction = _ref3.interaction;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    }
-
-    fireDropEvents(interaction, interaction.dropState.events);
-    interaction.dropState.events = {};
-  });
-  interactions.signals.on('after-action-end', function (_ref4) {
-    var interaction = _ref4.interaction;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    }
-
-    fireDropEvents(interaction, interaction.dropState.events);
-  });
-  interactions.signals.on('stop', function (_ref5) {
-    var interaction = _ref5.interaction;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    }
-
-    var dropState = interaction.dropState;
-
-    if (dropState) {
-      dropState.activeDrops = null;
-      dropState.events = null;
-      dropState.cur.dropzone = null;
-      dropState.cur.element = null;
-      dropState.prev.dropzone = null;
-      dropState.prev.element = null;
-      dropState.rejected = false;
-    }
-  });
-  /**
-   *
-   * ```js
-   * interact('.drop').dropzone({
-   *   accept: '.can-drop' || document.getElementById('single-drop'),
-   *   overlap: 'pointer' || 'center' || zeroToOne
-   * }
-   * ```
-   *
-   * Returns or sets whether draggables can be dropped onto this target to
-   * trigger drop events
-   *
-   * Dropzones can receive the following events:
-   *  - `dropactivate` and `dropdeactivate` when an acceptable drag starts and ends
-   *  - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone
-   *  - `dragmove` when a draggable that has entered the dropzone is moved
-   *  - `drop` when a draggable is dropped into this dropzone
-   *
-   * Use the `accept` option to allow only elements that match the given CSS
-   * selector or element. The value can be:
-   *
-   *  - **an Element** - only that element can be dropped into this dropzone.
-   *  - **a string**, - the element being dragged must match it as a CSS selector.
-   *  - **`null`** - accept options is cleared - it accepts any element.
-   *
-   * Use the `overlap` option to set how drops are checked for. The allowed
-   * values are:
-   *
-   *   - `'pointer'`, the pointer must be over the dropzone (default)
-   *   - `'center'`, the draggable element's center must be over the dropzone
-   *   - a number from 0-1 which is the `(intersection area) / (draggable area)`.
-   *   e.g. `0.5` for drop to happen when half of the area of the draggable is
-   *   over the dropzone
-   *
-   * Use the `checker` option to specify a function to check if a dragged element
-   * is over this Interactable.
-   *
-   * @param {boolean | object | null} [options] The new options to be set.
-   * @return {boolean | Interactable} The current setting or this Interactable
-   */
-
-  Interactable.prototype.dropzone = function (options) {
-    return dropzoneMethod(this, options);
-  };
-  /**
-   * ```js
-   * interact(target)
-   * .dropChecker(function(dragEvent,         // related dragmove or dragend event
-   *                       event,             // TouchEvent/PointerEvent/MouseEvent
-   *                       dropped,           // bool result of the default checker
-   *                       dropzone,          // dropzone Interactable
-   *                       dropElement,       // dropzone elemnt
-   *                       draggable,         // draggable Interactable
-   *                       draggableElement) {// draggable element
-   *
-   *   return dropped && event.target.hasAttribute('allow-drop')
-   * }
-   * ```
-   */
-
-
-  Interactable.prototype.dropCheck = function (dragEvent, event, draggable, draggableElement, dropElement, rect) {
-    return dropCheckMethod(this, dragEvent, event, draggable, draggableElement, dropElement, rect);
-  };
-  /**
-   * Returns or sets whether the dimensions of dropzone elements are calculated
-   * on every dragmove or only on dragstart for the default dropChecker
-   *
-   * @param {boolean} [newValue] True to check on each move. False to check only
-   * before start
-   * @return {boolean | interact} The current setting or interact
-   */
-
-
-  interact.dynamicDrop = function (newValue) {
-    if (__utils_3.is.bool(newValue)) {
-      // if (dragging && scope.dynamicDrop !== newValue && !newValue) {
-      //  calcRects(dropzones)
-      // }
-      scope.dynamicDrop = newValue;
-      return interact;
-    }
-
-    return scope.dynamicDrop;
-  };
-
-  __utils_3.arr.merge(actions.eventTypes, ['dragenter', 'dragleave', 'dropactivate', 'dropdeactivate', 'dropmove', 'drop']);
-  actions.methodDict.drop = 'dropzone';
-  scope.dynamicDrop = false;
-  defaults.actions.drop = drop.defaults;
-}
-
-function collectDrops(_ref6, draggableElement) {
-  var interactables = _ref6.interactables;
-  var drops = []; // collect all dropzones and their elements which qualify for a drop
-
-  for (var _i = 0; _i < interactables.list.length; _i++) {
-    var _ref7;
-
-    _ref7 = interactables.list[_i];
-    var dropzone = _ref7;
-
-    if (!dropzone.options.drop.enabled) {
-      continue;
-    }
-
-    var accept = dropzone.options.drop.accept; // test the draggable draggableElement against the dropzone's accept setting
-
-    if (__utils_3.is.element(accept) && accept !== draggableElement || __utils_3.is.string(accept) && !__utils_3.dom.matchesSelector(draggableElement, accept) || __utils_3.is.func(accept) && !accept({
-      dropzone: dropzone,
-      draggableElement: draggableElement
-    })) {
-      continue;
-    } // query for new elements if necessary
-
-
-    var dropElements = __utils_3.is.string(dropzone.target) ? dropzone._context.querySelectorAll(dropzone.target) : __utils_3.is.array(dropzone.target) ? dropzone.target : [dropzone.target];
-
-    for (var _i2 = 0; _i2 < dropElements.length; _i2++) {
-      var _ref8;
-
-      _ref8 = dropElements[_i2];
-      var dropzoneElement = _ref8;
-
-      if (dropzoneElement !== draggableElement) {
-        drops.push({
-          dropzone: dropzone,
-          element: dropzoneElement
-        });
-      }
-    }
-  }
-
-  return drops;
-}
-
-function fireActivationEvents(activeDrops, event) {
-  // loop through all active dropzones and trigger event
-  for (var _i3 = 0; _i3 < activeDrops.length; _i3++) {
-    var _ref9;
-
-    _ref9 = activeDrops[_i3];
-    var _ref10 = _ref9,
-        dropzone = _ref10.dropzone,
-        element = _ref10.element;
-    event.dropzone = dropzone; // set current element as event target
-
-    event.target = element;
-    dropzone.fire(event);
-    event.propagationStopped = event.immediatePropagationStopped = false;
-  }
-} // return a new array of possible drops. getActiveDrops should always be
-// called when a drag has just started or a drag event happens while
-// dynamicDrop is true
-
-
-function getActiveDrops(scope, dragElement) {
-  // get dropzones and their elements that could receive the draggable
-  var activeDrops = collectDrops(scope, dragElement);
-
-  for (var _i4 = 0; _i4 < activeDrops.length; _i4++) {
-    var _ref11;
-
-    _ref11 = activeDrops[_i4];
-    var activeDrop = _ref11;
-    activeDrop.rect = activeDrop.dropzone.getRect(activeDrop.element);
-  }
-
-  return activeDrops;
-}
-
-function getDrop(_ref12, dragEvent, pointerEvent) {
-  var dropState = _ref12.dropState,
-      draggable = _ref12.interactable,
-      dragElement = _ref12.element;
-  var validDrops = []; // collect all dropzones and their elements which qualify for a drop
-
-  for (var _i5 = 0; _i5 < dropState.activeDrops.length; _i5++) {
-    var _ref13;
-
-    _ref13 = dropState.activeDrops[_i5];
-    var _ref14 = _ref13,
-        dropzone = _ref14.dropzone,
-        dropzoneElement = _ref14.element,
-        rect = _ref14.rect;
-    validDrops.push(dropzone.dropCheck(dragEvent, pointerEvent, draggable, dragElement, dropzoneElement, rect) ? dropzoneElement : null);
-  } // get the most appropriate dropzone based on DOM depth and order
-
-
-  var dropIndex = __utils_3.dom.indexOfDeepestElement(validDrops);
-  return dropState.activeDrops[dropIndex] || null;
-}
-
-function getDropEvents(interaction, _pointerEvent, dragEvent) {
-  var dropState = interaction.dropState;
-  var dropEvents = {
-    enter: null,
-    leave: null,
-    activate: null,
-    deactivate: null,
-    move: null,
-    drop: null
-  };
-
-  if (dragEvent.type === 'dragstart') {
-    dropEvents.activate = new _DropEvent["default"](dropState, dragEvent, 'dropactivate');
-    dropEvents.activate.target = null;
-    dropEvents.activate.dropzone = null;
-  }
-
-  if (dragEvent.type === 'dragend') {
-    dropEvents.deactivate = new _DropEvent["default"](dropState, dragEvent, 'dropdeactivate');
-    dropEvents.deactivate.target = null;
-    dropEvents.deactivate.dropzone = null;
-  }
-
-  if (dropState.rejected) {
-    return dropEvents;
-  }
-
-  if (dropState.cur.element !== dropState.prev.element) {
-    // if there was a previous dropzone, create a dragleave event
-    if (dropState.prev.dropzone) {
-      dropEvents.leave = new _DropEvent["default"](dropState, dragEvent, 'dragleave');
-      dragEvent.dragLeave = dropEvents.leave.target = dropState.prev.element;
-      dragEvent.prevDropzone = dropEvents.leave.dropzone = dropState.prev.dropzone;
-    } // if dropzone is not null, create a dragenter event
-
-
-    if (dropState.cur.dropzone) {
-      dropEvents.enter = new _DropEvent["default"](dropState, dragEvent, 'dragenter');
-      dragEvent.dragEnter = dropState.cur.element;
-      dragEvent.dropzone = dropState.cur.dropzone;
-    }
-  }
-
-  if (dragEvent.type === 'dragend' && dropState.cur.dropzone) {
-    dropEvents.drop = new _DropEvent["default"](dropState, dragEvent, 'drop');
-    dragEvent.dropzone = dropState.cur.dropzone;
-    dragEvent.relatedTarget = dropState.cur.element;
-  }
-
-  if (dragEvent.type === 'dragmove' && dropState.cur.dropzone) {
-    dropEvents.move = new _DropEvent["default"](dropState, dragEvent, 'dropmove');
-    dropEvents.move.dragmove = dragEvent;
-    dragEvent.dropzone = dropState.cur.dropzone;
-  }
-
-  return dropEvents;
-}
-
-function fireDropEvents(interaction, events) {
-  var dropState = interaction.dropState;
-  var activeDrops = dropState.activeDrops,
-      cur = dropState.cur,
-      prev = dropState.prev;
-
-  if (events.leave) {
-    prev.dropzone.fire(events.leave);
-  }
-
-  if (events.move) {
-    cur.dropzone.fire(events.move);
-  }
-
-  if (events.enter) {
-    cur.dropzone.fire(events.enter);
-  }
-
-  if (events.drop) {
-    cur.dropzone.fire(events.drop);
-  }
-
-  if (events.deactivate) {
-    fireActivationEvents(activeDrops, events.deactivate);
-  }
-
-  dropState.prev.dropzone = cur.dropzone;
-  dropState.prev.element = cur.element;
-}
-
-function onEventCreated(_ref15, scope) {
-  var interaction = _ref15.interaction,
-      iEvent = _ref15.iEvent,
-      event = _ref15.event;
-
-  if (iEvent.type !== 'dragmove' && iEvent.type !== 'dragend') {
-    return;
-  }
-
-  var dropState = interaction.dropState;
-
-  if (scope.dynamicDrop) {
-    dropState.activeDrops = getActiveDrops(scope, interaction.element);
-  }
-
-  var dragEvent = iEvent;
-  var dropResult = getDrop(interaction, dragEvent, event); // update rejected status
-
-  dropState.rejected = dropState.rejected && !!dropResult && dropResult.dropzone === dropState.cur.dropzone && dropResult.element === dropState.cur.element;
-  dropState.cur.dropzone = dropResult && dropResult.dropzone;
-  dropState.cur.element = dropResult && dropResult.element;
-  dropState.events = getDropEvents(interaction, event, dragEvent);
-}
-
-function dropzoneMethod(interactable, options) {
-  if (__utils_3.is.object(options)) {
-    interactable.options.drop.enabled = options.enabled !== false;
-
-    if (options.listeners) {
-      var normalized = __utils_3.normalizeListeners(options.listeners); // rename 'drop' to '' as it will be prefixed with 'drop'
-
-      var corrected = Object.keys(normalized).reduce(function (acc, type) {
-        var correctedType = /^(enter|leave)/.test(type) ? "drag".concat(type) : /^(activate|deactivate|move)/.test(type) ? "drop".concat(type) : type;
-        acc[correctedType] = normalized[type];
-        return acc;
-      }, {});
-      interactable.off(interactable.options.drop.listeners);
-      interactable.on(corrected);
-      interactable.options.drop.listeners = corrected;
-    }
-
-    if (__utils_3.is.func(options.ondrop)) {
-      interactable.on('drop', options.ondrop);
-    }
-
-    if (__utils_3.is.func(options.ondropactivate)) {
-      interactable.on('dropactivate', options.ondropactivate);
-    }
-
-    if (__utils_3.is.func(options.ondropdeactivate)) {
-      interactable.on('dropdeactivate', options.ondropdeactivate);
-    }
-
-    if (__utils_3.is.func(options.ondragenter)) {
-      interactable.on('dragenter', options.ondragenter);
-    }
-
-    if (__utils_3.is.func(options.ondragleave)) {
-      interactable.on('dragleave', options.ondragleave);
-    }
-
-    if (__utils_3.is.func(options.ondropmove)) {
-      interactable.on('dropmove', options.ondropmove);
-    }
-
-    if (/^(pointer|center)$/.test(options.overlap)) {
-      interactable.options.drop.overlap = options.overlap;
-    } else if (__utils_3.is.number(options.overlap)) {
-      interactable.options.drop.overlap = Math.max(Math.min(1, options.overlap), 0);
-    }
-
-    if ('accept' in options) {
-      interactable.options.drop.accept = options.accept;
-    }
-
-    if ('checker' in options) {
-      interactable.options.drop.checker = options.checker;
-    }
-
-    return interactable;
-  }
-
-  if (__utils_3.is.bool(options)) {
-    interactable.options.drop.enabled = options;
-    return interactable;
-  }
-
-  return interactable.options.drop;
-}
-
-function dropCheckMethod(interactable, dragEvent, event, draggable, draggableElement, dropElement, rect) {
-  var dropped = false; // if the dropzone has no rect (eg. display: none)
-  // call the custom dropChecker or just return false
-
-  if (!(rect = rect || interactable.getRect(dropElement))) {
-    return interactable.options.drop.checker ? interactable.options.drop.checker(dragEvent, event, dropped, interactable, dropElement, draggable, draggableElement) : false;
-  }
-
-  var dropOverlap = interactable.options.drop.overlap;
-
-  if (dropOverlap === 'pointer') {
-    var origin = __utils_3.getOriginXY(draggable, draggableElement, 'drag');
-    var page = __utils_3.pointer.getPageXY(dragEvent);
-    page.x += origin.x;
-    page.y += origin.y;
-    var horizontal = page.x > rect.left && page.x < rect.right;
-    var vertical = page.y > rect.top && page.y < rect.bottom;
-    dropped = horizontal && vertical;
-  }
-
-  var dragRect = draggable.getRect(draggableElement);
-
-  if (dragRect && dropOverlap === 'center') {
-    var cx = dragRect.left + dragRect.width / 2;
-    var cy = dragRect.top + dragRect.height / 2;
-    dropped = cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom;
-  }
-
-  if (dragRect && __utils_3.is.number(dropOverlap)) {
-    var overlapArea = Math.max(0, Math.min(rect.right, dragRect.right) - Math.max(rect.left, dragRect.left)) * Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top, dragRect.top));
-    var overlapRatio = overlapArea / (dragRect.width * dragRect.height);
-    dropped = overlapRatio >= dropOverlap;
-  }
-
-  if (interactable.options.drop.checker) {
-    dropped = interactable.options.drop.checker(dragEvent, event, dropped, interactable, dropElement, draggable, draggableElement);
-  }
-
-  return dropped;
-}
-
-var drop = {
-  id: 'actions/drop',
-  install: __install_3,
-  getActiveDrops: getActiveDrops,
-  getDrop: getDrop,
-  getDropEvents: getDropEvents,
-  fireDropEvents: fireDropEvents,
-  defaults: {
-    enabled: false,
-    accept: null,
-    overlap: 'pointer'
-  }
-};
-var ___default_3 = drop;
-_$drop_3["default"] = ___default_3;
-
-var _$gesture_4 = {};
-"use strict";
-
-Object.defineProperty(_$gesture_4, "__esModule", {
-  value: true
-});
-_$gesture_4["default"] = void 0;
-
-var ___InteractEvent_4 = ___interopRequireDefault_4(_$InteractEvent_15);
-
-var ___scope_4 = _$scope_24({});
-
-var __utils_4 = ___interopRequireWildcard_4(_$utils_56);
-
-function ___interopRequireWildcard_4(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_4(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-___scope_4.ActionName.Gesture = 'gesture';
-
-function __install_4(scope) {
-  var actions = scope.actions,
-      Interactable = scope.Interactable,
-      interactions = scope.interactions,
-      defaults = scope.defaults;
-  /**
-   * ```js
-   * interact(element).gesturable({
-   *     onstart: function (event) {},
-   *     onmove : function (event) {},
-   *     onend  : function (event) {},
-   *
-   *     // limit multiple gestures.
-   *     // See the explanation in {@link Interactable.draggable} example
-   *     max: Infinity,
-   *     maxPerElement: 1,
-   * })
-   *
-   * var isGestureable = interact(element).gesturable()
-   * ```
-   *
-   * Gets or sets whether multitouch gestures can be performed on the target
-   *
-   * @param {boolean | object} [options] true/false or An object with event
-   * listeners to be fired on gesture events (makes the Interactable gesturable)
-   * @return {boolean | Interactable} A boolean indicating if this can be the
-   * target of gesture events, or this Interactable
-   */
-
-  Interactable.prototype.gesturable = function (options) {
-    if (__utils_4.is.object(options)) {
-      this.options.gesture.enabled = options.enabled !== false;
-      this.setPerAction('gesture', options);
-      this.setOnEvents('gesture', options);
-      return this;
-    }
-
-    if (__utils_4.is.bool(options)) {
-      this.options.gesture.enabled = options;
-      return this;
-    }
-
-    return this.options.gesture;
-  };
-
-  interactions.signals.on('action-start', updateGestureProps);
-  interactions.signals.on('action-move', updateGestureProps);
-  interactions.signals.on('action-end', updateGestureProps);
-  interactions.signals.on('new', function (_ref) {
-    var interaction = _ref.interaction;
-    interaction.gesture = {
-      angle: 0,
-      distance: 0,
-      scale: 1,
-      startAngle: 0,
-      startDistance: 0
-    };
-  });
-  actions[___scope_4.ActionName.Gesture] = gesture;
-  actions.names.push(___scope_4.ActionName.Gesture);
-  __utils_4.arr.merge(actions.eventTypes, ['gesturestart', 'gesturemove', 'gestureend']);
-  actions.methodDict.gesture = 'gesturable';
-  defaults.actions.gesture = gesture.defaults;
-}
-
-var gesture = {
-  id: 'actions/gesture',
-  install: __install_4,
-  defaults: {},
-  checker: function checker(_pointer, _event, _interactable, _element, interaction) {
-    if (interaction.pointers.length >= 2) {
-      return {
-        name: 'gesture'
-      };
-    }
-
-    return null;
-  },
-  getCursor: function getCursor() {
-    return '';
-  }
-};
-
-function updateGestureProps(_ref2) {
-  var interaction = _ref2.interaction,
-      iEvent = _ref2.iEvent,
-      event = _ref2.event,
-      phase = _ref2.phase;
-
-  if (interaction.prepared.name !== 'gesture') {
-    return;
-  }
-
-  var pointers = interaction.pointers.map(function (p) {
-    return p.pointer;
-  });
-  var starting = phase === 'start';
-  var ending = phase === 'end';
-  var deltaSource = interaction.interactable.options.deltaSource;
-  iEvent.touches = [pointers[0], pointers[1]];
-
-  if (starting) {
-    iEvent.distance = __utils_4.pointer.touchDistance(pointers, deltaSource);
-    iEvent.box = __utils_4.pointer.touchBBox(pointers);
-    iEvent.scale = 1;
-    iEvent.ds = 0;
-    iEvent.angle = __utils_4.pointer.touchAngle(pointers, deltaSource);
-    iEvent.da = 0;
-    interaction.gesture.startDistance = iEvent.distance;
-    interaction.gesture.startAngle = iEvent.angle;
-  } else if (ending || event instanceof ___InteractEvent_4["default"]) {
-    var prevEvent = interaction.prevEvent;
-    iEvent.distance = prevEvent.distance;
-    iEvent.box = prevEvent.box;
-    iEvent.scale = prevEvent.scale;
-    iEvent.ds = 0;
-    iEvent.angle = prevEvent.angle;
-    iEvent.da = 0;
-  } else {
-    iEvent.distance = __utils_4.pointer.touchDistance(pointers, deltaSource);
-    iEvent.box = __utils_4.pointer.touchBBox(pointers);
-    iEvent.scale = iEvent.distance / interaction.gesture.startDistance;
-    iEvent.angle = __utils_4.pointer.touchAngle(pointers, deltaSource);
-    iEvent.ds = iEvent.scale - interaction.gesture.scale;
-    iEvent.da = iEvent.angle - interaction.gesture.angle;
-  }
-
-  interaction.gesture.distance = iEvent.distance;
-  interaction.gesture.angle = iEvent.angle;
-
-  if (__utils_4.is.number(iEvent.scale) && iEvent.scale !== Infinity && !isNaN(iEvent.scale)) {
-    interaction.gesture.scale = iEvent.scale;
-  }
-}
-
-var ___default_4 = gesture;
-_$gesture_4["default"] = ___default_4;
-
-var _$resize_6 = {};
-"use strict";
-
-Object.defineProperty(_$resize_6, "__esModule", {
-  value: true
-});
-_$resize_6["default"] = void 0;
-
-var ___scope_6 = _$scope_24({});
-
-var __arr_6 = ___interopRequireWildcard_6(_$arr_47);
-
-var __dom_6 = ___interopRequireWildcard_6(_$domUtils_51);
-
-var ___extend_6 = ___interopRequireDefault_6(_$extend_53);
-
-var __is_6 = ___interopRequireWildcard_6(_$is_57);
-
-function ___interopRequireDefault_6(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_6(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-___scope_6.ActionName.Resize = 'resize';
-
-function __install_6(scope) {
-  var actions = scope.actions,
-      browser = scope.browser,
-      Interactable = scope.Interactable,
-      interactions = scope.interactions,
-      defaults = scope.defaults; // Less Precision with touch input
-
-  interactions.signals.on('new', function (interaction) {
-    interaction.resizeAxes = 'xy';
-  });
-  interactions.signals.on('action-start', start);
-  interactions.signals.on('action-move', __move_6);
-  interactions.signals.on('action-end', end);
-  interactions.signals.on('action-start', updateEventAxes);
-  interactions.signals.on('action-move', updateEventAxes);
-  resize.cursors = initCursors(browser);
-  resize.defaultMargin = browser.supportsTouch || browser.supportsPointerEvent ? 20 : 10;
-  /**
-   * ```js
-   * interact(element).resizable({
-   *   onstart: function (event) {},
-   *   onmove : function (event) {},
-   *   onend  : function (event) {},
-   *
-   *   edges: {
-   *     top   : true,       // Use pointer coords to check for resize.
-   *     left  : false,      // Disable resizing from left edge.
-   *     bottom: '.resize-s',// Resize if pointer target matches selector
-   *     right : handleEl    // Resize if pointer target is the given Element
-   *   },
-   *
-   *     // Width and height can be adjusted independently. When `true`, width and
-   *     // height are adjusted at a 1:1 ratio.
-   *     square: false,
-   *
-   *     // Width and height can be adjusted independently. When `true`, width and
-   *     // height maintain the aspect ratio they had when resizing started.
-   *     preserveAspectRatio: false,
-   *
-   *   // a value of 'none' will limit the resize rect to a minimum of 0x0
-   *   // 'negate' will allow the rect to have negative width/height
-   *   // 'reposition' will keep the width/height positive by swapping
-   *   // the top and bottom edges and/or swapping the left and right edges
-   *   invert: 'none' || 'negate' || 'reposition'
-   *
-   *   // limit multiple resizes.
-   *   // See the explanation in the {@link Interactable.draggable} example
-   *   max: Infinity,
-   *   maxPerElement: 1,
-   * })
-   *
-   * var isResizeable = interact(element).resizable()
-   * ```
-   *
-   * Gets or sets whether resize actions can be performed on the target
-   *
-   * @param {boolean | object} [options] true/false or An object with event
-   * listeners to be fired on resize events (object makes the Interactable
-   * resizable)
-   * @return {boolean | Interactable} A boolean indicating if this can be the
-   * target of resize elements, or this Interactable
-   */
-
-  Interactable.prototype.resizable = function (options) {
-    return resizable(this, options, scope);
-  };
-
-  actions[___scope_6.ActionName.Resize] = resize;
-  actions.names.push(___scope_6.ActionName.Resize);
-  __arr_6.merge(actions.eventTypes, ['resizestart', 'resizemove', 'resizeinertiastart', 'resizeresume', 'resizeend']);
-  actions.methodDict.resize = 'resizable';
-  defaults.actions.resize = resize.defaults;
-}
-
-var resize = {
-  id: 'actions/resize',
-  install: __install_6,
-  defaults: {
-    square: false,
-    preserveAspectRatio: false,
-    axis: 'xy',
-    // use default margin
-    margin: NaN,
-    // object with props left, right, top, bottom which are
-    // true/false values to resize when the pointer is over that edge,
-    // CSS selectors to match the handles for each direction
-    // or the Elements for each handle
-    edges: null,
-    // a value of 'none' will limit the resize rect to a minimum of 0x0
-    // 'negate' will alow the rect to have negative width/height
-    // 'reposition' will keep the width/height positive by swapping
-    // the top and bottom edges and/or swapping the left and right edges
-    invert: 'none'
-  },
-  checker: function checker(_pointer, _event, interactable, element, interaction, rect) {
-    if (!rect) {
-      return null;
-    }
-
-    var page = (0, ___extend_6["default"])({}, interaction.coords.cur.page);
-    var options = interactable.options;
-
-    if (options.resize.enabled) {
-      var resizeOptions = options.resize;
-      var resizeEdges = {
-        left: false,
-        right: false,
-        top: false,
-        bottom: false
-      }; // if using resize.edges
-
-      if (__is_6.object(resizeOptions.edges)) {
-        for (var edge in resizeEdges) {
-          resizeEdges[edge] = checkResizeEdge(edge, resizeOptions.edges[edge], page, interaction._latestPointer.eventTarget, element, rect, resizeOptions.margin || this.defaultMargin);
-        }
-
-        resizeEdges.left = resizeEdges.left && !resizeEdges.right;
-        resizeEdges.top = resizeEdges.top && !resizeEdges.bottom;
-
-        if (resizeEdges.left || resizeEdges.right || resizeEdges.top || resizeEdges.bottom) {
-          return {
-            name: 'resize',
-            edges: resizeEdges
-          };
-        }
-      } else {
-        var right = options.resize.axis !== 'y' && page.x > rect.right - this.defaultMargin;
-        var bottom = options.resize.axis !== 'x' && page.y > rect.bottom - this.defaultMargin;
-
-        if (right || bottom) {
-          return {
-            name: 'resize',
-            axes: (right ? 'x' : '') + (bottom ? 'y' : '')
-          };
-        }
-      }
-    }
-
-    return null;
-  },
-  cursors: null,
-  getCursor: function getCursor(_ref) {
-    var edges = _ref.edges,
-        axis = _ref.axis,
-        name = _ref.name;
-    var cursors = resize.cursors;
-    var result = null;
-
-    if (axis) {
-      result = cursors[name + axis];
-    } else if (edges) {
-      var cursorKey = '';
-      var _arr = ['top', 'bottom', 'left', 'right'];
-
-      for (var _i = 0; _i < _arr.length; _i++) {
-        var edge = _arr[_i];
-
-        if (edges[edge]) {
-          cursorKey += edge;
-        }
-      }
-
-      result = cursors[cursorKey];
-    }
-
-    return result;
-  },
-  defaultMargin: null
-};
-
-function resizable(interactable, options, scope) {
-  if (__is_6.object(options)) {
-    interactable.options.resize.enabled = options.enabled !== false;
-    interactable.setPerAction('resize', options);
-    interactable.setOnEvents('resize', options);
-
-    if (__is_6.string(options.axis) && /^x$|^y$|^xy$/.test(options.axis)) {
-      interactable.options.resize.axis = options.axis;
-    } else if (options.axis === null) {
-      interactable.options.resize.axis = scope.defaults.actions.resize.axis;
-    }
-
-    if (__is_6.bool(options.preserveAspectRatio)) {
-      interactable.options.resize.preserveAspectRatio = options.preserveAspectRatio;
-    } else if (__is_6.bool(options.square)) {
-      interactable.options.resize.square = options.square;
-    }
-
-    return interactable;
-  }
-
-  if (__is_6.bool(options)) {
-    interactable.options.resize.enabled = options;
-    return interactable;
-  }
-
-  return interactable.options.resize;
-}
-
-function checkResizeEdge(name, value, page, element, interactableElement, rect, margin) {
-  // false, '', undefined, null
-  if (!value) {
-    return false;
-  } // true value, use pointer coords and element rect
-
-
-  if (value === true) {
-    // if dimensions are negative, "switch" edges
-    var width = __is_6.number(rect.width) ? rect.width : rect.right - rect.left;
-    var height = __is_6.number(rect.height) ? rect.height : rect.bottom - rect.top; // don't use margin greater than half the relevent dimension
-
-    margin = Math.min(margin, (name === 'left' || name === 'right' ? width : height) / 2);
-
-    if (width < 0) {
-      if (name === 'left') {
-        name = 'right';
-      } else if (name === 'right') {
-        name = 'left';
-      }
-    }
-
-    if (height < 0) {
-      if (name === 'top') {
-        name = 'bottom';
-      } else if (name === 'bottom') {
-        name = 'top';
-      }
-    }
-
-    if (name === 'left') {
-      return page.x < (width >= 0 ? rect.left : rect.right) + margin;
-    }
-
-    if (name === 'top') {
-      return page.y < (height >= 0 ? rect.top : rect.bottom) + margin;
-    }
-
-    if (name === 'right') {
-      return page.x > (width >= 0 ? rect.right : rect.left) - margin;
-    }
-
-    if (name === 'bottom') {
-      return page.y > (height >= 0 ? rect.bottom : rect.top) - margin;
-    }
-  } // the remaining checks require an element
-
-
-  if (!__is_6.element(element)) {
-    return false;
-  }
-
-  return __is_6.element(value) // the value is an element to use as a resize handle
-  ? value === element // otherwise check if element matches value as selector
-  : __dom_6.matchesUpTo(element, value, interactableElement);
-}
-
-function initCursors(browser) {
-  return browser.isIe9 ? {
-    x: 'e-resize',
-    y: 's-resize',
-    xy: 'se-resize',
-    top: 'n-resize',
-    left: 'w-resize',
-    bottom: 's-resize',
-    right: 'e-resize',
-    topleft: 'se-resize',
-    bottomright: 'se-resize',
-    topright: 'ne-resize',
-    bottomleft: 'ne-resize'
-  } : {
-    x: 'ew-resize',
-    y: 'ns-resize',
-    xy: 'nwse-resize',
-    top: 'ns-resize',
-    left: 'ew-resize',
-    bottom: 'ns-resize',
-    right: 'ew-resize',
-    topleft: 'nwse-resize',
-    bottomright: 'nwse-resize',
-    topright: 'nesw-resize',
-    bottomleft: 'nesw-resize'
-  };
-}
-
-function start(_ref2) {
-  var iEvent = _ref2.iEvent,
-      interaction = _ref2.interaction;
-
-  if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) {
-    return;
-  }
-
-  var startRect = (0, ___extend_6["default"])({}, interaction.rect);
-  var resizeOptions = interaction.interactable.options.resize;
-  /*
-   * When using the `resizable.square` or `resizable.preserveAspectRatio` options, resizing from one edge
-   * will affect another. E.g. with `resizable.square`, resizing to make the right edge larger will make
-   * the bottom edge larger by the same amount. We call these 'linked' edges. Any linked edges will depend
-   * on the active edges and the edge being interacted with.
-   */
-
-  if (resizeOptions.square || resizeOptions.preserveAspectRatio) {
-    var linkedEdges = (0, ___extend_6["default"])({}, interaction.prepared.edges);
-    linkedEdges.top = linkedEdges.top || linkedEdges.left && !linkedEdges.bottom;
-    linkedEdges.left = linkedEdges.left || linkedEdges.top && !linkedEdges.right;
-    linkedEdges.bottom = linkedEdges.bottom || linkedEdges.right && !linkedEdges.top;
-    linkedEdges.right = linkedEdges.right || linkedEdges.bottom && !linkedEdges.left;
-    interaction.prepared._linkedEdges = linkedEdges;
-  } else {
-    interaction.prepared._linkedEdges = null;
-  } // if using `resizable.preserveAspectRatio` option, record aspect ratio at the start of the resize
-
-
-  if (resizeOptions.preserveAspectRatio) {
-    interaction.resizeStartAspectRatio = startRect.width / startRect.height;
-  }
-
-  interaction.resizeRects = {
-    start: startRect,
-    current: {
-      left: startRect.left,
-      right: startRect.right,
-      top: startRect.top,
-      bottom: startRect.bottom
-    },
-    inverted: (0, ___extend_6["default"])({}, startRect),
-    previous: (0, ___extend_6["default"])({}, startRect),
-    delta: {
-      left: 0,
-      right: 0,
-      width: 0,
-      top: 0,
-      bottom: 0,
-      height: 0
-    }
-  };
-  iEvent.edges = interaction.prepared.edges;
-  iEvent.rect = interaction.resizeRects.inverted;
-  iEvent.deltaRect = interaction.resizeRects.delta;
-}
-
-function __move_6(_ref3) {
-  var iEvent = _ref3.iEvent,
-      interaction = _ref3.interaction;
-
-  if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) {
-    return;
-  }
-
-  var resizeOptions = interaction.interactable.options.resize;
-  var invert = resizeOptions.invert;
-  var invertible = invert === 'reposition' || invert === 'negate';
-  var edges = interaction.prepared.edges; // eslint-disable-next-line no-shadow
-
-  var start = interaction.resizeRects.start;
-  var current = interaction.resizeRects.current;
-  var inverted = interaction.resizeRects.inverted;
-  var deltaRect = interaction.resizeRects.delta;
-  var previous = (0, ___extend_6["default"])(interaction.resizeRects.previous, inverted);
-  var originalEdges = edges;
-  var eventDelta = (0, ___extend_6["default"])({}, iEvent.delta);
-
-  if (resizeOptions.preserveAspectRatio || resizeOptions.square) {
-    // `resize.preserveAspectRatio` takes precedence over `resize.square`
-    var startAspectRatio = resizeOptions.preserveAspectRatio ? interaction.resizeStartAspectRatio : 1;
-    edges = interaction.prepared._linkedEdges;
-
-    if (originalEdges.left && originalEdges.bottom || originalEdges.right && originalEdges.top) {
-      eventDelta.y = -eventDelta.x / startAspectRatio;
-    } else if (originalEdges.left || originalEdges.right) {
-      eventDelta.y = eventDelta.x / startAspectRatio;
-    } else if (originalEdges.top || originalEdges.bottom) {
-      eventDelta.x = eventDelta.y * startAspectRatio;
-    }
-  } // update the 'current' rect without modifications
-
-
-  if (edges.top) {
-    current.top += eventDelta.y;
-  }
-
-  if (edges.bottom) {
-    current.bottom += eventDelta.y;
-  }
-
-  if (edges.left) {
-    current.left += eventDelta.x;
-  }
-
-  if (edges.right) {
-    current.right += eventDelta.x;
-  }
-
-  if (invertible) {
-    // if invertible, copy the current rect
-    (0, ___extend_6["default"])(inverted, current);
-
-    if (invert === 'reposition') {
-      // swap edge values if necessary to keep width/height positive
-      var swap;
-
-      if (inverted.top > inverted.bottom) {
-        swap = inverted.top;
-        inverted.top = inverted.bottom;
-        inverted.bottom = swap;
-      }
-
-      if (inverted.left > inverted.right) {
-        swap = inverted.left;
-        inverted.left = inverted.right;
-        inverted.right = swap;
-      }
-    }
-  } else {
-    // if not invertible, restrict to minimum of 0x0 rect
-    inverted.top = Math.min(current.top, start.bottom);
-    inverted.bottom = Math.max(current.bottom, start.top);
-    inverted.left = Math.min(current.left, start.right);
-    inverted.right = Math.max(current.right, start.left);
-  }
-
-  inverted.width = inverted.right - inverted.left;
-  inverted.height = inverted.bottom - inverted.top;
-
-  for (var edge in inverted) {
-    deltaRect[edge] = inverted[edge] - previous[edge];
-  }
-
-  iEvent.edges = interaction.prepared.edges;
-  iEvent.rect = inverted;
-  iEvent.deltaRect = deltaRect;
-}
-
-function end(_ref4) {
-  var iEvent = _ref4.iEvent,
-      interaction = _ref4.interaction;
-
-  if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) {
-    return;
-  }
-
-  iEvent.edges = interaction.prepared.edges;
-  iEvent.rect = interaction.resizeRects.inverted;
-  iEvent.deltaRect = interaction.resizeRects.delta;
-}
-
-function updateEventAxes(_ref5) {
-  var iEvent = _ref5.iEvent,
-      interaction = _ref5.interaction,
-      action = _ref5.action;
-
-  if (action !== ___scope_6.ActionName.Resize || !interaction.resizeAxes) {
-    return;
-  }
-
-  var options = interaction.interactable.options;
-
-  if (options.resize.square) {
-    if (interaction.resizeAxes === 'y') {
-      iEvent.delta.x = iEvent.delta.y;
-    } else {
-      iEvent.delta.y = iEvent.delta.x;
-    }
-
-    iEvent.axes = 'xy';
-  } else {
-    iEvent.axes = interaction.resizeAxes;
-
-    if (interaction.resizeAxes === 'x') {
-      iEvent.delta.y = 0;
-    } else if (interaction.resizeAxes === 'y') {
-      iEvent.delta.x = 0;
-    }
-  }
-}
-
-var ___default_6 = resize;
-_$resize_6["default"] = ___default_6;
-
-var _$actions_5 = {};
-"use strict";
-
-Object.defineProperty(_$actions_5, "__esModule", {
-  value: true
-});
-_$actions_5.install = __install_5;
-Object.defineProperty(_$actions_5, "drag", {
-  enumerable: true,
-  get: function get() {
-    return ___drag_5["default"];
-  }
-});
-Object.defineProperty(_$actions_5, "drop", {
-  enumerable: true,
-  get: function get() {
-    return _drop["default"];
-  }
-});
-Object.defineProperty(_$actions_5, "gesture", {
-  enumerable: true,
-  get: function get() {
-    return _gesture["default"];
-  }
-});
-Object.defineProperty(_$actions_5, "resize", {
-  enumerable: true,
-  get: function get() {
-    return _resize["default"];
-  }
-});
-_$actions_5.id = void 0;
-
-var ___drag_5 = ___interopRequireDefault_5(_$drag_1);
-
-var _drop = ___interopRequireDefault_5(_$drop_3);
-
-var _gesture = ___interopRequireDefault_5(_$gesture_4);
-
-var _resize = ___interopRequireDefault_5(_$resize_6);
-
-function ___interopRequireDefault_5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_5(scope) {
-  scope.usePlugin(_gesture["default"]);
-  scope.usePlugin(_resize["default"]);
-  scope.usePlugin(___drag_5["default"]);
-  scope.usePlugin(_drop["default"]);
-}
-
-var id = 'actions';
-_$actions_5.id = id;
-
-var _$autoScroll_7 = {};
-"use strict";
-
-Object.defineProperty(_$autoScroll_7, "__esModule", {
-  value: true
-});
-_$autoScroll_7.getContainer = getContainer;
-_$autoScroll_7.getScroll = getScroll;
-_$autoScroll_7.getScrollSize = getScrollSize;
-_$autoScroll_7.getScrollSizeDelta = getScrollSizeDelta;
-_$autoScroll_7["default"] = void 0;
-
-var __domUtils_7 = ___interopRequireWildcard_7(_$domUtils_51);
-
-var __is_7 = ___interopRequireWildcard_7(_$is_57);
-
-var ___raf_7 = ___interopRequireDefault_7(_$raf_62);
-
-/* removed: var _$rect_63 = require("@interactjs/utils/rect"); */;
-
-/* removed: var _$window_66 = require("@interactjs/utils/window"); */;
-
-function ___interopRequireDefault_7(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_7(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __install_7(scope) {
-  var interactions = scope.interactions,
-      defaults = scope.defaults,
-      actions = scope.actions;
-  scope.autoScroll = autoScroll;
-
-  autoScroll.now = function () {
-    return scope.now();
-  };
-
-  interactions.signals.on('new', function (_ref) {
-    var interaction = _ref.interaction;
-    interaction.autoScroll = null;
-  });
-  interactions.signals.on('destroy', function (_ref2) {
-    var interaction = _ref2.interaction;
-    interaction.autoScroll = null;
-    autoScroll.stop();
-
-    if (autoScroll.interaction) {
-      autoScroll.interaction = null;
-    }
-  });
-  interactions.signals.on('stop', autoScroll.stop);
-  interactions.signals.on('action-move', function (arg) {
-    return autoScroll.onInteractionMove(arg);
-  });
-  actions.eventTypes.push('autoscroll');
-  defaults.perAction.autoScroll = autoScroll.defaults;
-}
-
-var autoScroll = {
-  defaults: {
-    enabled: false,
-    margin: 60,
-    // the item that is scrolled (Window or HTMLElement)
-    container: null,
-    // the scroll speed in pixels per second
-    speed: 300
-  },
-  now: Date.now,
-  interaction: null,
-  i: null,
-  x: 0,
-  y: 0,
-  isScrolling: false,
-  prevTime: 0,
-  margin: 0,
-  speed: 0,
-  start: function start(interaction) {
-    autoScroll.isScrolling = true;
-
-    ___raf_7["default"].cancel(autoScroll.i);
-
-    interaction.autoScroll = autoScroll;
-    autoScroll.interaction = interaction;
-    autoScroll.prevTime = autoScroll.now();
-    autoScroll.i = ___raf_7["default"].request(autoScroll.scroll);
-  },
-  stop: function stop() {
-    autoScroll.isScrolling = false;
-
-    if (autoScroll.interaction) {
-      autoScroll.interaction.autoScroll = null;
-    }
-
-    ___raf_7["default"].cancel(autoScroll.i);
-  },
-  // scroll the window by the values in scroll.x/y
-  scroll: function scroll() {
-    var interaction = autoScroll.interaction;
-    var interactable = interaction.interactable,
-        element = interaction.element;
-    var options = interactable.options[autoScroll.interaction.prepared.name].autoScroll;
-    var container = getContainer(options.container, interactable, element);
-    var now = autoScroll.now(); // change in time in seconds
-
-    var dt = (now - autoScroll.prevTime) / 1000; // displacement
-
-    var s = options.speed * dt;
-
-    if (s >= 1) {
-      var scrollBy = {
-        x: autoScroll.x * s,
-        y: autoScroll.y * s
-      };
-
-      if (scrollBy.x || scrollBy.y) {
-        var prevScroll = getScroll(container);
-
-        if (__is_7.window(container)) {
-          container.scrollBy(scrollBy.x, scrollBy.y);
-        } else if (container) {
-          container.scrollLeft += scrollBy.x;
-          container.scrollTop += scrollBy.y;
-        }
-
-        var curScroll = getScroll(container);
-        var delta = {
-          x: curScroll.x - prevScroll.x,
-          y: curScroll.y - prevScroll.y
-        };
-
-        if (delta.x || delta.y) {
-          interactable.fire({
-            type: 'autoscroll',
-            target: element,
-            interactable: interactable,
-            delta: delta,
-            interaction: interaction,
-            container: container
-          });
-        }
-      }
-
-      autoScroll.prevTime = now;
-    }
-
-    if (autoScroll.isScrolling) {
-      ___raf_7["default"].cancel(autoScroll.i);
-
-      autoScroll.i = ___raf_7["default"].request(autoScroll.scroll);
-    }
-  },
-  check: function check(interactable, actionName) {
-    var options = interactable.options;
-    return options[actionName].autoScroll && options[actionName].autoScroll.enabled;
-  },
-  onInteractionMove: function onInteractionMove(_ref3) {
-    var interaction = _ref3.interaction,
-        pointer = _ref3.pointer;
-
-    if (!(interaction.interacting() && autoScroll.check(interaction.interactable, interaction.prepared.name))) {
-      return;
-    }
-
-    if (interaction.simulation) {
-      autoScroll.x = autoScroll.y = 0;
-      return;
-    }
-
-    var top;
-    var right;
-    var bottom;
-    var left;
-    var interactable = interaction.interactable,
-        element = interaction.element;
-    var options = interactable.options[interaction.prepared.name].autoScroll;
-    var container = getContainer(options.container, interactable, element);
-
-    if (__is_7.window(container)) {
-      left = pointer.clientX < autoScroll.margin;
-      top = pointer.clientY < autoScroll.margin;
-      right = pointer.clientX > container.innerWidth - autoScroll.margin;
-      bottom = pointer.clientY > container.innerHeight - autoScroll.margin;
-    } else {
-      var rect = __domUtils_7.getElementClientRect(container);
-      left = pointer.clientX < rect.left + autoScroll.margin;
-      top = pointer.clientY < rect.top + autoScroll.margin;
-      right = pointer.clientX > rect.right - autoScroll.margin;
-      bottom = pointer.clientY > rect.bottom - autoScroll.margin;
-    }
-
-    autoScroll.x = right ? 1 : left ? -1 : 0;
-    autoScroll.y = bottom ? 1 : top ? -1 : 0;
-
-    if (!autoScroll.isScrolling) {
-      // set the autoScroll properties to those of the target
-      autoScroll.margin = options.margin;
-      autoScroll.speed = options.speed;
-      autoScroll.start(interaction);
-    }
-  }
-};
-
-function getContainer(value, interactable, element) {
-  return (__is_7.string(value) ? (0, _$rect_63.getStringOptionResult)(value, interactable, element) : value) || (0, _$window_66.getWindow)(element);
-}
-
-function getScroll(container) {
-  if (__is_7.window(container)) {
-    container = window.document.body;
-  }
-
-  return {
-    x: container.scrollLeft,
-    y: container.scrollTop
-  };
-}
-
-function getScrollSize(container) {
-  if (__is_7.window(container)) {
-    container = window.document.body;
-  }
-
-  return {
-    x: container.scrollWidth,
-    y: container.scrollHeight
-  };
-}
-
-function getScrollSizeDelta(_ref4, func) {
-  var interaction = _ref4.interaction,
-      element = _ref4.element;
-  var scrollOptions = interaction && interaction.interactable.options[interaction.prepared.name].autoScroll;
-
-  if (!scrollOptions || !scrollOptions.enabled) {
-    func();
-    return {
-      x: 0,
-      y: 0
-    };
-  }
-
-  var scrollContainer = getContainer(scrollOptions.container, interaction.interactable, element);
-  var prevSize = getScroll(scrollContainer);
-  func();
-  var curSize = getScroll(scrollContainer);
-  return {
-    x: curSize.x - prevSize.x,
-    y: curSize.y - prevSize.y
-  };
-}
-
-var ___default_7 = {
-  id: 'auto-scroll',
-  install: __install_7
-};
-_$autoScroll_7["default"] = ___default_7;
-
-var _$InteractableMethods_8 = {};
-"use strict";
-
-Object.defineProperty(_$InteractableMethods_8, "__esModule", {
-  value: true
-});
-_$InteractableMethods_8["default"] = void 0;
-
-/* removed: var _$utils_56 = require("@interactjs/utils"); */;
-
-var __is_8 = ___interopRequireWildcard_8(_$is_57);
-
-function ___interopRequireWildcard_8(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __install_8(scope) {
-  var Interactable = scope.Interactable,
-      actions = scope.actions;
-  Interactable.prototype.getAction = getAction;
-  /**
-   * ```js
-   * interact(element, { ignoreFrom: document.getElementById('no-action') })
-   * // or
-   * interact(element).ignoreFrom('input, textarea, a')
-   * ```
-   * @deprecated
-   * If the target of the `mousedown`, `pointerdown` or `touchstart` event or any
-   * of it's parents match the given CSS selector or Element, no
-   * drag/resize/gesture is started.
-   *
-   * Don't use this method. Instead set the `ignoreFrom` option for each action
-   * or for `pointerEvents`
-   *
-   * @example
-   * interact(targett)
-   *   .draggable({
-   *     ignoreFrom: 'input, textarea, a[href]'',
-   *   })
-   *   .pointerEvents({
-   *     ignoreFrom: '[no-pointer]',
-   *   })
-   *
-   * @param {string | Element | null} [newValue] a CSS selector string, an
-   * Element or `null` to not ignore any elements
-   * @return {string | Element | object} The current ignoreFrom value or this
-   * Interactable
-   */
-
-  Interactable.prototype.ignoreFrom = (0, _$utils_56.warnOnce)(function (newValue) {
-    return this._backCompatOption('ignoreFrom', newValue);
-  }, 'Interactable.ignoreFrom() has been deprecated. Use Interactble.draggable({ignoreFrom: newValue}).');
-  /**
-   * @deprecated
-   *
-   * A drag/resize/gesture is started only If the target of the `mousedown`,
-   * `pointerdown` or `touchstart` event or any of it's parents match the given
-   * CSS selector or Element.
-   *
-   * Don't use this method. Instead set the `allowFrom` option for each action
-   * or for `pointerEvents`
-   *
-   * @example
-   * interact(targett)
-   *   .resizable({
-   *     allowFrom: '.resize-handle',
-   *   .pointerEvents({
-   *     allowFrom: '.handle',,
-   *   })
-   *
-   * @param {string | Element | null} [newValue] a CSS selector string, an
-   * Element or `null` to allow from any element
-   * @return {string | Element | object} The current allowFrom value or this
-   * Interactable
-   */
-
-  Interactable.prototype.allowFrom = (0, _$utils_56.warnOnce)(function (newValue) {
-    return this._backCompatOption('allowFrom', newValue);
-  }, 'Interactable.allowFrom() has been deprecated. Use Interactble.draggable({allowFrom: newValue}).');
-  /**
-   * ```js
-   * interact('.resize-drag')
-   *   .resizable(true)
-   *   .draggable(true)
-   *   .actionChecker(function (pointer, event, action, interactable, element, interaction) {
-   *
-   *   if (interact.matchesSelector(event.target, '.drag-handle')) {
-   *     // force drag with handle target
-   *     action.name = drag
-   *   }
-   *   else {
-   *     // resize from the top and right edges
-   *     action.name  = 'resize'
-   *     action.edges = { top: true, right: true }
-   *   }
-   *
-   *   return action
-   * })
-   * ```
-   *
-   * Returns or sets the function used to check action to be performed on
-   * pointerDown
-   *
-   * @param {function | null} [checker] A function which takes a pointer event,
-   * defaultAction string, interactable, element and interaction as parameters
-   * and returns an object with name property 'drag' 'resize' or 'gesture' and
-   * optionally an `edges` object with boolean 'top', 'left', 'bottom' and right
-   * props.
-   * @return {Function | Interactable} The checker function or this Interactable
-   */
-
-  Interactable.prototype.actionChecker = actionChecker;
-  /**
-   * Returns or sets whether the the cursor should be changed depending on the
-   * action that would be performed if the mouse were pressed and dragged.
-   *
-   * @param {boolean} [newValue]
-   * @return {boolean | Interactable} The current setting or this Interactable
-   */
-
-  Interactable.prototype.styleCursor = styleCursor;
-
-  Interactable.prototype.defaultActionChecker = function (pointer, event, interaction, element) {
-    return defaultActionChecker(this, pointer, event, interaction, element, actions);
-  };
-}
-
-function getAction(pointer, event, interaction, element) {
-  var action = this.defaultActionChecker(pointer, event, interaction, element);
-
-  if (this.options.actionChecker) {
-    return this.options.actionChecker(pointer, event, action, this, element, interaction);
-  }
-
-  return action;
-}
-
-function defaultActionChecker(interactable, pointer, event, interaction, element, actions) {
-  var rect = interactable.getRect(element);
-  var buttons = event.buttons || {
-    0: 1,
-    1: 4,
-    3: 8,
-    4: 16
-  }[event.button];
-  var action = null;
-
-  for (var _i = 0; _i < actions.names.length; _i++) {
-    var _ref;
-
-    _ref = actions.names[_i];
-    var actionName = _ref;
-
-    // check mouseButton setting if the pointer is down
-    if (interaction.pointerIsDown && /mouse|pointer/.test(interaction.pointerType) && (buttons & interactable.options[actionName].mouseButtons) === 0) {
-      continue;
-    }
-
-    action = actions[actionName].checker(pointer, event, interactable, element, interaction, rect);
-
-    if (action) {
-      return action;
-    }
-  }
-}
-
-function styleCursor(newValue) {
-  if (__is_8.bool(newValue)) {
-    this.options.styleCursor = newValue;
-    return this;
-  }
-
-  if (newValue === null) {
-    delete this.options.styleCursor;
-    return this;
-  }
-
-  return this.options.styleCursor;
-}
-
-function actionChecker(checker) {
-  if (__is_8.func(checker)) {
-    this.options.actionChecker = checker;
-    return this;
-  }
-
-  if (checker === null) {
-    delete this.options.actionChecker;
-    return this;
-  }
-
-  return this.options.actionChecker;
-}
-
-var ___default_8 = {
-  id: 'auto-start/interactableMethods',
-  install: __install_8
-};
-_$InteractableMethods_8["default"] = ___default_8;
-
-var _$base_9 = {};
-"use strict";
-
-Object.defineProperty(_$base_9, "__esModule", {
-  value: true
-});
-_$base_9["default"] = void 0;
-
-var __utils_9 = ___interopRequireWildcard_9(_$utils_56);
-
-var _InteractableMethods = ___interopRequireDefault_9(_$InteractableMethods_8);
-
-function ___interopRequireDefault_9(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_9(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __install_9(scope) {
-  var interact = scope.interact,
-      interactions = scope.interactions,
-      defaults = scope.defaults;
-  scope.usePlugin(_InteractableMethods["default"]); // set cursor style on mousedown
-
-  interactions.signals.on('down', function (_ref) {
-    var interaction = _ref.interaction,
-        pointer = _ref.pointer,
-        event = _ref.event,
-        eventTarget = _ref.eventTarget;
-
-    if (interaction.interacting()) {
-      return;
-    }
-
-    var actionInfo = getActionInfo(interaction, pointer, event, eventTarget, scope);
-    prepare(interaction, actionInfo, scope);
-  }); // set cursor style on mousemove
-
-  interactions.signals.on('move', function (_ref2) {
-    var interaction = _ref2.interaction,
-        pointer = _ref2.pointer,
-        event = _ref2.event,
-        eventTarget = _ref2.eventTarget;
-
-    if (interaction.pointerType !== 'mouse' || interaction.pointerIsDown || interaction.interacting()) {
-      return;
-    }
-
-    var actionInfo = getActionInfo(interaction, pointer, event, eventTarget, scope);
-    prepare(interaction, actionInfo, scope);
-  });
-  interactions.signals.on('move', function (arg) {
-    var interaction = arg.interaction;
-
-    if (!interaction.pointerIsDown || interaction.interacting() || !interaction.pointerWasMoved || !interaction.prepared.name) {
-      return;
-    }
-
-    scope.autoStart.signals.fire('before-start', arg);
-    var interactable = interaction.interactable;
-
-    if (interaction.prepared.name && interactable) {
-      // check manualStart and interaction limit
-      if (interactable.options[interaction.prepared.name].manualStart || !withinInteractionLimit(interactable, interaction.element, interaction.prepared, scope)) {
-        interaction.stop();
-      } else {
-        interaction.start(interaction.prepared, interactable, interaction.element);
-        setInteractionCursor(interaction, scope);
-      }
-    }
-  });
-  interactions.signals.on('stop', function (_ref3) {
-    var interaction = _ref3.interaction;
-    var interactable = interaction.interactable;
-
-    if (interactable && interactable.options.styleCursor) {
-      setCursor(interaction.element, '', scope);
-    }
-  });
-  defaults.base.actionChecker = null;
-  defaults.base.styleCursor = true;
-  __utils_9.extend(defaults.perAction, {
-    manualStart: false,
-    max: Infinity,
-    maxPerElement: 1,
-    allowFrom: null,
-    ignoreFrom: null,
-    // only allow left button by default
-    // see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#Return_value
-    mouseButtons: 1
-  });
-  /**
-   * Returns or sets the maximum number of concurrent interactions allowed.  By
-   * default only 1 interaction is allowed at a time (for backwards
-   * compatibility). To allow multiple interactions on the same Interactables and
-   * elements, you need to enable it in the draggable, resizable and gesturable
-   * `'max'` and `'maxPerElement'` options.
-   *
-   * @alias module:interact.maxInteractions
-   *
-   * @param {number} [newValue] Any number. newValue <= 0 means no interactions.
-   */
-
-  interact.maxInteractions = function (newValue) {
-    return maxInteractions(newValue, scope);
-  };
-
-  scope.autoStart = {
-    // Allow this many interactions to happen simultaneously
-    maxInteractions: Infinity,
-    withinInteractionLimit: withinInteractionLimit,
-    cursorElement: null,
-    signals: new __utils_9.Signals()
-  };
-} // Check if the current interactable supports the action.
-// If so, return the validated action. Otherwise, return null
-
-
-function validateAction(action, interactable, element, eventTarget, scope) {
-  if (interactable.testIgnoreAllow(interactable.options[action.name], element, eventTarget) && interactable.options[action.name].enabled && withinInteractionLimit(interactable, element, action, scope)) {
-    return action;
-  }
-
-  return null;
-}
-
-function validateMatches(interaction, pointer, event, matches, matchElements, eventTarget, scope) {
-  for (var i = 0, len = matches.length; i < len; i++) {
-    var match = matches[i];
-    var matchElement = matchElements[i];
-    var matchAction = match.getAction(pointer, event, interaction, matchElement);
-
-    if (!matchAction) {
-      continue;
-    }
-
-    var action = validateAction(matchAction, match, matchElement, eventTarget, scope);
-
-    if (action) {
-      return {
-        action: action,
-        interactable: match,
-        element: matchElement
-      };
-    }
-  }
-
-  return {
-    action: null,
-    interactable: null,
-    element: null
-  };
-}
-
-function getActionInfo(interaction, pointer, event, eventTarget, scope) {
-  var matches = [];
-  var matchElements = [];
-  var element = eventTarget;
-
-  function pushMatches(interactable) {
-    matches.push(interactable);
-    matchElements.push(element);
-  }
-
-  while (__utils_9.is.element(element)) {
-    matches = [];
-    matchElements = [];
-    scope.interactables.forEachMatch(element, pushMatches);
-    var actionInfo = validateMatches(interaction, pointer, event, matches, matchElements, eventTarget, scope);
-
-    if (actionInfo.action && !actionInfo.interactable.options[actionInfo.action.name].manualStart) {
-      return actionInfo;
-    }
-
-    element = __utils_9.dom.parentNode(element);
-  }
-
-  return {
-    action: null,
-    interactable: null,
-    element: null
-  };
-}
-
-function prepare(interaction, _ref4, scope) {
-  var action = _ref4.action,
-      interactable = _ref4.interactable,
-      element = _ref4.element;
-  action = action || {
-    name: null
-  }; // clear previous target element cursor
-
-  if (interaction.interactable && interaction.interactable.options.styleCursor) {
-    setCursor(interaction.element, '', scope);
-  }
-
-  interaction.interactable = interactable;
-  interaction.element = element;
-  __utils_9.copyAction(interaction.prepared, action);
-  interaction.rect = interactable && action.name ? interactable.getRect(element) : null;
-  setInteractionCursor(interaction, scope);
-  scope.autoStart.signals.fire('prepared', {
-    interaction: interaction
-  });
-}
-
-function withinInteractionLimit(interactable, element, action, scope) {
-  var options = interactable.options;
-  var maxActions = options[action.name].max;
-  var maxPerElement = options[action.name].maxPerElement;
-  var autoStartMax = scope.autoStart.maxInteractions;
-  var activeInteractions = 0;
-  var interactableCount = 0;
-  var elementCount = 0; // no actions if any of these values == 0
-
-  if (!(maxActions && maxPerElement && autoStartMax)) {
-    return false;
-  }
-
-  for (var _i = 0; _i < scope.interactions.list.length; _i++) {
-    var _ref5;
-
-    _ref5 = scope.interactions.list[_i];
-    var interaction = _ref5;
-    var otherAction = interaction.prepared.name;
-
-    if (!interaction.interacting()) {
-      continue;
-    }
-
-    activeInteractions++;
-
-    if (activeInteractions >= autoStartMax) {
-      return false;
-    }
-
-    if (interaction.interactable !== interactable) {
-      continue;
-    }
-
-    interactableCount += otherAction === action.name ? 1 : 0;
-
-    if (interactableCount >= maxActions) {
-      return false;
-    }
-
-    if (interaction.element === element) {
-      elementCount++;
-
-      if (otherAction === action.name && elementCount >= maxPerElement) {
-        return false;
-      }
-    }
-  }
-
-  return autoStartMax > 0;
-}
-
-function maxInteractions(newValue, scope) {
-  if (__utils_9.is.number(newValue)) {
-    scope.autoStart.maxInteractions = newValue;
-    return this;
-  }
-
-  return scope.autoStart.maxInteractions;
-}
-
-function setCursor(element, cursor, scope) {
-  if (scope.autoStart.cursorElement) {
-    scope.autoStart.cursorElement.style.cursor = '';
-  }
-
-  element.ownerDocument.documentElement.style.cursor = cursor;
-  element.style.cursor = cursor;
-  scope.autoStart.cursorElement = cursor ? element : null;
-}
-
-function setInteractionCursor(interaction, scope) {
-  var interactable = interaction.interactable,
-      element = interaction.element,
-      prepared = interaction.prepared;
-
-  if (!(interaction.pointerType === 'mouse' && interactable && interactable.options.styleCursor)) {
-    return;
-  }
-
-  var cursor = '';
-
-  if (prepared.name) {
-    var cursorChecker = interactable.options[prepared.name].cursorChecker;
-
-    if (__utils_9.is.func(cursorChecker)) {
-      cursor = cursorChecker(prepared, interactable, element, interaction._interacting);
-    } else {
-      cursor = scope.actions[prepared.name].getCursor(prepared);
-    }
-  }
-
-  setCursor(interaction.element, cursor || '', scope);
-}
-
-var ___default_9 = {
-  id: 'auto-start/base',
-  install: __install_9,
-  maxInteractions: maxInteractions,
-  withinInteractionLimit: withinInteractionLimit,
-  validateAction: validateAction
-};
-_$base_9["default"] = ___default_9;
-
-var _$dragAxis_10 = {};
-"use strict";
-
-Object.defineProperty(_$dragAxis_10, "__esModule", {
-  value: true
-});
-_$dragAxis_10["default"] = void 0;
-
-var ___scope_10 = _$scope_24({});
-
-/* removed: var _$domUtils_51 = require("@interactjs/utils/domUtils"); */;
-
-var __is_10 = ___interopRequireWildcard_10(_$is_57);
-
-var _base = ___interopRequireDefault_10(_$base_9);
-
-function ___interopRequireDefault_10(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_10(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __install_10(scope) {
-  scope.autoStart.signals.on('before-start', function (_ref) {
-    var interaction = _ref.interaction,
-        eventTarget = _ref.eventTarget,
-        dx = _ref.dx,
-        dy = _ref.dy;
-
-    if (interaction.prepared.name !== 'drag') {
-      return;
-    } // check if a drag is in the correct axis
-
-
-    var absX = Math.abs(dx);
-    var absY = Math.abs(dy);
-    var targetOptions = interaction.interactable.options.drag;
-    var startAxis = targetOptions.startAxis;
-    var currentAxis = absX > absY ? 'x' : absX < absY ? 'y' : 'xy';
-    interaction.prepared.axis = targetOptions.lockAxis === 'start' ? currentAxis[0] // always lock to one axis even if currentAxis === 'xy'
-    : targetOptions.lockAxis; // if the movement isn't in the startAxis of the interactable
-
-    if (currentAxis !== 'xy' && startAxis !== 'xy' && startAxis !== currentAxis) {
-      // cancel the prepared action
-      interaction.prepared.name = null; // then try to get a drag from another ineractable
-
-      var element = eventTarget;
-
-      var getDraggable = function getDraggable(interactable) {
-        if (interactable === interaction.interactable) {
-          return;
-        }
-
-        var options = interaction.interactable.options.drag;
-
-        if (!options.manualStart && interactable.testIgnoreAllow(options, element, eventTarget)) {
-          var action = interactable.getAction(interaction.downPointer, interaction.downEvent, interaction, element);
-
-          if (action && action.name === ___scope_10.ActionName.Drag && checkStartAxis(currentAxis, interactable) && _base["default"].validateAction(action, interactable, element, eventTarget, scope)) {
-            return interactable;
-          }
-        }
-      }; // check all interactables
-
-
-      while (__is_10.element(element)) {
-        var interactable = scope.interactables.forEachMatch(element, getDraggable);
-
-        if (interactable) {
-          interaction.prepared.name = ___scope_10.ActionName.Drag;
-          interaction.interactable = interactable;
-          interaction.element = element;
-          break;
-        }
-
-        element = (0, _$domUtils_51.parentNode)(element);
-      }
-    }
-  });
-
-  function checkStartAxis(startAxis, interactable) {
-    if (!interactable) {
-      return false;
-    }
-
-    var thisAxis = interactable.options[___scope_10.ActionName.Drag].startAxis;
-    return startAxis === 'xy' || thisAxis === 'xy' || thisAxis === startAxis;
-  }
-}
-
-var ___default_10 = {
-  id: 'auto-start/dragAxis',
-  install: __install_10
-};
-_$dragAxis_10["default"] = ___default_10;
-
-var _$hold_11 = {};
-"use strict";
-
-Object.defineProperty(_$hold_11, "__esModule", {
-  value: true
-});
-_$hold_11["default"] = void 0;
-
-var ___base_11 = ___interopRequireDefault_11(_$base_9);
-
-function ___interopRequireDefault_11(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_11(scope) {
-  var autoStart = scope.autoStart,
-      interactions = scope.interactions,
-      defaults = scope.defaults;
-  scope.usePlugin(___base_11["default"]);
-  defaults.perAction.hold = 0;
-  defaults.perAction.delay = 0;
-  interactions.signals.on('new', function (interaction) {
-    interaction.autoStartHoldTimer = null;
-  });
-  autoStart.signals.on('prepared', function (_ref) {
-    var interaction = _ref.interaction;
-    var hold = getHoldDuration(interaction);
-
-    if (hold > 0) {
-      interaction.autoStartHoldTimer = setTimeout(function () {
-        interaction.start(interaction.prepared, interaction.interactable, interaction.element);
-      }, hold);
-    }
-  });
-  interactions.signals.on('move', function (_ref2) {
-    var interaction = _ref2.interaction,
-        duplicate = _ref2.duplicate;
-
-    if (interaction.pointerWasMoved && !duplicate) {
-      clearTimeout(interaction.autoStartHoldTimer);
-    }
-  }); // prevent regular down->move autoStart
-
-  autoStart.signals.on('before-start', function (_ref3) {
-    var interaction = _ref3.interaction;
-    var hold = getHoldDuration(interaction);
-
-    if (hold > 0) {
-      interaction.prepared.name = null;
-    }
-  });
-}
-
-function getHoldDuration(interaction) {
-  var actionName = interaction.prepared && interaction.prepared.name;
-
-  if (!actionName) {
-    return null;
-  }
-
-  var options = interaction.interactable.options;
-  return options[actionName].hold || options[actionName].delay;
-}
-
-var ___default_11 = {
-  id: 'auto-start/hold',
-  install: __install_11,
-  getHoldDuration: getHoldDuration
-};
-_$hold_11["default"] = ___default_11;
-
-var _$autoStart_12 = {};
-"use strict";
-
-Object.defineProperty(_$autoStart_12, "__esModule", {
-  value: true
-});
-_$autoStart_12.install = __install_12;
-Object.defineProperty(_$autoStart_12, "autoStart", {
-  enumerable: true,
-  get: function get() {
-    return ___base_12["default"];
-  }
-});
-Object.defineProperty(_$autoStart_12, "dragAxis", {
-  enumerable: true,
-  get: function get() {
-    return _dragAxis["default"];
-  }
-});
-Object.defineProperty(_$autoStart_12, "hold", {
-  enumerable: true,
-  get: function get() {
-    return _hold["default"];
-  }
-});
-_$autoStart_12.id = void 0;
-
-var ___base_12 = ___interopRequireDefault_12(_$base_9);
-
-var _dragAxis = ___interopRequireDefault_12(_$dragAxis_10);
-
-var _hold = ___interopRequireDefault_12(_$hold_11);
-
-function ___interopRequireDefault_12(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_12(scope) {
-  scope.usePlugin(___base_12["default"]);
-  scope.usePlugin(_hold["default"]);
-  scope.usePlugin(_dragAxis["default"]);
-}
-
-var __id_12 = 'auto-start';
-_$autoStart_12.id = __id_12;
-
-var _$interactablePreventDefault_21 = {};
-"use strict";
-
-Object.defineProperty(_$interactablePreventDefault_21, "__esModule", {
-  value: true
-});
-_$interactablePreventDefault_21.install = __install_21;
-_$interactablePreventDefault_21["default"] = void 0;
-
-/* removed: var _$domUtils_51 = require("@interactjs/utils/domUtils"); */;
-
-var ___events_21 = ___interopRequireDefault_21(_$events_52);
-
-var __is_21 = ___interopRequireWildcard_21(_$is_57);
-
-/* removed: var _$window_66 = require("@interactjs/utils/window"); */;
-
-function ___interopRequireWildcard_21(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_21(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function preventDefault(newValue) {
-  if (/^(always|never|auto)$/.test(newValue)) {
-    this.options.preventDefault = newValue;
-    return this;
-  }
-
-  if (__is_21.bool(newValue)) {
-    this.options.preventDefault = newValue ? 'always' : 'never';
-    return this;
-  }
-
-  return this.options.preventDefault;
-}
-
-function checkAndPreventDefault(interactable, scope, event) {
-  var setting = interactable.options.preventDefault;
-
-  if (setting === 'never') {
-    return;
-  }
-
-  if (setting === 'always') {
-    event.preventDefault();
-    return;
-  } // setting === 'auto'
-  // if the browser supports passive event listeners and isn't running on iOS,
-  // don't preventDefault of touch{start,move} events. CSS touch-action and
-  // user-select should be used instead of calling event.preventDefault().
-
-
-  if (___events_21["default"].supportsPassive && /^touch(start|move)$/.test(event.type)) {
-    var doc = (0, _$window_66.getWindow)(event.target).document;
-    var docOptions = scope.getDocOptions(doc);
-
-    if (!(docOptions && docOptions.events) || docOptions.events.passive !== false) {
-      return;
-    }
-  } // don't preventDefault of pointerdown events
-
-
-  if (/^(mouse|pointer|touch)*(down|start)/i.test(event.type)) {
-    return;
-  } // don't preventDefault on editable elements
-
-
-  if (__is_21.element(event.target) && (0, _$domUtils_51.matchesSelector)(event.target, 'input,select,textarea,[contenteditable=true],[contenteditable=true] *')) {
-    return;
-  }
-
-  event.preventDefault();
-}
-
-function onInteractionEvent(_ref) {
-  var interaction = _ref.interaction,
-      event = _ref.event;
-
-  if (interaction.interactable) {
-    interaction.interactable.checkAndPreventDefault(event);
-  }
-}
-
-function __install_21(scope) {
-  /** @lends Interactable */
-  var Interactable = scope.Interactable;
-  /**
-   * Returns or sets whether to prevent the browser's default behaviour in
-   * response to pointer events. Can be set to:
-   *  - `'always'` to always prevent
-   *  - `'never'` to never prevent
-   *  - `'auto'` to let interact.js try to determine what would be best
-   *
-   * @param {string} [newValue] `'always'`, `'never'` or `'auto'`
-   * @return {string | Interactable} The current setting or this Interactable
-   */
-
-  Interactable.prototype.preventDefault = preventDefault;
-
-  Interactable.prototype.checkAndPreventDefault = function (event) {
-    return checkAndPreventDefault(this, scope, event);
-  };
-
-  var _arr = ['down', 'move', 'up', 'cancel'];
-
-  for (var _i = 0; _i < _arr.length; _i++) {
-    var eventSignal = _arr[_i];
-    scope.interactions.signals.on(eventSignal, onInteractionEvent);
-  } // prevent native HTML5 drag on interact.js target elements
-
-
-  scope.interactions.docEvents.push({
-    type: 'dragstart',
-    listener: function listener(event) {
-      for (var _i2 = 0; _i2 < scope.interactions.list.length; _i2++) {
-        var _ref2;
-
-        _ref2 = scope.interactions.list[_i2];
-        var interaction = _ref2;
-
-        if (interaction.element && (interaction.element === event.target || (0, _$domUtils_51.nodeContains)(interaction.element, event.target))) {
-          interaction.interactable.checkAndPreventDefault(event);
-          return;
-        }
-      }
-    }
-  });
-}
-
-var ___default_21 = {
-  id: 'core/interactablePreventDefault',
-  install: __install_21
-};
-_$interactablePreventDefault_21["default"] = ___default_21;
-
-var _$devTools_25 = {};
-"use strict";
-
-Object.defineProperty(_$devTools_25, "__esModule", {
-  value: true
-});
-_$devTools_25["default"] = void 0;
-
-var ___domObjects_25 = ___interopRequireDefault_25(_$domObjects_50);
-
-/* removed: var _$domUtils_51 = require("@interactjs/utils/domUtils"); */;
-
-var ___extend_25 = ___interopRequireDefault_25(_$extend_53);
-
-var __is_25 = ___interopRequireWildcard_25(_$is_57);
-
-var ___window_25 = ___interopRequireDefault_25(_$window_66);
-
-function ___interopRequireWildcard_25(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_25(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___toConsumableArray_25(arr) { return ___arrayWithoutHoles_25(arr) || ___iterableToArray_25(arr) || ___nonIterableSpread_25(); }
-
-function ___nonIterableSpread_25() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
-
-function ___iterableToArray_25(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
-
-function ___arrayWithoutHoles_25(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
-
-var CheckName;
-
-(function (CheckName) {
-  CheckName["touchAction"] = "";
-  CheckName["boxSizing"] = "";
-  CheckName["noListeners"] = "";
-})(CheckName || (CheckName = {}));
-
-var prefix = '[interact.js] ';
-var links = {
-  touchAction: 'https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action',
-  boxSizing: 'https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing'
-};
-var isProduction = "production" === 'production'; // eslint-disable-next-line no-restricted-syntax
-
-function __install_25(scope) {
-  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
-      logger = _ref.logger;
-
-  var interactions = scope.interactions,
-      Interactable = scope.Interactable,
-      defaults = scope.defaults;
-  logger = logger || console;
-  interactions.signals.on('action-start', function (_ref2) {
-    var interaction = _ref2.interaction;
-
-    for (var _i = 0; _i < checks.length; _i++) {
-      var _ref3;
-
-      _ref3 = checks[_i];
-      var check = _ref3;
-      var options = interaction.interactable && interaction.interactable.options[interaction.prepared.name];
-
-      if (!(options && options.devTools && options.devTools.ignore[check.name]) && check.perform(interaction)) {
-        var _logger;
-
-        (_logger = logger).warn.apply(_logger, [prefix + check.text].concat(___toConsumableArray_25(check.getInfo(interaction))));
-      }
-    }
-  });
-  defaults.base.devTools = {
-    ignore: {}
-  };
-
-  Interactable.prototype.devTools = function (options) {
-    if (options) {
-      (0, ___extend_25["default"])(this.options.devTools, options);
-      return this;
-    }
-
-    return this.options.devTools;
-  };
-}
-
-var checks = [{
-  name: 'touchAction',
-  perform: function perform(_ref4) {
-    var element = _ref4.element;
-    return !parentHasStyle(element, 'touchAction', /pan-|pinch|none/);
-  },
-  getInfo: function getInfo(_ref5) {
-    var element = _ref5.element;
-    return [element, links.touchAction];
-  },
-  text: 'Consider adding CSS "touch-action: none" to this element\n'
-}, {
-  name: 'boxSizing',
-  perform: function perform(interaction) {
-    var element = interaction.element;
-    return interaction.prepared.name === 'resize' && element instanceof ___domObjects_25["default"].HTMLElement && !hasStyle(element, 'boxSizing', /border-box/);
-  },
-  text: 'Consider adding CSS "box-sizing: border-box" to this resizable element',
-  getInfo: function getInfo(_ref6) {
-    var element = _ref6.element;
-    return [element, links.boxSizing];
-  }
-}, {
-  name: 'noListeners',
-  perform: function perform(interaction) {
-    var actionName = interaction.prepared.name;
-    var moveListeners = interaction.interactable.events.types["".concat(actionName, "move")] || [];
-    return !moveListeners.length;
-  },
-  getInfo: function getInfo(interaction) {
-    return [interaction.prepared.name, interaction.interactable];
-  },
-  text: 'There are no listeners set for this action'
-}];
-
-function hasStyle(element, prop, styleRe) {
-  return styleRe.test(element.style[prop] || ___window_25["default"].window.getComputedStyle(element)[prop]);
-}
-
-function parentHasStyle(element, prop, styleRe) {
-  var parent = element;
-
-  while (__is_25.element(parent)) {
-    if (hasStyle(parent, prop, styleRe)) {
-      return true;
-    }
-
-    parent = (0, _$domUtils_51.parentNode)(parent);
-  }
-
-  return false;
-}
-
-var __id_25 = 'dev-tools';
-var defaultExport = isProduction ? {
-  id: __id_25,
-  install: function install() {}
-} : {
-  id: __id_25,
-  install: __install_25,
-  checks: checks,
-  CheckName: CheckName,
-  links: links,
-  prefix: prefix
-};
-var ___default_25 = defaultExport;
-_$devTools_25["default"] = ___default_25;
-
-var _$base_30 = {};
-"use strict";
-
-Object.defineProperty(_$base_30, "__esModule", {
-  value: true
-});
-_$base_30.startAll = startAll;
-_$base_30.setAll = setAll;
-_$base_30.prepareStates = prepareStates;
-_$base_30.makeModifier = makeModifier;
-_$base_30["default"] = void 0;
-
-var ___extend_30 = ___interopRequireDefault_30(_$extend_53);
-
-function ___interopRequireDefault_30(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___slicedToArray_30(arr, i) { return ___arrayWithHoles_30(arr) || ___iterableToArrayLimit_30(arr, i) || ___nonIterableRest_30(); }
-
-function ___nonIterableRest_30() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
-
-function ___iterableToArrayLimit_30(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
-
-function ___arrayWithHoles_30(arr) { if (Array.isArray(arr)) return arr; }
-
-function __install_30(scope) {
-  var interactions = scope.interactions;
-  scope.defaults.perAction.modifiers = [];
-  interactions.signals.on('new', function (_ref) {
-    var interaction = _ref.interaction;
-    interaction.modifiers = {
-      startOffset: {
-        left: 0,
-        right: 0,
-        top: 0,
-        bottom: 0
-      },
-      offsets: {},
-      states: null,
-      result: null,
-      endPrevented: false,
-      startDelta: null
-    };
-  });
-  interactions.signals.on('before-action-start', function (arg) {
-    __start_30(arg, arg.interaction.coords.start.page);
-  });
-  interactions.signals.on('action-resume', function (arg) {
-    stop(arg);
-    __start_30(arg, arg.interaction.coords.cur.page);
-    __beforeMove_30(arg);
-  });
-  interactions.signals.on('after-action-move', restoreCoords);
-  interactions.signals.on('before-action-move', __beforeMove_30);
-  interactions.signals.on('before-action-start', setCoords);
-  interactions.signals.on('after-action-start', restoreCoords);
-  interactions.signals.on('before-action-end', beforeEnd);
-  interactions.signals.on('stop', stop);
-}
-
-function __start_30(_ref2, pageCoords) {
-  var interaction = _ref2.interaction,
-      phase = _ref2.phase;
-  var interactable = interaction.interactable,
-      element = interaction.element;
-  var modifierList = getModifierList(interaction);
-  var states = prepareStates(modifierList);
-  var rect = (0, ___extend_30["default"])({}, interaction.rect);
-
-  if (!('width' in rect)) {
-    rect.width = rect.right - rect.left;
-  }
-
-  if (!('height' in rect)) {
-    rect.height = rect.bottom - rect.top;
-  }
-
-  var startOffset = getRectOffset(rect, pageCoords);
-  interaction.modifiers.startOffset = startOffset;
-  interaction.modifiers.startDelta = {
-    x: 0,
-    y: 0
-  };
-  var arg = {
-    interaction: interaction,
-    interactable: interactable,
-    element: element,
-    pageCoords: pageCoords,
-    phase: phase,
-    rect: rect,
-    startOffset: startOffset,
-    states: states,
-    preEnd: false,
-    requireEndOnly: false
-  };
-  interaction.modifiers.states = states;
-  interaction.modifiers.result = null;
-  startAll(arg);
-  arg.pageCoords = (0, ___extend_30["default"])({}, interaction.coords.start.page);
-  var result = interaction.modifiers.result = setAll(arg);
-  return result;
-}
-
-function startAll(arg) {
-  var states = arg.states;
-
-  for (var _i = 0; _i < states.length; _i++) {
-    var _ref3;
-
-    _ref3 = states[_i];
-    var state = _ref3;
-
-    if (state.methods.start) {
-      arg.state = state;
-      state.methods.start(arg);
-    }
-  }
-}
-
-function setAll(arg) {
-  var interaction = arg.interaction,
-      _arg$modifiersState = arg.modifiersState,
-      modifiersState = _arg$modifiersState === void 0 ? interaction.modifiers : _arg$modifiersState,
-      _arg$prevCoords = arg.prevCoords,
-      prevCoords = _arg$prevCoords === void 0 ? modifiersState.result ? modifiersState.result.coords : interaction.coords.prev.page : _arg$prevCoords,
-      phase = arg.phase,
-      preEnd = arg.preEnd,
-      requireEndOnly = arg.requireEndOnly,
-      rect = arg.rect,
-      skipModifiers = arg.skipModifiers;
-  var states = skipModifiers ? arg.states.slice(skipModifiers) : arg.states;
-  arg.coords = (0, ___extend_30["default"])({}, arg.pageCoords);
-  arg.rect = (0, ___extend_30["default"])({}, rect);
-  var result = {
-    delta: {
-      x: 0,
-      y: 0
-    },
-    rectDelta: {
-      left: 0,
-      right: 0,
-      top: 0,
-      bottom: 0
-    },
-    coords: arg.coords,
-    changed: true
-  };
-
-  for (var _i2 = 0; _i2 < states.length; _i2++) {
-    var _ref4;
-
-    _ref4 = states[_i2];
-    var state = _ref4;
-    var options = state.options;
-
-    if (!state.methods.set || !shouldDo(options, preEnd, requireEndOnly, phase)) {
-      continue;
-    }
-
-    arg.state = state;
-    state.methods.set(arg);
-  }
-
-  result.delta.x = arg.coords.x - arg.pageCoords.x;
-  result.delta.y = arg.coords.y - arg.pageCoords.y;
-  var rectChanged = false;
-
-  if (rect) {
-    result.rectDelta.left = arg.rect.left - rect.left;
-    result.rectDelta.right = arg.rect.right - rect.right;
-    result.rectDelta.top = arg.rect.top - rect.top;
-    result.rectDelta.bottom = arg.rect.bottom - rect.bottom;
-    rectChanged = result.rectDelta.left !== 0 || result.rectDelta.right !== 0 || result.rectDelta.top !== 0 || result.rectDelta.bottom !== 0;
-  }
-
-  result.changed = prevCoords.x !== result.coords.x || prevCoords.y !== result.coords.y || rectChanged;
-  return result;
-}
-
-function __beforeMove_30(arg) {
-  var interaction = arg.interaction,
-      phase = arg.phase,
-      preEnd = arg.preEnd,
-      skipModifiers = arg.skipModifiers;
-  var interactable = interaction.interactable,
-      element = interaction.element;
-  var modifierResult = setAll({
-    interaction: interaction,
-    interactable: interactable,
-    element: element,
-    preEnd: preEnd,
-    phase: phase,
-    pageCoords: interaction.coords.cur.page,
-    rect: interaction.rect,
-    states: interaction.modifiers.states,
-    requireEndOnly: false,
-    skipModifiers: skipModifiers
-  });
-  interaction.modifiers.result = modifierResult; // don't fire an action move if a modifier would keep the event in the same
-  // cordinates as before
-
-  if (!modifierResult.changed && interaction.interacting()) {
-    return false;
-  }
-
-  setCoords(arg);
-}
-
-function beforeEnd(arg) {
-  var interaction = arg.interaction,
-      event = arg.event,
-      noPreEnd = arg.noPreEnd;
-  var states = interaction.modifiers.states;
-
-  if (noPreEnd || !states || !states.length) {
-    return;
-  }
-
-  var didPreEnd = false;
-
-  for (var _i3 = 0; _i3 < states.length; _i3++) {
-    var _ref5;
-
-    _ref5 = states[_i3];
-    var state = _ref5;
-    arg.state = state;
-    var options = state.options,
-        methods = state.methods;
-    var endResult = methods.beforeEnd && methods.beforeEnd(arg);
-
-    if (endResult === false) {
-      interaction.modifiers.endPrevented = true;
-      return false;
-    } // if the endOnly option is true for any modifier
-
-
-    if (!didPreEnd && shouldDo(options, true, true)) {
-      // fire a move event at the modified coordinates
-      interaction.move({
-        event: event,
-        preEnd: true
-      });
-      didPreEnd = true;
-    }
-  }
-}
-
-function stop(arg) {
-  var interaction = arg.interaction;
-  var states = interaction.modifiers.states;
-
-  if (!states || !states.length) {
-    return;
-  }
-
-  var modifierArg = (0, ___extend_30["default"])({
-    states: states,
-    interactable: interaction.interactable,
-    element: interaction.element
-  }, arg);
-  restoreCoords(arg);
-
-  for (var _i4 = 0; _i4 < states.length; _i4++) {
-    var _ref6;
-
-    _ref6 = states[_i4];
-    var state = _ref6;
-    modifierArg.state = state;
-
-    if (state.methods.stop) {
-      state.methods.stop(modifierArg);
-    }
-  }
-
-  arg.interaction.modifiers.states = null;
-  arg.interaction.modifiers.endPrevented = false;
-}
-
-function getModifierList(interaction) {
-  var actionOptions = interaction.interactable.options[interaction.prepared.name];
-  var actionModifiers = actionOptions.modifiers;
-
-  if (actionModifiers && actionModifiers.length) {
-    return actionModifiers.filter(function (modifier) {
-      return !modifier.options || modifier.options.enabled !== false;
-    });
-  }
-
-  return ['snap', 'snapSize', 'snapEdges', 'restrict', 'restrictEdges', 'restrictSize'].map(function (type) {
-    var options = actionOptions[type];
-    return options && options.enabled && {
-      options: options,
-      methods: options._methods
-    };
-  }).filter(function (m) {
-    return !!m;
-  });
-}
-
-function prepareStates(modifierList) {
-  var states = [];
-
-  for (var index = 0; index < modifierList.length; index++) {
-    var _modifierList$index = modifierList[index],
-        options = _modifierList$index.options,
-        methods = _modifierList$index.methods,
-        name = _modifierList$index.name;
-
-    if (options && options.enabled === false) {
-      continue;
-    }
-
-    states.push({
-      options: options,
-      methods: methods,
-      index: index,
-      name: name
-    });
-  }
-
-  return states;
-}
-
-function setCoords(arg) {
-  var interaction = arg.interaction,
-      phase = arg.phase;
-  var curCoords = arg.curCoords || interaction.coords.cur;
-  var startCoords = arg.startCoords || interaction.coords.start;
-  var _interaction$modifier = interaction.modifiers,
-      result = _interaction$modifier.result,
-      startDelta = _interaction$modifier.startDelta;
-  var curDelta = result.delta;
-
-  if (phase === 'start') {
-    (0, ___extend_30["default"])(interaction.modifiers.startDelta, result.delta);
-  }
-
-  var _arr = [[startCoords, startDelta], [curCoords, curDelta]];
-
-  for (var _i5 = 0; _i5 < _arr.length; _i5++) {
-    var _arr$_i = ___slicedToArray_30(_arr[_i5], 2),
-        coordsSet = _arr$_i[0],
-        delta = _arr$_i[1];
-
-    coordsSet.page.x += delta.x;
-    coordsSet.page.y += delta.y;
-    coordsSet.client.x += delta.x;
-    coordsSet.client.y += delta.y;
-  }
-
-  var rectDelta = interaction.modifiers.result.rectDelta;
-  var rect = arg.rect || interaction.rect;
-  rect.left += rectDelta.left;
-  rect.right += rectDelta.right;
-  rect.top += rectDelta.top;
-  rect.bottom += rectDelta.bottom;
-  rect.width = rect.right - rect.left;
-  rect.height = rect.bottom - rect.top;
-}
-
-function restoreCoords(_ref7) {
-  var _ref7$interaction = _ref7.interaction,
-      coords = _ref7$interaction.coords,
-      rect = _ref7$interaction.rect,
-      modifiers = _ref7$interaction.modifiers;
-
-  if (!modifiers.result) {
-    return;
-  }
-
-  var startDelta = modifiers.startDelta;
-  var _modifiers$result = modifiers.result,
-      curDelta = _modifiers$result.delta,
-      rectDelta = _modifiers$result.rectDelta;
-  var coordsAndDeltas = [[coords.start, startDelta], [coords.cur, curDelta]];
-
-  for (var _i6 = 0; _i6 < coordsAndDeltas.length; _i6++) {
-    var _coordsAndDeltas$_i = ___slicedToArray_30(coordsAndDeltas[_i6], 2),
-        coordsSet = _coordsAndDeltas$_i[0],
-        delta = _coordsAndDeltas$_i[1];
-
-    coordsSet.page.x -= delta.x;
-    coordsSet.page.y -= delta.y;
-    coordsSet.client.x -= delta.x;
-    coordsSet.client.y -= delta.y;
-  }
-
-  rect.left -= rectDelta.left;
-  rect.right -= rectDelta.right;
-  rect.top -= rectDelta.top;
-  rect.bottom -= rectDelta.bottom;
-}
-
-function shouldDo(options, preEnd, requireEndOnly, phase) {
-  return options ? options.enabled !== false && (preEnd || !options.endOnly) && (!requireEndOnly || options.endOnly || options.alwaysOnEnd) && (options.setStart || phase !== 'start') : !requireEndOnly;
-}
-
-function getRectOffset(rect, coords) {
-  return rect ? {
-    left: coords.x - rect.left,
-    top: coords.y - rect.top,
-    right: rect.right - coords.x,
-    bottom: rect.bottom - coords.y
-  } : {
-    left: 0,
-    top: 0,
-    right: 0,
-    bottom: 0
-  };
-}
-
-function makeModifier(module, name) {
-  var defaults = module.defaults;
-  var methods = {
-    start: module.start,
-    set: module.set,
-    beforeEnd: module.beforeEnd,
-    stop: module.stop
-  };
-
-  var modifier = function modifier(_options) {
-    var options = _options || {};
-    options.enabled = options.enabled !== false; // add missing defaults to options
-
-    for (var prop in defaults) {
-      if (!(prop in options)) {
-        options[prop] = defaults[prop];
-      }
-    }
-
-    var m = {
-      options: options,
-      methods: methods,
-      name: name
-    };
-    return m;
-  };
-
-  if (name && typeof name === 'string') {
-    // for backwrads compatibility
-    modifier._defaults = defaults;
-    modifier._methods = methods;
-  }
-
-  return modifier;
-}
-
-var ___default_30 = {
-  id: 'modifiers/base',
-  install: __install_30,
-  startAll: startAll,
-  setAll: setAll,
-  prepareStates: prepareStates,
-  start: __start_30,
-  beforeMove: __beforeMove_30,
-  beforeEnd: beforeEnd,
-  stop: stop,
-  shouldDo: shouldDo,
-  getModifierList: getModifierList,
-  getRectOffset: getRectOffset,
-  makeModifier: makeModifier
-};
-_$base_30["default"] = ___default_30;
-
-var _$inertia_26 = {};
-"use strict";
-
-Object.defineProperty(_$inertia_26, "__esModule", {
-  value: true
-});
-_$inertia_26["default"] = void 0;
-
-/* removed: var _$InteractEvent_15 = require("@interactjs/core/InteractEvent"); */;
-
-var ___base_26 = ___interopRequireDefault_26(_$base_30);
-
-var __utils_26 = ___interopRequireWildcard_26(_$utils_56);
-
-var ___raf_26 = ___interopRequireDefault_26(_$raf_62);
-
-function ___interopRequireWildcard_26(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_26(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-_$InteractEvent_15.EventPhase.Resume = 'resume';
-_$InteractEvent_15.EventPhase.InertiaStart = 'inertiastart';
-
-function __install_26(scope) {
-  var interactions = scope.interactions,
-      defaults = scope.defaults;
-  interactions.signals.on('new', function (_ref) {
-    var interaction = _ref.interaction;
-    interaction.inertia = {
-      active: false,
-      smoothEnd: false,
-      allowResume: false,
-      upCoords: {},
-      timeout: null
-    };
-  }); // FIXME proper signal typing
-
-  interactions.signals.on('before-action-end', function (arg) {
-    return release(arg, scope);
-  });
-  interactions.signals.on('down', function (arg) {
-    return resume(arg, scope);
-  });
-  interactions.signals.on('stop', function (arg) {
-    return __stop_26(arg);
-  });
-  defaults.perAction.inertia = {
-    enabled: false,
-    resistance: 10,
-    minSpeed: 100,
-    endSpeed: 10,
-    allowResume: true,
-    smoothEndDuration: 300
-  };
-  scope.usePlugin(___base_26["default"]);
-}
-
-function resume(_ref2, scope) {
-  var interaction = _ref2.interaction,
-      event = _ref2.event,
-      pointer = _ref2.pointer,
-      eventTarget = _ref2.eventTarget;
-  var state = interaction.inertia; // Check if the down event hits the current inertia target
-
-  if (state.active) {
-    var element = eventTarget; // climb up the DOM tree from the event target
-
-    while (__utils_26.is.element(element)) {
-      // if interaction element is the current inertia target element
-      if (element === interaction.element) {
-        // stop inertia
-        ___raf_26["default"].cancel(state.timeout);
-
-        state.active = false;
-        interaction.simulation = null; // update pointers to the down event's coordinates
-
-        interaction.updatePointer(pointer, event, eventTarget, true);
-        __utils_26.pointer.setCoords(interaction.coords.cur, interaction.pointers.map(function (p) {
-          return p.pointer;
-        }), interaction._now()); // fire appropriate signals
-
-        var signalArg = {
-          interaction: interaction
-        };
-        scope.interactions.signals.fire('action-resume', signalArg); // fire a reume event
-
-        var resumeEvent = new scope.InteractEvent(interaction, event, interaction.prepared.name, _$InteractEvent_15.EventPhase.Resume, interaction.element);
-
-        interaction._fireEvent(resumeEvent);
-
-        __utils_26.pointer.copyCoords(interaction.coords.prev, interaction.coords.cur);
-        break;
-      }
-
-      element = __utils_26.dom.parentNode(element);
-    }
-  }
-}
-
-function release(_ref3, scope) {
-  var interaction = _ref3.interaction,
-      event = _ref3.event,
-      noPreEnd = _ref3.noPreEnd;
-  var state = interaction.inertia;
-
-  if (!interaction.interacting() || interaction.simulation && interaction.simulation.active || noPreEnd) {
-    return null;
-  }
-
-  var options = __getOptions_26(interaction);
-
-  var now = interaction._now();
-
-  var velocityClient = interaction.coords.velocity.client;
-  var pointerSpeed = __utils_26.hypot(velocityClient.x, velocityClient.y);
-  var smoothEnd = false;
-  var modifierResult; // check if inertia should be started
-
-  var inertiaPossible = options && options.enabled && interaction.prepared.name !== 'gesture' && event !== state.startEvent;
-  var inertia = inertiaPossible && now - interaction.coords.cur.timeStamp < 50 && pointerSpeed > options.minSpeed && pointerSpeed > options.endSpeed;
-  var modifierArg = {
-    interaction: interaction,
-    pageCoords: __utils_26.extend({}, interaction.coords.cur.page),
-    states: inertiaPossible && interaction.modifiers.states.map(function (modifierStatus) {
-      return __utils_26.extend({}, modifierStatus);
-    }),
-    preEnd: true,
-    prevCoords: undefined,
-    requireEndOnly: null
-  }; // smoothEnd
-
-  if (inertiaPossible && !inertia) {
-    modifierArg.prevCoords = interaction.prevEvent.page;
-    modifierArg.requireEndOnly = false;
-    modifierResult = ___base_26["default"].setAll(modifierArg);
-
-    if (modifierResult.changed) {
-      smoothEnd = true;
-    }
-  }
-
-  if (!(inertia || smoothEnd)) {
-    return null;
-  }
-
-  __utils_26.pointer.copyCoords(state.upCoords, interaction.coords.cur);
-  interaction.pointers[0].pointer = state.startEvent = new scope.InteractEvent(interaction, event, // FIXME add proper typing Action.name
-  interaction.prepared.name, _$InteractEvent_15.EventPhase.InertiaStart, interaction.element);
-  state.t0 = now;
-  state.active = true;
-  state.allowResume = options.allowResume;
-  interaction.simulation = state;
-  interaction.interactable.fire(state.startEvent);
-
-  if (inertia) {
-    state.vx0 = interaction.coords.velocity.client.x;
-    state.vy0 = interaction.coords.velocity.client.y;
-    state.v0 = pointerSpeed;
-    calcInertia(interaction, state);
-    __utils_26.extend(modifierArg.pageCoords, interaction.coords.cur.page);
-    modifierArg.pageCoords.x += state.xe;
-    modifierArg.pageCoords.y += state.ye;
-    modifierArg.prevCoords = undefined;
-    modifierArg.requireEndOnly = true;
-    modifierResult = ___base_26["default"].setAll(modifierArg);
-    state.modifiedXe += modifierResult.delta.x;
-    state.modifiedYe += modifierResult.delta.y;
-    state.timeout = ___raf_26["default"].request(function () {
-      return inertiaTick(interaction);
-    });
-  } else {
-    state.smoothEnd = true;
-    state.xe = modifierResult.delta.x;
-    state.ye = modifierResult.delta.y;
-    state.sx = state.sy = 0;
-    state.timeout = ___raf_26["default"].request(function () {
-      return smothEndTick(interaction);
-    });
-  }
-
-  return false;
-}
-
-function __stop_26(_ref4) {
-  var interaction = _ref4.interaction;
-  var state = interaction.inertia;
-
-  if (state.active) {
-    ___raf_26["default"].cancel(state.timeout);
-
-    state.active = false;
-    interaction.simulation = null;
-  }
-}
-
-function calcInertia(interaction, state) {
-  var options = __getOptions_26(interaction);
-  var lambda = options.resistance;
-  var inertiaDur = -Math.log(options.endSpeed / state.v0) / lambda;
-  state.x0 = interaction.prevEvent.page.x;
-  state.y0 = interaction.prevEvent.page.y;
-  state.t0 = state.startEvent.timeStamp / 1000;
-  state.sx = state.sy = 0;
-  state.modifiedXe = state.xe = (state.vx0 - inertiaDur) / lambda;
-  state.modifiedYe = state.ye = (state.vy0 - inertiaDur) / lambda;
-  state.te = inertiaDur;
-  state.lambda_v0 = lambda / state.v0;
-  state.one_ve_v0 = 1 - options.endSpeed / state.v0;
-}
-
-function inertiaTick(interaction) {
-  updateInertiaCoords(interaction);
-  __utils_26.pointer.setCoordDeltas(interaction.coords.delta, interaction.coords.prev, interaction.coords.cur);
-  __utils_26.pointer.setCoordVelocity(interaction.coords.velocity, interaction.coords.delta);
-  var state = interaction.inertia;
-  var options = __getOptions_26(interaction);
-  var lambda = options.resistance;
-  var t = interaction._now() / 1000 - state.t0;
-
-  if (t < state.te) {
-    var progress = 1 - (Math.exp(-lambda * t) - state.lambda_v0) / state.one_ve_v0;
-
-    if (state.modifiedXe === state.xe && state.modifiedYe === state.ye) {
-      state.sx = state.xe * progress;
-      state.sy = state.ye * progress;
-    } else {
-      var quadPoint = __utils_26.getQuadraticCurvePoint(0, 0, state.xe, state.ye, state.modifiedXe, state.modifiedYe, progress);
-      state.sx = quadPoint.x;
-      state.sy = quadPoint.y;
-    }
-
-    interaction.move();
-    state.timeout = ___raf_26["default"].request(function () {
-      return inertiaTick(interaction);
-    });
-  } else {
-    state.sx = state.modifiedXe;
-    state.sy = state.modifiedYe;
-    interaction.move();
-    interaction.end(state.startEvent);
-    state.active = false;
-    interaction.simulation = null;
-  }
-
-  __utils_26.pointer.copyCoords(interaction.coords.prev, interaction.coords.cur);
-}
-
-function smothEndTick(interaction) {
-  updateInertiaCoords(interaction);
-  var state = interaction.inertia;
-  var t = interaction._now() - state.t0;
-
-  var _getOptions = __getOptions_26(interaction),
-      duration = _getOptions.smoothEndDuration;
-
-  if (t < duration) {
-    state.sx = __utils_26.easeOutQuad(t, 0, state.xe, duration);
-    state.sy = __utils_26.easeOutQuad(t, 0, state.ye, duration);
-    interaction.move();
-    state.timeout = ___raf_26["default"].request(function () {
-      return smothEndTick(interaction);
-    });
-  } else {
-    state.sx = state.xe;
-    state.sy = state.ye;
-    interaction.move();
-    interaction.end(state.startEvent);
-    state.smoothEnd = state.active = false;
-    interaction.simulation = null;
-  }
-}
-
-function updateInertiaCoords(interaction) {
-  var state = interaction.inertia; // return if inertia isn't running
-
-  if (!state.active) {
-    return;
-  }
-
-  var pageUp = state.upCoords.page;
-  var clientUp = state.upCoords.client;
-  __utils_26.pointer.setCoords(interaction.coords.cur, [{
-    pageX: pageUp.x + state.sx,
-    pageY: pageUp.y + state.sy,
-    clientX: clientUp.x + state.sx,
-    clientY: clientUp.y + state.sy
-  }], interaction._now());
-}
-
-function __getOptions_26(_ref5) {
-  var interactable = _ref5.interactable,
-      prepared = _ref5.prepared;
-  return interactable && interactable.options && prepared.name && interactable.options[prepared.name].inertia;
-}
-
-var ___default_26 = {
-  id: 'inertia',
-  install: __install_26,
-  calcInertia: calcInertia,
-  inertiaTick: inertiaTick,
-  smothEndTick: smothEndTick,
-  updateInertiaCoords: updateInertiaCoords
-};
-_$inertia_26["default"] = ___default_26;
-
-var _$pointer_33 = {};
-"use strict";
-
-Object.defineProperty(_$pointer_33, "__esModule", {
-  value: true
-});
-_$pointer_33["default"] = void 0;
-
-var ___extend_33 = ___interopRequireDefault_33(_$extend_53);
-
-var __is_33 = ___interopRequireWildcard_33(_$is_57);
-
-var ___rect_33 = ___interopRequireDefault_33(_$rect_63);
-
-function ___interopRequireWildcard_33(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_33(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __start_33(_ref) {
-  var rect = _ref.rect,
-      startOffset = _ref.startOffset,
-      state = _ref.state,
-      interaction = _ref.interaction,
-      pageCoords = _ref.pageCoords;
-  var options = state.options;
-  var elementRect = options.elementRect;
-  var offset = (0, ___extend_33["default"])({
-    left: 0,
-    top: 0,
-    right: 0,
-    bottom: 0
-  }, options.offset || {});
-
-  if (rect && elementRect) {
-    var restriction = getRestrictionRect(options.restriction, interaction, pageCoords);
-
-    if (restriction) {
-      var widthDiff = restriction.right - restriction.left - rect.width;
-      var heightDiff = restriction.bottom - restriction.top - rect.height;
-
-      if (widthDiff < 0) {
-        offset.left += widthDiff;
-        offset.right += widthDiff;
-      }
-
-      if (heightDiff < 0) {
-        offset.top += heightDiff;
-        offset.bottom += heightDiff;
-      }
-    }
-
-    offset.left += startOffset.left - rect.width * elementRect.left;
-    offset.top += startOffset.top - rect.height * elementRect.top;
-    offset.right += startOffset.right - rect.width * (1 - elementRect.right);
-    offset.bottom += startOffset.bottom - rect.height * (1 - elementRect.bottom);
-  }
-
-  state.offset = offset;
-}
-
-function set(_ref2) {
-  var coords = _ref2.coords,
-      interaction = _ref2.interaction,
-      state = _ref2.state;
-  var options = state.options,
-      offset = state.offset;
-  var restriction = getRestrictionRect(options.restriction, interaction, coords);
-
-  if (!restriction) {
-    return;
-  }
-
-  var rect = ___rect_33["default"].xywhToTlbr(restriction);
-
-  coords.x = Math.max(Math.min(rect.right - offset.right, coords.x), rect.left + offset.left);
-  coords.y = Math.max(Math.min(rect.bottom - offset.bottom, coords.y), rect.top + offset.top);
-}
-
-function getRestrictionRect(value, interaction, coords) {
-  if (__is_33.func(value)) {
-    return ___rect_33["default"].resolveRectLike(value, interaction.interactable, interaction.element, [coords.x, coords.y, interaction]);
-  } else {
-    return ___rect_33["default"].resolveRectLike(value, interaction.interactable, interaction.element);
-  }
-}
-
-var __defaults_33 = {
-  restriction: null,
-  elementRect: null,
-  offset: null,
-  endOnly: false,
-  enabled: false
-};
-var restrict = {
-  start: __start_33,
-  set: set,
-  getRestrictionRect: getRestrictionRect,
-  defaults: __defaults_33
-};
-var ___default_33 = restrict;
-_$pointer_33["default"] = ___default_33;
-
-var _$edges_32 = {};
-"use strict";
-
-Object.defineProperty(_$edges_32, "__esModule", {
-  value: true
-});
-_$edges_32["default"] = void 0;
-
-var ___extend_32 = ___interopRequireDefault_32(_$extend_53);
-
-var ___rect_32 = ___interopRequireDefault_32(_$rect_63);
-
-var _pointer = ___interopRequireDefault_32(_$pointer_33);
-
-function ___interopRequireDefault_32(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-// This module adds the options.resize.restrictEdges setting which sets min and
-// max for the top, left, bottom and right edges of the target being resized.
-//
-// interact(target).resize({
-//   edges: { top: true, left: true },
-//   restrictEdges: {
-//     inner: { top: 200, left: 200, right: 400, bottom: 400 },
-//     outer: { top:   0, left:   0, right: 600, bottom: 600 },
-//   },
-// })
-var __getRestrictionRect_32 = _pointer["default"].getRestrictionRect;
-var noInner = {
-  top: +Infinity,
-  left: +Infinity,
-  bottom: -Infinity,
-  right: -Infinity
-};
-var noOuter = {
-  top: -Infinity,
-  left: -Infinity,
-  bottom: +Infinity,
-  right: +Infinity
-};
-
-function __start_32(_ref) {
-  var interaction = _ref.interaction,
-      state = _ref.state;
-  var options = state.options;
-  var startOffset = interaction.modifiers.startOffset;
-  var offset;
-
-  if (options) {
-    var offsetRect = __getRestrictionRect_32(options.offset, interaction, interaction.coords.start.page);
-    offset = ___rect_32["default"].rectToXY(offsetRect);
-  }
-
-  offset = offset || {
-    x: 0,
-    y: 0
-  };
-  state.offset = {
-    top: offset.y + startOffset.top,
-    left: offset.x + startOffset.left,
-    bottom: offset.y - startOffset.bottom,
-    right: offset.x - startOffset.right
-  };
-}
-
-function __set_32(_ref2) {
-  var coords = _ref2.coords,
-      interaction = _ref2.interaction,
-      state = _ref2.state;
-  var offset = state.offset,
-      options = state.options;
-  var edges = interaction.prepared._linkedEdges || interaction.prepared.edges;
-
-  if (!edges) {
-    return;
-  }
-
-  var page = (0, ___extend_32["default"])({}, coords);
-  var inner = __getRestrictionRect_32(options.inner, interaction, page) || {};
-  var outer = __getRestrictionRect_32(options.outer, interaction, page) || {};
-  fixRect(inner, noInner);
-  fixRect(outer, noOuter);
-
-  if (edges.top) {
-    coords.y = Math.min(Math.max(outer.top + offset.top, page.y), inner.top + offset.top);
-  } else if (edges.bottom) {
-    coords.y = Math.max(Math.min(outer.bottom + offset.bottom, page.y), inner.bottom + offset.bottom);
-  }
-
-  if (edges.left) {
-    coords.x = Math.min(Math.max(outer.left + offset.left, page.x), inner.left + offset.left);
-  } else if (edges.right) {
-    coords.x = Math.max(Math.min(outer.right + offset.right, page.x), inner.right + offset.right);
-  }
-}
-
-function fixRect(rect, defaults) {
-  var _arr = ['top', 'left', 'bottom', 'right'];
-
-  for (var _i = 0; _i < _arr.length; _i++) {
-    var edge = _arr[_i];
-
-    if (!(edge in rect)) {
-      rect[edge] = defaults[edge];
-    }
-  }
-
-  return rect;
-}
-
-var __defaults_32 = {
-  inner: null,
-  outer: null,
-  offset: null,
-  endOnly: false,
-  enabled: false
-};
-var restrictEdges = {
-  noInner: noInner,
-  noOuter: noOuter,
-  getRestrictionRect: __getRestrictionRect_32,
-  start: __start_32,
-  set: __set_32,
-  defaults: __defaults_32
-};
-var ___default_32 = restrictEdges;
-_$edges_32["default"] = ___default_32;
-
-var _$rect_34 = {};
-"use strict";
-
-Object.defineProperty(_$rect_34, "__esModule", {
-  value: true
-});
-_$rect_34["default"] = void 0;
-
-var ___extend_34 = ___interopRequireDefault_34(_$extend_53);
-
-var ___pointer_34 = ___interopRequireDefault_34(_$pointer_33);
-
-function ___interopRequireDefault_34(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var __defaults_34 = (0, ___extend_34["default"])({
-  get elementRect() {
-    return {
-      top: 0,
-      left: 0,
-      bottom: 1,
-      right: 1
-    };
-  },
-
-  set elementRect(_) {}
-
-}, ___pointer_34["default"].defaults);
-var restrictRect = {
-  start: ___pointer_34["default"].start,
-  set: ___pointer_34["default"].set,
-  defaults: __defaults_34
-};
-var ___default_34 = restrictRect;
-_$rect_34["default"] = ___default_34;
-
-var _$size_35 = {};
-"use strict";
-
-Object.defineProperty(_$size_35, "__esModule", {
-  value: true
-});
-_$size_35["default"] = void 0;
-
-var ___extend_35 = ___interopRequireDefault_35(_$extend_53);
-
-var ___rect_35 = ___interopRequireDefault_35(_$rect_63);
-
-var _edges = ___interopRequireDefault_35(_$edges_32);
-
-function ___interopRequireDefault_35(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var noMin = {
-  width: -Infinity,
-  height: -Infinity
-};
-var noMax = {
-  width: +Infinity,
-  height: +Infinity
-};
-
-function __start_35(arg) {
-  return _edges["default"].start(arg);
-}
-
-function __set_35(arg) {
-  var interaction = arg.interaction,
-      state = arg.state;
-  var options = state.options;
-  var edges = interaction.prepared._linkedEdges || interaction.prepared.edges;
-
-  if (!edges) {
-    return;
-  }
-
-  var rect = ___rect_35["default"].xywhToTlbr(interaction.resizeRects.inverted);
-
-  var minSize = ___rect_35["default"].tlbrToXywh(_edges["default"].getRestrictionRect(options.min, interaction, arg.coords)) || noMin;
-  var maxSize = ___rect_35["default"].tlbrToXywh(_edges["default"].getRestrictionRect(options.max, interaction, arg.coords)) || noMax;
-  state.options = {
-    endOnly: options.endOnly,
-    inner: (0, ___extend_35["default"])({}, _edges["default"].noInner),
-    outer: (0, ___extend_35["default"])({}, _edges["default"].noOuter)
-  };
-
-  if (edges.top) {
-    state.options.inner.top = rect.bottom - minSize.height;
-    state.options.outer.top = rect.bottom - maxSize.height;
-  } else if (edges.bottom) {
-    state.options.inner.bottom = rect.top + minSize.height;
-    state.options.outer.bottom = rect.top + maxSize.height;
-  }
-
-  if (edges.left) {
-    state.options.inner.left = rect.right - minSize.width;
-    state.options.outer.left = rect.right - maxSize.width;
-  } else if (edges.right) {
-    state.options.inner.right = rect.left + minSize.width;
-    state.options.outer.right = rect.left + maxSize.width;
-  }
-
-  _edges["default"].set(arg);
-
-  state.options = options;
-}
-
-var __defaults_35 = {
-  min: null,
-  max: null,
-  endOnly: false,
-  enabled: false
-};
-var restrictSize = {
-  start: __start_35,
-  set: __set_35,
-  defaults: __defaults_35
-};
-var ___default_35 = restrictSize;
-_$size_35["default"] = ___default_35;
-
-var _$pointer_37 = {};
-"use strict";
-
-Object.defineProperty(_$pointer_37, "__esModule", {
-  value: true
-});
-_$pointer_37["default"] = void 0;
-
-var __utils_37 = ___interopRequireWildcard_37(_$utils_56);
-
-function ___interopRequireWildcard_37(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __start_37(arg) {
-  var interaction = arg.interaction,
-      interactable = arg.interactable,
-      element = arg.element,
-      rect = arg.rect,
-      state = arg.state,
-      startOffset = arg.startOffset;
-  var options = state.options;
-  var offsets = [];
-  var origin = options.offsetWithOrigin ? getOrigin(arg) : {
-    x: 0,
-    y: 0
-  };
-  var snapOffset;
-
-  if (options.offset === 'startCoords') {
-    snapOffset = {
-      x: interaction.coords.start.page.x,
-      y: interaction.coords.start.page.y
-    };
-  } else {
-    var offsetRect = __utils_37.rect.resolveRectLike(options.offset, interactable, element, [interaction]);
-    snapOffset = __utils_37.rect.rectToXY(offsetRect) || {
-      x: 0,
-      y: 0
-    };
-    snapOffset.x += origin.x;
-    snapOffset.y += origin.y;
-  }
-
-  var relativePoints = options.relativePoints || [];
-
-  if (rect && options.relativePoints && options.relativePoints.length) {
-    for (var index = 0; index < relativePoints.length; index++) {
-      var relativePoint = relativePoints[index];
-      offsets.push({
-        index: index,
-        relativePoint: relativePoint,
-        x: startOffset.left - rect.width * relativePoint.x + snapOffset.x,
-        y: startOffset.top - rect.height * relativePoint.y + snapOffset.y
-      });
-    }
-  } else {
-    offsets.push(__utils_37.extend({
-      index: 0,
-      relativePoint: null
-    }, snapOffset));
-  }
-
-  state.offsets = offsets;
-}
-
-function __set_37(arg) {
-  var interaction = arg.interaction,
-      coords = arg.coords,
-      state = arg.state;
-  var options = state.options,
-      offsets = state.offsets;
-  var origin = __utils_37.getOriginXY(interaction.interactable, interaction.element, interaction.prepared.name);
-  var page = __utils_37.extend({}, coords);
-  var targets = [];
-  var target;
-
-  if (!options.offsetWithOrigin) {
-    page.x -= origin.x;
-    page.y -= origin.y;
-  }
-
-  state.realX = page.x;
-  state.realY = page.y;
-
-  for (var _i = 0; _i < offsets.length; _i++) {
-    var _ref;
-
-    _ref = offsets[_i];
-    var offset = _ref;
-    var relativeX = page.x - offset.x;
-    var relativeY = page.y - offset.y;
-
-    for (var index = 0, _len = options.targets.length; index < _len; index++) {
-      var snapTarget = options.targets[index];
-
-      if (__utils_37.is.func(snapTarget)) {
-        target = snapTarget(relativeX, relativeY, interaction, offset, index);
-      } else {
-        target = snapTarget;
-      }
-
-      if (!target) {
-        continue;
-      }
-
-      targets.push({
-        x: (__utils_37.is.number(target.x) ? target.x : relativeX) + offset.x,
-        y: (__utils_37.is.number(target.y) ? target.y : relativeY) + offset.y,
-        range: __utils_37.is.number(target.range) ? target.range : options.range
-      });
-    }
-  }
-
-  var closest = {
-    target: null,
-    inRange: false,
-    distance: 0,
-    range: 0,
-    dx: 0,
-    dy: 0
-  };
-
-  for (var i = 0, len = targets.length; i < len; i++) {
-    target = targets[i];
-    var range = target.range;
-    var dx = target.x - page.x;
-    var dy = target.y - page.y;
-    var distance = __utils_37.hypot(dx, dy);
-    var inRange = distance <= range; // Infinite targets count as being out of range
-    // compared to non infinite ones that are in range
-
-    if (range === Infinity && closest.inRange && closest.range !== Infinity) {
-      inRange = false;
-    }
-
-    if (!closest.target || (inRange // is the closest target in range?
-    ? closest.inRange && range !== Infinity // the pointer is relatively deeper in this target
-    ? distance / range < closest.distance / closest.range // this target has Infinite range and the closest doesn't
-    : range === Infinity && closest.range !== Infinity || // OR this target is closer that the previous closest
-    distance < closest.distance : // The other is not in range and the pointer is closer to this target
-    !closest.inRange && distance < closest.distance)) {
-      closest.target = target;
-      closest.distance = distance;
-      closest.range = range;
-      closest.inRange = inRange;
-      closest.dx = dx;
-      closest.dy = dy;
-      state.range = range;
-    }
-  }
-
-  if (closest.inRange) {
-    coords.x = closest.target.x;
-    coords.y = closest.target.y;
-  }
-
-  state.closest = closest;
-}
-
-function getOrigin(arg) {
-  var optionsOrigin = __utils_37.rect.rectToXY(__utils_37.rect.resolveRectLike(arg.state.options.origin, [arg.interaction.element]));
-  var origin = optionsOrigin || __utils_37.getOriginXY(arg.interactable, arg.interaction.element, arg.interaction.prepared.name);
-  return origin;
-}
-
-var __defaults_37 = {
-  range: Infinity,
-  targets: null,
-  offset: null,
-  offsetWithOrigin: true,
-  origin: null,
-  relativePoints: null,
-  endOnly: false,
-  enabled: false
-};
-var snap = {
-  start: __start_37,
-  set: __set_37,
-  defaults: __defaults_37
-};
-var ___default_37 = snap;
-_$pointer_37["default"] = ___default_37;
-
-var _$size_38 = {};
-"use strict";
-
-Object.defineProperty(_$size_38, "__esModule", {
-  value: true
-});
-_$size_38["default"] = void 0;
-
-var ___extend_38 = ___interopRequireDefault_38(_$extend_53);
-
-var __is_38 = ___interopRequireWildcard_38(_$is_57);
-
-var ___pointer_38 = ___interopRequireDefault_38(_$pointer_37);
-
-function ___interopRequireWildcard_38(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___interopRequireDefault_38(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___slicedToArray_38(arr, i) { return ___arrayWithHoles_38(arr) || ___iterableToArrayLimit_38(arr, i) || ___nonIterableRest_38(); }
-
-function ___nonIterableRest_38() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
-
-function ___iterableToArrayLimit_38(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
-
-function ___arrayWithHoles_38(arr) { if (Array.isArray(arr)) return arr; }
-
-function __start_38(arg) {
-  var interaction = arg.interaction,
-      state = arg.state;
-  var options = state.options;
-  var edges = interaction.prepared.edges;
-
-  if (!edges) {
-    return null;
-  }
-
-  arg.state = {
-    options: {
-      targets: null,
-      relativePoints: [{
-        x: edges.left ? 0 : 1,
-        y: edges.top ? 0 : 1
-      }],
-      offset: options.offset || 'self',
-      origin: {
-        x: 0,
-        y: 0
-      },
-      range: options.range
-    }
-  };
-  state.targetFields = state.targetFields || [['width', 'height'], ['x', 'y']];
-
-  ___pointer_38["default"].start(arg);
-
-  state.offsets = arg.state.offsets;
-  arg.state = state;
-}
-
-function __set_38(arg) {
-  var interaction = arg.interaction,
-      state = arg.state,
-      coords = arg.coords;
-  var options = state.options,
-      offsets = state.offsets;
-  var relative = {
-    x: coords.x - offsets[0].x,
-    y: coords.y - offsets[0].y
-  };
-  state.options = (0, ___extend_38["default"])({}, options);
-  state.options.targets = [];
-
-  for (var _i = 0; _i < (options.targets || []).length; _i++) {
-    var _ref;
-
-    _ref = (options.targets || [])[_i];
-    var snapTarget = _ref;
-    var target = void 0;
-
-    if (__is_38.func(snapTarget)) {
-      target = snapTarget(relative.x, relative.y, interaction);
-    } else {
-      target = snapTarget;
-    }
-
-    if (!target) {
-      continue;
-    }
-
-    for (var _i2 = 0; _i2 < state.targetFields.length; _i2++) {
-      var _ref2;
-
-      _ref2 = state.targetFields[_i2];
-
-      var _ref3 = _ref2,
-          _ref4 = ___slicedToArray_38(_ref3, 2),
-          xField = _ref4[0],
-          yField = _ref4[1];
-
-      if (xField in target || yField in target) {
-        target.x = target[xField];
-        target.y = target[yField];
-        break;
-      }
-    }
-
-    state.options.targets.push(target);
-  }
-
-  ___pointer_38["default"].set(arg);
-
-  state.options = options;
-}
-
-var __defaults_38 = {
-  range: Infinity,
-  targets: null,
-  offset: null,
-  endOnly: false,
-  enabled: false
-};
-var snapSize = {
-  start: __start_38,
-  set: __set_38,
-  defaults: __defaults_38
-};
-var ___default_38 = snapSize;
-_$size_38["default"] = ___default_38;
-
-var _$edges_36 = {};
-"use strict";
-
-Object.defineProperty(_$edges_36, "__esModule", {
-  value: true
-});
-_$edges_36["default"] = void 0;
-
-var ___clone_36 = ___interopRequireDefault_36(_$clone_49);
-
-var ___extend_36 = ___interopRequireDefault_36(_$extend_53);
-
-var _size = ___interopRequireDefault_36(_$size_38);
-
-function ___interopRequireDefault_36(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-/**
- * @module modifiers/snapEdges
- *
- * @description
- * This module allows snapping of the edges of targets during resize
- * interactions.
- *
- * @example
- * interact(target).resizable({
- *   snapEdges: {
- *     targets: [interact.snappers.grid({ x: 100, y: 50 })],
- *   },
- * })
- *
- * interact(target).resizable({
- *   snapEdges: {
- *     targets: [
- *       interact.snappers.grid({
- *        top: 50,
- *        left: 50,
- *        bottom: 100,
- *        right: 100,
- *       }),
- *     ],
- *   },
- * })
- */
-function __start_36(arg) {
-  var edges = arg.interaction.prepared.edges;
-
-  if (!edges) {
-    return null;
-  }
-
-  arg.state.targetFields = arg.state.targetFields || [[edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom']];
-  return _size["default"].start(arg);
-}
-
-function __set_36(arg) {
-  return _size["default"].set(arg);
-}
-
-var snapEdges = {
-  start: __start_36,
-  set: __set_36,
-  defaults: (0, ___extend_36["default"])((0, ___clone_36["default"])(_size["default"].defaults), {
-    offset: {
-      x: 0,
-      y: 0
-    }
-  })
-};
-var ___default_36 = snapEdges;
-_$edges_36["default"] = ___default_36;
-
-var _$modifiers_31 = {};
-"use strict";
-
-Object.defineProperty(_$modifiers_31, "__esModule", {
-  value: true
-});
-_$modifiers_31.restrictSize = _$modifiers_31.restrictEdges = _$modifiers_31.restrictRect = _$modifiers_31.restrict = _$modifiers_31.snapEdges = _$modifiers_31.snapSize = _$modifiers_31.snap = void 0;
-
-var ___base_31 = ___interopRequireDefault_31(_$base_30);
-
-var ___edges_31 = ___interopRequireDefault_31(_$edges_32);
-
-var ___pointer_31 = ___interopRequireDefault_31(_$pointer_33);
-
-var ___rect_31 = ___interopRequireDefault_31(_$rect_34);
-
-var ___size_31 = ___interopRequireDefault_31(_$size_35);
-
-var _edges2 = ___interopRequireDefault_31(_$edges_36);
-
-var _pointer2 = ___interopRequireDefault_31(_$pointer_37);
-
-var _size2 = ___interopRequireDefault_31(_$size_38);
-
-function ___interopRequireDefault_31(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var __makeModifier_31 = ___base_31["default"].makeModifier;
-var __snap_31 = __makeModifier_31(_pointer2["default"], 'snap');
-_$modifiers_31.snap = __snap_31;
-var __snapSize_31 = __makeModifier_31(_size2["default"], 'snapSize');
-_$modifiers_31.snapSize = __snapSize_31;
-var __snapEdges_31 = __makeModifier_31(_edges2["default"], 'snapEdges');
-_$modifiers_31.snapEdges = __snapEdges_31;
-var __restrict_31 = __makeModifier_31(___pointer_31["default"], 'restrict');
-_$modifiers_31.restrict = __restrict_31;
-var __restrictRect_31 = __makeModifier_31(___rect_31["default"], 'restrictRect');
-_$modifiers_31.restrictRect = __restrictRect_31;
-var __restrictEdges_31 = __makeModifier_31(___edges_31["default"], 'restrictEdges');
-_$modifiers_31.restrictEdges = __restrictEdges_31;
-var __restrictSize_31 = __makeModifier_31(___size_31["default"], 'restrictSize');
-_$modifiers_31.restrictSize = __restrictSize_31;
-
-var _$PointerEvent_39 = {};
-"use strict";
-
-Object.defineProperty(_$PointerEvent_39, "__esModule", {
-  value: true
-});
-_$PointerEvent_39["default"] = void 0;
-
-var ___BaseEvent2_39 = ___interopRequireDefault_39(_$BaseEvent_13);
-
-var ___pointerUtils_39 = ___interopRequireDefault_39(_$pointerUtils_61);
-
-function ___interopRequireDefault_39(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___typeof_39(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ___typeof_39 = function _typeof(obj) { return typeof obj; }; } else { ___typeof_39 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ___typeof_39(obj); }
-
-function ___classCallCheck_39(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function ___defineProperties_39(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function ___createClass_39(Constructor, protoProps, staticProps) { if (protoProps) ___defineProperties_39(Constructor.prototype, protoProps); if (staticProps) ___defineProperties_39(Constructor, staticProps); return Constructor; }
-
-function ___possibleConstructorReturn_39(self, call) { if (call && (___typeof_39(call) === "object" || typeof call === "function")) { return call; } return ___assertThisInitialized_39(self); }
-
-function ___getPrototypeOf_39(o) { ___getPrototypeOf_39 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return ___getPrototypeOf_39(o); }
-
-function ___assertThisInitialized_39(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function ___inherits_39(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) ___setPrototypeOf_39(subClass, superClass); }
-
-function ___setPrototypeOf_39(o, p) { ___setPrototypeOf_39 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return ___setPrototypeOf_39(o, p); }
-
-/** */
-var PointerEvent =
-/*#__PURE__*/
-function (_BaseEvent) {
-  ___inherits_39(PointerEvent, _BaseEvent);
-
-  /** */
-  function PointerEvent(type, pointer, event, eventTarget, interaction, timeStamp) {
-    var _this;
-
-    ___classCallCheck_39(this, PointerEvent);
-
-    _this = ___possibleConstructorReturn_39(this, ___getPrototypeOf_39(PointerEvent).call(this, interaction));
-
-    ___pointerUtils_39["default"].pointerExtend(___assertThisInitialized_39(_this), event);
-
-    if (event !== pointer) {
-      ___pointerUtils_39["default"].pointerExtend(___assertThisInitialized_39(_this), pointer);
-    }
-
-    _this.timeStamp = timeStamp;
-    _this.originalEvent = event;
-    _this.type = type;
-    _this.pointerId = ___pointerUtils_39["default"].getPointerId(pointer);
-    _this.pointerType = ___pointerUtils_39["default"].getPointerType(pointer);
-    _this.target = eventTarget;
-    _this.currentTarget = null;
-
-    if (type === 'tap') {
-      var pointerIndex = interaction.getPointerIndex(pointer);
-      _this.dt = _this.timeStamp - interaction.pointers[pointerIndex].downTime;
-      var interval = _this.timeStamp - interaction.tapTime;
-      _this["double"] = !!(interaction.prevTap && interaction.prevTap.type !== 'doubletap' && interaction.prevTap.target === _this.target && interval < 500);
-    } else if (type === 'doubletap') {
-      _this.dt = pointer.timeStamp - interaction.tapTime;
-    }
-
-    return _this;
-  }
-
-  ___createClass_39(PointerEvent, [{
-    key: "_subtractOrigin",
-    value: function _subtractOrigin(_ref) {
-      var originX = _ref.x,
-          originY = _ref.y;
-      this.pageX -= originX;
-      this.pageY -= originY;
-      this.clientX -= originX;
-      this.clientY -= originY;
-      return this;
-    }
-  }, {
-    key: "_addOrigin",
-    value: function _addOrigin(_ref2) {
-      var originX = _ref2.x,
-          originY = _ref2.y;
-      this.pageX += originX;
-      this.pageY += originY;
-      this.clientX += originX;
-      this.clientY += originY;
-      return this;
-    }
-    /**
-     * Prevent the default behaviour of the original Event
-     */
-
-  }, {
-    key: "preventDefault",
-    value: function preventDefault() {
-      this.originalEvent.preventDefault();
-    }
-  }]);
-
-  return PointerEvent;
-}(___BaseEvent2_39["default"]);
-
-_$PointerEvent_39["default"] = PointerEvent;
-
-var _$base_40 = {};
-"use strict";
-
-Object.defineProperty(_$base_40, "__esModule", {
-  value: true
-});
-_$base_40["default"] = void 0;
-
-var __utils_40 = ___interopRequireWildcard_40(_$utils_56);
-
-var _PointerEvent = ___interopRequireDefault_40(_$PointerEvent_39);
-
-function ___interopRequireDefault_40(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_40(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-var signals = new __utils_40.Signals();
-var simpleSignals = ['down', 'up', 'cancel'];
-var simpleEvents = ['down', 'up', 'cancel'];
-var __defaults_40 = {
-  holdDuration: 600,
-  ignoreFrom: null,
-  allowFrom: null,
-  origin: {
-    x: 0,
-    y: 0
-  }
-};
-var pointerEvents = {
-  id: 'pointer-events/base',
-  install: __install_40,
-  signals: signals,
-  PointerEvent: _PointerEvent["default"],
-  fire: fire,
-  collectEventTargets: collectEventTargets,
-  createSignalListener: createSignalListener,
-  defaults: __defaults_40,
-  types: ['down', 'move', 'up', 'cancel', 'tap', 'doubletap', 'hold']
-};
-
-function fire(arg, scope) {
-  var interaction = arg.interaction,
-      pointer = arg.pointer,
-      event = arg.event,
-      eventTarget = arg.eventTarget,
-      _arg$type = arg.type,
-      type = _arg$type === void 0 ? arg.pointerEvent.type : _arg$type,
-      _arg$targets = arg.targets,
-      targets = _arg$targets === void 0 ? collectEventTargets(arg) : _arg$targets;
-  var _arg$pointerEvent = arg.pointerEvent,
-      pointerEvent = _arg$pointerEvent === void 0 ? new _PointerEvent["default"](type, pointer, event, eventTarget, interaction, scope.now()) : _arg$pointerEvent;
-  var signalArg = {
-    interaction: interaction,
-    pointer: pointer,
-    event: event,
-    eventTarget: eventTarget,
-    targets: targets,
-    type: type,
-    pointerEvent: pointerEvent
-  };
-
-  for (var i = 0; i < targets.length; i++) {
-    var target = targets[i];
-
-    for (var prop in target.props || {}) {
-      pointerEvent[prop] = target.props[prop];
-    }
-
-    var origin = __utils_40.getOriginXY(target.eventable, target.node);
-
-    pointerEvent._subtractOrigin(origin);
-
-    pointerEvent.eventable = target.eventable;
-    pointerEvent.currentTarget = target.node;
-    target.eventable.fire(pointerEvent);
-
-    pointerEvent._addOrigin(origin);
-
-    if (pointerEvent.immediatePropagationStopped || pointerEvent.propagationStopped && i + 1 < targets.length && targets[i + 1].node !== pointerEvent.currentTarget) {
-      break;
-    }
-  }
-
-  signals.fire('fired', signalArg);
-
-  if (type === 'tap') {
-    // if pointerEvent should make a double tap, create and fire a doubletap
-    // PointerEvent and use that as the prevTap
-    var prevTap = pointerEvent["double"] ? fire({
-      interaction: interaction,
-      pointer: pointer,
-      event: event,
-      eventTarget: eventTarget,
-      type: 'doubletap'
-    }, scope) : pointerEvent;
-    interaction.prevTap = prevTap;
-    interaction.tapTime = prevTap.timeStamp;
-  }
-
-  return pointerEvent;
-}
-
-function collectEventTargets(_ref) {
-  var interaction = _ref.interaction,
-      pointer = _ref.pointer,
-      event = _ref.event,
-      eventTarget = _ref.eventTarget,
-      type = _ref.type;
-  var pointerIndex = interaction.getPointerIndex(pointer);
-  var pointerInfo = interaction.pointers[pointerIndex]; // do not fire a tap event if the pointer was moved before being lifted
-
-  if (type === 'tap' && (interaction.pointerWasMoved || // or if the pointerup target is different to the pointerdown target
-  !(pointerInfo && pointerInfo.downTarget === eventTarget))) {
-    return [];
-  }
-
-  var path = __utils_40.dom.getPath(eventTarget);
-  var signalArg = {
-    interaction: interaction,
-    pointer: pointer,
-    event: event,
-    eventTarget: eventTarget,
-    type: type,
-    path: path,
-    targets: [],
-    node: null
-  };
-
-  for (var _i = 0; _i < path.length; _i++) {
-    var _ref2;
-
-    _ref2 = path[_i];
-    var node = _ref2;
-    signalArg.node = node;
-    signals.fire('collect-targets', signalArg);
-  }
-
-  if (type === 'hold') {
-    signalArg.targets = signalArg.targets.filter(function (target) {
-      return target.eventable.options.holdDuration === interaction.pointers[pointerIndex].hold.duration;
-    });
-  }
-
-  return signalArg.targets;
-}
-
-function __install_40(scope) {
-  var interactions = scope.interactions;
-  scope.pointerEvents = pointerEvents;
-  scope.defaults.actions.pointerEvents = pointerEvents.defaults;
-  interactions.signals.on('new', function (_ref3) {
-    var interaction = _ref3.interaction;
-    interaction.prevTap = null; // the most recent tap event on this interaction
-
-    interaction.tapTime = 0; // time of the most recent tap event
-  });
-  interactions.signals.on('update-pointer', function (_ref4) {
-    var down = _ref4.down,
-        pointerInfo = _ref4.pointerInfo;
-
-    if (!down && pointerInfo.hold) {
-      return;
-    }
-
-    pointerInfo.hold = {
-      duration: Infinity,
-      timeout: null
-    };
-  });
-  interactions.signals.on('move', function (_ref5) {
-    var interaction = _ref5.interaction,
-        pointer = _ref5.pointer,
-        event = _ref5.event,
-        eventTarget = _ref5.eventTarget,
-        duplicateMove = _ref5.duplicateMove;
-    var pointerIndex = interaction.getPointerIndex(pointer);
-
-    if (!duplicateMove && (!interaction.pointerIsDown || interaction.pointerWasMoved)) {
-      if (interaction.pointerIsDown) {
-        clearTimeout(interaction.pointers[pointerIndex].hold.timeout);
-      }
-
-      fire({
-        interaction: interaction,
-        pointer: pointer,
-        event: event,
-        eventTarget: eventTarget,
-        type: 'move'
-      }, scope);
-    }
-  });
-  interactions.signals.on('down', function (_ref6) {
-    var interaction = _ref6.interaction,
-        pointer = _ref6.pointer,
-        event = _ref6.event,
-        eventTarget = _ref6.eventTarget,
-        pointerIndex = _ref6.pointerIndex;
-    var timer = interaction.pointers[pointerIndex].hold;
-    var path = __utils_40.dom.getPath(eventTarget);
-    var signalArg = {
-      interaction: interaction,
-      pointer: pointer,
-      event: event,
-      eventTarget: eventTarget,
-      type: 'hold',
-      targets: [],
-      path: path,
-      node: null
-    };
-
-    for (var _i2 = 0; _i2 < path.length; _i2++) {
-      var _ref7;
-
-      _ref7 = path[_i2];
-      var node = _ref7;
-      signalArg.node = node;
-      signals.fire('collect-targets', signalArg);
-    }
-
-    if (!signalArg.targets.length) {
-      return;
-    }
-
-    var minDuration = Infinity;
-
-    for (var _i3 = 0; _i3 < signalArg.targets.length; _i3++) {
-      var _ref8;
-
-      _ref8 = signalArg.targets[_i3];
-      var target = _ref8;
-      var holdDuration = target.eventable.options.holdDuration;
-
-      if (holdDuration < minDuration) {
-        minDuration = holdDuration;
-      }
-    }
-
-    timer.duration = minDuration;
-    timer.timeout = setTimeout(function () {
-      fire({
-        interaction: interaction,
-        eventTarget: eventTarget,
-        pointer: pointer,
-        event: event,
-        type: 'hold'
-      }, scope);
-    }, minDuration);
-  });
-  var _arr = ['up', 'cancel'];
-
-  for (var _i4 = 0; _i4 < _arr.length; _i4++) {
-    var signalName = _arr[_i4];
-    interactions.signals.on(signalName, function (_ref10) {
-      var interaction = _ref10.interaction,
-          pointerIndex = _ref10.pointerIndex;
-
-      if (interaction.pointers[pointerIndex].hold) {
-        clearTimeout(interaction.pointers[pointerIndex].hold.timeout);
-      }
-    });
-  }
-
-  for (var i = 0; i < simpleSignals.length; i++) {
-    interactions.signals.on(simpleSignals[i], createSignalListener(simpleEvents[i], scope));
-  }
-
-  interactions.signals.on('up', function (_ref9) {
-    var interaction = _ref9.interaction,
-        pointer = _ref9.pointer,
-        event = _ref9.event,
-        eventTarget = _ref9.eventTarget;
-
-    if (!interaction.pointerWasMoved) {
-      fire({
-        interaction: interaction,
-        eventTarget: eventTarget,
-        pointer: pointer,
-        event: event,
-        type: 'tap'
-      }, scope);
-    }
-  });
-}
-
-function createSignalListener(type, scope) {
-  return function (_ref11) {
-    var interaction = _ref11.interaction,
-        pointer = _ref11.pointer,
-        event = _ref11.event,
-        eventTarget = _ref11.eventTarget;
-    fire({
-      interaction: interaction,
-      eventTarget: eventTarget,
-      pointer: pointer,
-      event: event,
-      type: type
-    }, scope);
-  };
-}
-
-var ___default_40 = pointerEvents;
-_$base_40["default"] = ___default_40;
-
-var _$holdRepeat_41 = {};
-"use strict";
-
-Object.defineProperty(_$holdRepeat_41, "__esModule", {
-  value: true
-});
-_$holdRepeat_41["default"] = void 0;
-
-var ___base_41 = ___interopRequireDefault_41(_$base_40);
-
-function ___interopRequireDefault_41(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_41(scope) {
-  var pointerEvents = scope.pointerEvents,
-      interactions = scope.interactions;
-  scope.usePlugin(___base_41["default"]);
-  pointerEvents.signals.on('new', onNew);
-  pointerEvents.signals.on('fired', function (arg) {
-    return onFired(arg, scope);
-  });
-  var _arr = ['move', 'up', 'cancel', 'endall'];
-
-  for (var _i = 0; _i < _arr.length; _i++) {
-    var signal = _arr[_i];
-    interactions.signals.on(signal, endHoldRepeat);
-  } // don't repeat by default
-
-
-  pointerEvents.defaults.holdRepeatInterval = 0;
-  pointerEvents.types.push('holdrepeat');
-}
-
-function onNew(_ref) {
-  var pointerEvent = _ref.pointerEvent;
-
-  if (pointerEvent.type !== 'hold') {
-    return;
-  }
-
-  pointerEvent.count = (pointerEvent.count || 0) + 1;
-}
-
-function onFired(_ref2, scope) {
-  var interaction = _ref2.interaction,
-      pointerEvent = _ref2.pointerEvent,
-      eventTarget = _ref2.eventTarget,
-      targets = _ref2.targets;
-
-  if (pointerEvent.type !== 'hold' || !targets.length) {
-    return;
-  } // get the repeat interval from the first eventable
-
-
-  var interval = targets[0].eventable.options.holdRepeatInterval; // don't repeat if the interval is 0 or less
-
-  if (interval <= 0) {
-    return;
-  } // set a timeout to fire the holdrepeat event
-
-
-  interaction.holdIntervalHandle = setTimeout(function () {
-    scope.pointerEvents.fire({
-      interaction: interaction,
-      eventTarget: eventTarget,
-      type: 'hold',
-      pointer: pointerEvent,
-      event: pointerEvent
-    }, scope);
-  }, interval);
-}
-
-function endHoldRepeat(_ref3) {
-  var interaction = _ref3.interaction;
-
-  // set the interaction's holdStopTime property
-  // to stop further holdRepeat events
-  if (interaction.holdIntervalHandle) {
-    clearInterval(interaction.holdIntervalHandle);
-    interaction.holdIntervalHandle = null;
-  }
-}
-
-var ___default_41 = {
-  id: 'pointer-events/holdRepeat',
-  install: __install_41
-};
-_$holdRepeat_41["default"] = ___default_41;
-
-var _$interactableTargets_43 = {};
-"use strict";
-
-Object.defineProperty(_$interactableTargets_43, "__esModule", {
-  value: true
-});
-_$interactableTargets_43["default"] = void 0;
-
-/* removed: var _$arr_47 = require("@interactjs/utils/arr"); */;
-
-var ___extend_43 = ___interopRequireDefault_43(_$extend_53);
-
-function ___interopRequireDefault_43(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_43(scope) {
-  var pointerEvents = scope.pointerEvents,
-      actions = scope.actions,
-      Interactable = scope.Interactable,
-      interactables = scope.interactables;
-  pointerEvents.signals.on('collect-targets', function (_ref) {
-    var targets = _ref.targets,
-        node = _ref.node,
-        type = _ref.type,
-        eventTarget = _ref.eventTarget;
-    scope.interactables.forEachMatch(node, function (interactable) {
-      var eventable = interactable.events;
-      var options = eventable.options;
-
-      if (eventable.types[type] && eventable.types[type].length && interactable.testIgnoreAllow(options, node, eventTarget)) {
-        targets.push({
-          node: node,
-          eventable: eventable,
-          props: {
-            interactable: interactable
-          }
-        });
-      }
-    });
-  });
-  interactables.signals.on('new', function (_ref2) {
-    var interactable = _ref2.interactable;
-
-    interactable.events.getRect = function (element) {
-      return interactable.getRect(element);
-    };
-  });
-  interactables.signals.on('set', function (_ref3) {
-    var interactable = _ref3.interactable,
-        options = _ref3.options;
-    (0, ___extend_43["default"])(interactable.events.options, pointerEvents.defaults);
-    (0, ___extend_43["default"])(interactable.events.options, options.pointerEvents || {});
-  });
-  (0, _$arr_47.merge)(actions.eventTypes, pointerEvents.types);
-  Interactable.prototype.pointerEvents = pointerEventsMethod;
-  var __backCompatOption = Interactable.prototype._backCompatOption;
-
-  Interactable.prototype._backCompatOption = function (optionName, newValue) {
-    var ret = __backCompatOption.call(this, optionName, newValue);
-
-    if (ret === this) {
-      this.events.options[optionName] = newValue;
-    }
-
-    return ret;
-  };
-}
-
-function pointerEventsMethod(options) {
-  (0, ___extend_43["default"])(this.events.options, options);
-  return this;
-}
-
-var ___default_43 = {
-  id: 'pointer-events/interactableTargets',
-  install: __install_43
-};
-_$interactableTargets_43["default"] = ___default_43;
-
-var _$pointerEvents_42 = {};
-"use strict";
-
-Object.defineProperty(_$pointerEvents_42, "__esModule", {
-  value: true
-});
-_$pointerEvents_42.install = __install_42;
-Object.defineProperty(_$pointerEvents_42, "pointerEvents", {
-  enumerable: true,
-  get: function get() {
-    return ___base_42["default"];
-  }
-});
-Object.defineProperty(_$pointerEvents_42, "holdRepeat", {
-  enumerable: true,
-  get: function get() {
-    return _holdRepeat["default"];
-  }
-});
-Object.defineProperty(_$pointerEvents_42, "interactableTargets", {
-  enumerable: true,
-  get: function get() {
-    return _interactableTargets["default"];
-  }
-});
-_$pointerEvents_42.id = void 0;
-
-var ___base_42 = ___interopRequireDefault_42(_$base_40);
-
-var _holdRepeat = ___interopRequireDefault_42(_$holdRepeat_41);
-
-var _interactableTargets = ___interopRequireDefault_42(_$interactableTargets_43);
-
-function ___interopRequireDefault_42(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function __install_42(scope) {
-  scope.usePlugin(___base_42["default"]);
-  scope.usePlugin(_holdRepeat["default"]);
-  scope.usePlugin(_interactableTargets["default"]);
-}
-
-var __id_42 = 'pointer-events';
-_$pointerEvents_42.id = __id_42;
-
-var _$reflow_44 = {};
-"use strict";
-
-Object.defineProperty(_$reflow_44, "__esModule", {
-  value: true
-});
-_$reflow_44.install = __install_44;
-_$reflow_44["default"] = void 0;
-
-/* removed: var _$InteractEvent_15 = require("@interactjs/core/InteractEvent"); */;
-
-/* removed: var _$utils_56 = require("@interactjs/utils"); */;
-
-_$InteractEvent_15.EventPhase.Reflow = 'reflow';
-
-function __install_44(scope) {
-  var actions = scope.actions,
-      interactions = scope.interactions,
-      Interactable = scope.Interactable; // add action reflow event types
-
-  for (var _i = 0; _i < actions.names.length; _i++) {
-    var _ref;
-
-    _ref = actions.names[_i];
-    var actionName = _ref;
-    actions.eventTypes.push("".concat(actionName, "reflow"));
-  } // remove completed reflow interactions
-
-
-  interactions.signals.on('stop', function (_ref2) {
-    var interaction = _ref2.interaction;
-
-    if (interaction.pointerType === _$InteractEvent_15.EventPhase.Reflow) {
-      if (interaction._reflowResolve) {
-        interaction._reflowResolve();
-      }
-
-      _$utils_56.arr.remove(scope.interactions.list, interaction);
-    }
-  });
-  /**
-   * ```js
-   * const interactable = interact(target)
-   * const drag = { name: drag, axis: 'x' }
-   * const resize = { name: resize, edges: { left: true, bottom: true }
-   *
-   * interactable.reflow(drag)
-   * interactable.reflow(resize)
-   * ```
-   *
-   * Start an action sequence to re-apply modifiers, check drops, etc.
-   *
-   * @param { Object } action The action to begin
-   * @param { string } action.name The name of the action
-   * @returns { Promise }
-   */
-
-  Interactable.prototype.reflow = function (action) {
-    return reflow(this, action, scope);
-  };
-}
-
-function reflow(interactable, action, scope) {
-  var elements = _$utils_56.is.string(interactable.target) ? _$utils_56.arr.from(interactable._context.querySelectorAll(interactable.target)) : [interactable.target]; // tslint:disable-next-line variable-name
-
-  var Promise = _$utils_56.win.window.Promise;
-  var promises = Promise ? [] : null;
-
-  var _loop = function _loop() {
-    _ref3 = elements[_i2];
-    var element = _ref3;
-    var rect = interactable.getRect(element);
-
-    if (!rect) {
-      return "break";
-    }
-
-    var runningInteraction = _$utils_56.arr.find(scope.interactions.list, function (interaction) {
-      return interaction.interacting() && interaction.interactable === interactable && interaction.element === element && interaction.prepared.name === action.name;
-    });
-
-    var reflowPromise = void 0;
-
-    if (runningInteraction) {
-      runningInteraction.move();
-
-      if (promises) {
-        reflowPromise = runningInteraction._reflowPromise || new Promise(function (resolve) {
-          runningInteraction._reflowResolve = resolve;
-        });
-      }
-    } else {
-      var xywh = _$utils_56.rect.tlbrToXywh(rect);
-
-      var coords = {
-        page: {
-          x: xywh.x,
-          y: xywh.y
-        },
-        client: {
-          x: xywh.x,
-          y: xywh.y
-        },
-        timeStamp: scope.now()
-      };
-
-      var event = _$utils_56.pointer.coordsToEvent(coords);
-
-      reflowPromise = startReflow(scope, interactable, element, action, event);
-    }
-
-    if (promises) {
-      promises.push(reflowPromise);
-    }
-  };
-
-  for (var _i2 = 0; _i2 < elements.length; _i2++) {
-    var _ref3;
-
-    var _ret = _loop();
-
-    if (_ret === "break") break;
-  }
-
-  return promises && Promise.all(promises).then(function () {
-    return interactable;
-  });
-}
-
-function startReflow(scope, interactable, element, action, event) {
-  var interaction = scope.interactions["new"]({
-    pointerType: 'reflow'
-  });
-  var signalArg = {
-    interaction: interaction,
-    event: event,
-    pointer: event,
-    eventTarget: element,
-    phase: _$InteractEvent_15.EventPhase.Reflow
-  };
-  interaction.interactable = interactable;
-  interaction.element = element;
-  interaction.prepared = (0, _$utils_56.extend)({}, action);
-  interaction.prevEvent = event;
-  interaction.updatePointer(event, event, element, true);
-
-  interaction._doPhase(signalArg);
-
-  var reflowPromise = _$utils_56.win.window.Promise ? new _$utils_56.win.window.Promise(function (resolve) {
-    interaction._reflowResolve = resolve;
-  }) : null;
-  interaction._reflowPromise = reflowPromise;
-  interaction.start(action, interactable, element);
-
-  if (interaction._interacting) {
-    interaction.move(signalArg);
-    interaction.end(event);
-  } else {
-    interaction.stop();
-  }
-
-  interaction.removePointer(event, event);
-  interaction.pointerIsDown = false;
-  return reflowPromise;
-}
-
-var ___default_44 = {
-  id: 'reflow',
-  install: __install_44
-};
-_$reflow_44["default"] = ___default_44;
-
-var _$interact_28 = {};
-"use strict";
-
-Object.defineProperty(_$interact_28, "__esModule", {
-  value: true
-});
-_$interact_28["default"] = _$interact_28.scope = _$interact_28.interact = void 0;
-
-var ___scope_28 = _$scope_24({});
-
-var __utils_28 = ___interopRequireWildcard_28(_$utils_56);
-
-var ___browser_28 = ___interopRequireDefault_28(_$browser_48);
-
-var ___events_28 = ___interopRequireDefault_28(_$events_52);
-
-function ___interopRequireDefault_28(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_28(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-/** @module interact */
-var globalEvents = {};
-var scope = new ___scope_28.Scope();
-/**
- * ```js
- * interact('#draggable').draggable(true)
- *
- * var rectables = interact('rect')
- * rectables
- *   .gesturable(true)
- *   .on('gesturemove', function (event) {
- *       // ...
- *   })
- * ```
- *
- * The methods of this variable can be used to set elements as interactables
- * and also to change various default settings.
- *
- * Calling it as a function and passing an element or a valid CSS selector
- * string returns an Interactable object which has various methods to configure
- * it.
- *
- * @global
- *
- * @param {Element | string} target The HTML or SVG Element to interact with
- * or CSS selector
- * @return {Interactable}
- */
-
-_$interact_28.scope = scope;
-
-var interact = function interact(target, options) {
-  var interactable = scope.interactables.get(target, options);
-
-  if (!interactable) {
-    interactable = scope.interactables["new"](target, options);
-    interactable.events.global = globalEvents;
-  }
-
-  return interactable;
-};
-/**
- * Use a plugin
- *
- * @alias module:interact.use
- *
- * @param {Object} plugin
- * @param {function} plugin.install
- * @return {interact}
- */
-
-
-_$interact_28.interact = interact;
-interact.use = use;
-
-function use(plugin, options) {
-  scope.usePlugin(plugin, options);
-  return interact;
-}
-/**
- * Check if an element or selector has been set with the {@link interact}
- * function
- *
- * @alias module:interact.isSet
- *
- * @param {Element} element The Element being searched for
- * @return {boolean} Indicates if the element or CSS selector was previously
- * passed to interact
- */
-
-
-interact.isSet = isSet;
-
-function isSet(target, options) {
-  return !!scope.interactables.get(target, options && options.context);
-}
-/**
- * Add a global listener for an InteractEvent or adds a DOM event to `document`
- *
- * @alias module:interact.on
- *
- * @param {string | array | object} type The types of events to listen for
- * @param {function} listener The function event (s)
- * @param {object | boolean} [options] object or useCapture flag for
- * addEventListener
- * @return {object} interact
- */
-
-
-interact.on = on;
-
-function on(type, listener, options) {
-  if (__utils_28.is.string(type) && type.search(' ') !== -1) {
-    type = type.trim().split(/ +/);
-  }
-
-  if (__utils_28.is.array(type)) {
-    for (var _i = 0; _i < type.length; _i++) {
-      var _ref;
-
-      _ref = type[_i];
-      var eventType = _ref;
-      interact.on(eventType, listener, options);
-    }
-
-    return interact;
-  }
-
-  if (__utils_28.is.object(type)) {
-    for (var prop in type) {
-      interact.on(prop, type[prop], listener);
-    }
-
-    return interact;
-  } // if it is an InteractEvent type, add listener to globalEvents
-
-
-  if (__utils_28.arr.contains(scope.actions.eventTypes, type)) {
-    // if this type of event was never bound
-    if (!globalEvents[type]) {
-      globalEvents[type] = [listener];
-    } else {
-      globalEvents[type].push(listener);
-    }
-  } // If non InteractEvent type, addEventListener to document
-  else {
-      ___events_28["default"].add(scope.document, type, listener, {
-        options: options
-      });
-    }
-
-  return interact;
-}
-/**
- * Removes a global InteractEvent listener or DOM event from `document`
- *
- * @alias module:interact.off
- *
- * @param {string | array | object} type The types of events that were listened
- * for
- * @param {function} listener The listener function to be removed
- * @param {object | boolean} options [options] object or useCapture flag for
- * removeEventListener
- * @return {object} interact
- */
-
-
-interact.off = off;
-
-function off(type, listener, options) {
-  if (__utils_28.is.string(type) && type.search(' ') !== -1) {
-    type = type.trim().split(/ +/);
-  }
-
-  if (__utils_28.is.array(type)) {
-    for (var _i2 = 0; _i2 < type.length; _i2++) {
-      var _ref2;
-
-      _ref2 = type[_i2];
-      var eventType = _ref2;
-      interact.off(eventType, listener, options);
-    }
-
-    return interact;
-  }
-
-  if (__utils_28.is.object(type)) {
-    for (var prop in type) {
-      interact.off(prop, type[prop], listener);
-    }
-
-    return interact;
-  }
-
-  if (!__utils_28.arr.contains(scope.actions.eventTypes, type)) {
-    ___events_28["default"].remove(scope.document, type, listener, options);
-  } else {
-    var index;
-
-    if (type in globalEvents && (index = globalEvents[type].indexOf(listener)) !== -1) {
-      globalEvents[type].splice(index, 1);
-    }
-  }
-
-  return interact;
-}
-/**
- * Returns an object which exposes internal data
- * @alias module:interact.debug
- *
- * @return {object} An object with properties that outline the current state
- * and expose internal functions and variables
- */
-
-
-interact.debug = debug;
-
-function debug() {
-  return scope;
-} // expose the functions used to calculate multi-touch properties
-
-
-interact.getPointerAverage = __utils_28.pointer.pointerAverage;
-interact.getTouchBBox = __utils_28.pointer.touchBBox;
-interact.getTouchDistance = __utils_28.pointer.touchDistance;
-interact.getTouchAngle = __utils_28.pointer.touchAngle;
-interact.getElementRect = __utils_28.dom.getElementRect;
-interact.getElementClientRect = __utils_28.dom.getElementClientRect;
-interact.matchesSelector = __utils_28.dom.matchesSelector;
-interact.closest = __utils_28.dom.closest;
-/**
- * @alias module:interact.supportsTouch
- *
- * @return {boolean} Whether or not the browser supports touch input
- */
-
-interact.supportsTouch = supportsTouch;
-
-function supportsTouch() {
-  return ___browser_28["default"].supportsTouch;
-}
-/**
- * @alias module:interact.supportsPointerEvent
- *
- * @return {boolean} Whether or not the browser supports PointerEvents
- */
-
-
-interact.supportsPointerEvent = supportsPointerEvent;
-
-function supportsPointerEvent() {
-  return ___browser_28["default"].supportsPointerEvent;
-}
-/**
- * Cancels all interactions (end events are not fired)
- *
- * @alias module:interact.stop
- *
- * @return {object} interact
- */
-
-
-interact.stop = __stop_28;
-
-function __stop_28() {
-  for (var _i3 = 0; _i3 < scope.interactions.list.length; _i3++) {
-    var _ref3;
-
-    _ref3 = scope.interactions.list[_i3];
-    var interaction = _ref3;
-    interaction.stop();
-  }
-
-  return interact;
-}
-/**
- * Returns or sets the distance the pointer must be moved before an action
- * sequence occurs. This also affects tolerance for tap events.
- *
- * @alias module:interact.pointerMoveTolerance
- *
- * @param {number} [newValue] The movement from the start position must be greater than this value
- * @return {interact | number}
- */
-
-
-interact.pointerMoveTolerance = pointerMoveTolerance;
-
-function pointerMoveTolerance(newValue) {
-  if (__utils_28.is.number(newValue)) {
-    scope.interactions.pointerMoveTolerance = newValue;
-    return interact;
-  }
-
-  return scope.interactions.pointerMoveTolerance;
-}
-
-scope.interactables.signals.on('unset', function (_ref4) {
-  var interactable = _ref4.interactable;
-  scope.interactables.list.splice(scope.interactables.list.indexOf(interactable), 1); // Stop related interactions when an Interactable is unset
-
-  for (var _i4 = 0; _i4 < scope.interactions.list.length; _i4++) {
-    var _ref5;
-
-    _ref5 = scope.interactions.list[_i4];
-    var interaction = _ref5;
-
-    if (interaction.interactable === interactable && interaction.interacting() && !interaction._ending) {
-      interaction.stop();
-    }
-  }
-});
-
-interact.addDocument = function (doc, options) {
-  return scope.addDocument(doc, options);
-};
-
-interact.removeDocument = function (doc) {
-  return scope.removeDocument(doc);
-};
-
-scope.interact = interact;
-var ___default_28 = interact;
-_$interact_28["default"] = ___default_28;
-
-var _$interact_27 = {};
-"use strict";
-
-Object.defineProperty(_$interact_27, "__esModule", {
-  value: true
-});
-_$interact_27.init = __init_27;
-Object.defineProperty(_$interact_27, "autoScroll", {
-  enumerable: true,
-  get: function get() {
-    return _autoScroll["default"];
-  }
-});
-Object.defineProperty(_$interact_27, "interactablePreventDefault", {
-  enumerable: true,
-  get: function get() {
-    return _interactablePreventDefault["default"];
-  }
-});
-Object.defineProperty(_$interact_27, "inertia", {
-  enumerable: true,
-  get: function get() {
-    return _inertia["default"];
-  }
-});
-Object.defineProperty(_$interact_27, "modifiers", {
-  enumerable: true,
-  get: function get() {
-    return ___base_27["default"];
-  }
-});
-Object.defineProperty(_$interact_27, "reflow", {
-  enumerable: true,
-  get: function get() {
-    return _reflow["default"];
-  }
-});
-Object.defineProperty(_$interact_27, "interact", {
-  enumerable: true,
-  get: function get() {
-    return _interact["default"];
-  }
-});
-_$interact_27.pointerEvents = _$interact_27.actions = _$interact_27["default"] = void 0;
-
-var actions = ___interopRequireWildcard_27(_$actions_5);
-
-_$interact_27.actions = actions;
-
-var _autoScroll = ___interopRequireDefault_27(_$autoScroll_7);
-
-var autoStart = ___interopRequireWildcard_27(_$autoStart_12);
-
-var _interactablePreventDefault = ___interopRequireDefault_27(_$interactablePreventDefault_21);
-
-var _devTools = ___interopRequireDefault_27(_$devTools_25);
-
-var _inertia = ___interopRequireDefault_27(_$inertia_26);
-
-var modifiers = ___interopRequireWildcard_27(_$modifiers_31);
-
-var ___base_27 = ___interopRequireDefault_27(_$base_30);
-
-var __pointerEvents_27 = ___interopRequireWildcard_27(_$pointerEvents_42);
-
-_$interact_27.pointerEvents = __pointerEvents_27;
-
-var _reflow = ___interopRequireDefault_27(_$reflow_44);
-
-var _interact = ___interopRequireWildcard_27(_$interact_28);
-
-function ___interopRequireDefault_27(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_27(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function __init_27(window) {
-  _interact.scope.init(window);
-
-  _interact["default"].use(_interactablePreventDefault["default"]); // pointerEvents
-
-
-  _interact["default"].use(__pointerEvents_27); // inertia
-
-
-  _interact["default"].use(_inertia["default"]); // autoStart, hold
-
-
-  _interact["default"].use(autoStart); // drag and drop, resize, gesture
-
-
-  _interact["default"].use(actions); // snap, resize, etc.
-
-
-  _interact["default"].use(___base_27["default"]); // for backwrads compatibility
-
-
-  for (var type in modifiers) {
-    var _modifiers$type = modifiers[type],
-        _defaults = _modifiers$type._defaults,
-        _methods = _modifiers$type._methods;
-    _defaults._methods = _methods;
-    _interact.scope.defaults.perAction[type] = _defaults;
-  } // autoScroll
-
-
-  _interact["default"].use(_autoScroll["default"]); // reflow
-
-
-  _interact["default"].use(_reflow["default"]); // eslint-disable-next-line no-undef
-
-
-  if ("production" !== 'production') {
-    _interact["default"].use(_devTools["default"]);
-  }
-
-  return _interact["default"];
-} // eslint-disable-next-line no-undef
-
-
-_interact["default"].version = "1.6.2";
-var ___default_27 = _interact["default"];
-_$interact_27["default"] = ___default_27;
-
-var _$types_45 = {};
-/// 
-"use strict";
-
-var _$grid_64 = {};
-"use strict";
-
-Object.defineProperty(_$grid_64, "__esModule", {
-  value: true
-});
-_$grid_64["default"] = void 0;
-
-function ___slicedToArray_64(arr, i) { return ___arrayWithHoles_64(arr) || ___iterableToArrayLimit_64(arr, i) || ___nonIterableRest_64(); }
-
-function ___nonIterableRest_64() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
-
-function ___iterableToArrayLimit_64(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
-
-function ___arrayWithHoles_64(arr) { if (Array.isArray(arr)) return arr; }
-
-function createGrid(grid) {
-  var coordFields = [['x', 'y'], ['left', 'top'], ['right', 'bottom'], ['width', 'height']].filter(function (_ref) {
-    var _ref2 = ___slicedToArray_64(_ref, 2),
-        xField = _ref2[0],
-        yField = _ref2[1];
-
-    return xField in grid || yField in grid;
-  });
-  return function (x, y) {
-    var range = grid.range,
-        _grid$limits = grid.limits,
-        limits = _grid$limits === void 0 ? {
-      left: -Infinity,
-      right: Infinity,
-      top: -Infinity,
-      bottom: Infinity
-    } : _grid$limits,
-        _grid$offset = grid.offset,
-        offset = _grid$offset === void 0 ? {
-      x: 0,
-      y: 0
-    } : _grid$offset;
-    var result = {
-      range: range
-    };
-
-    for (var _i2 = 0; _i2 < coordFields.length; _i2++) {
-      var _ref3;
-
-      _ref3 = coordFields[_i2];
-
-      var _ref4 = _ref3,
-          _ref5 = ___slicedToArray_64(_ref4, 2),
-          xField = _ref5[0],
-          yField = _ref5[1];
-
-      var gridx = Math.round((x - offset.x) / grid[xField]);
-      var gridy = Math.round((y - offset.y) / grid[yField]);
-      result[xField] = Math.max(limits.left, Math.min(limits.right, gridx * grid[xField] + offset.x));
-      result[yField] = Math.max(limits.top, Math.min(limits.bottom, gridy * grid[yField] + offset.y));
-    }
-
-    return result;
-  };
-}
-
-var ___default_64 = createGrid;
-_$grid_64["default"] = ___default_64;
-
-var _$snappers_65 = {};
-"use strict";
-
-Object.defineProperty(_$snappers_65, "__esModule", {
-  value: true
-});
-Object.defineProperty(_$snappers_65, "grid", {
-  enumerable: true,
-  get: function get() {
-    return _grid["default"];
-  }
-});
-
-var _grid = ___interopRequireDefault_65(_$grid_64);
-
-function ___interopRequireDefault_65(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-var _$index_29 = { exports: {} };
-"use strict";
-
-Object.defineProperty(_$index_29.exports, "__esModule", {
-  value: true
-});
-_$index_29.exports.init = __init_29;
-_$index_29.exports["default"] = void 0;
-
-var ___interact_29 = ___interopRequireWildcard_29(_$interact_27);
-
-var __modifiers_29 = ___interopRequireWildcard_29(_$modifiers_31);
-
-_$types_45;
-
-var ___extend_29 = ___interopRequireDefault_29(_$extend_53);
-
-var snappers = ___interopRequireWildcard_29(_$snappers_65);
-
-function ___interopRequireDefault_29(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
-
-function ___interopRequireWildcard_29(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
-
-function ___typeof_29(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ___typeof_29 = function _typeof(obj) { return typeof obj; }; } else { ___typeof_29 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ___typeof_29(obj); }
-
-if ((typeof window === "undefined" ? "undefined" : ___typeof_29(window)) === 'object' && !!window) {
-  __init_29(window);
-}
-
-function __init_29(win) {
-  (0, ___interact_29.init)(win);
-  return ___interact_29["default"].use({
-    id: 'interactjs',
-    install: function install() {
-      ___interact_29["default"].modifiers = (0, ___extend_29["default"])({}, __modifiers_29);
-      ___interact_29["default"].snappers = snappers;
-      ___interact_29["default"].createSnapGrid = ___interact_29["default"].snappers.grid;
-    }
-  });
-}
-
-var ___default_29 = ___interact_29["default"];
-_$index_29.exports["default"] = ___default_29;
-___interact_29["default"]['default'] = ___interact_29["default"]; // tslint:disable-line no-string-literal
-
-___interact_29["default"]['init'] = __init_29; // tslint:disable-line no-string-literal
-
-if (("object" === "undefined" ? "undefined" : ___typeof_29(_$index_29)) === 'object' && !!_$index_29) {
-  _$index_29.exports = ___interact_29["default"];
-}
-
-_$index_29 = _$index_29.exports
-return _$index_29;
-
-});
-
-
-//# sourceMappingURL=interact.js.map
diff --git a/lib/svg.js b/lib/svg.js
deleted file mode 100644
index 28b2793..0000000
--- a/lib/svg.js
+++ /dev/null
@@ -1,5601 +0,0 @@
-/*!
-* svg.js - A lightweight library for manipulating and animating SVG.
-* @version 2.7.1
-* https://svgdotjs.github.io/
-*
-* @copyright Wout Fierens 
-* @license MIT
-*
-* BUILT: Fri Nov 30 2018 10:01:55 GMT+0100 (GMT+01:00)
-*/;
-(function(root, factory) {
-  /* istanbul ignore next */
-  if (typeof define === 'function' && define.amd) {
-    define(function(){
-      return factory(root, root.document)
-    })
-  } else if (typeof exports === 'object') {
-    module.exports = root.document ? factory(root, root.document) : function(w){ return factory(w, w.document) }
-  } else {
-    root.SVG = factory(root, root.document)
-  }
-}(typeof window !== "undefined" ? window : this, function(window, document) {
-
-// Find global reference - uses 'this' by default when available,
-// falls back to 'window' otherwise (for bundlers like Webpack)
-var globalRef = (typeof this !== "undefined") ? this : window;
-
-// The main wrapping element
-var SVG = globalRef.SVG = function(element) {
-  if (SVG.supported) {
-    element = new SVG.Doc(element)
-
-    if(!SVG.parser.draw)
-      SVG.prepare()
-
-    return element
-  }
-}
-
-// Default namespaces
-SVG.ns    = 'http://www.w3.org/2000/svg'
-SVG.xmlns = 'http://www.w3.org/2000/xmlns/'
-SVG.xlink = 'http://www.w3.org/1999/xlink'
-SVG.svgjs = 'http://svgjs.com/svgjs'
-
-// Svg support test
-SVG.supported = (function() {
-  return !! document.createElementNS &&
-         !! document.createElementNS(SVG.ns,'svg').createSVGRect
-})()
-
-// Don't bother to continue if SVG is not supported
-if (!SVG.supported) return false
-
-// Element id sequence
-SVG.did  = 1000
-
-// Get next named element id
-SVG.eid = function(name) {
-  return 'Svgjs' + capitalize(name) + (SVG.did++)
-}
-
-// Method for element creation
-SVG.create = function(name) {
-  // create element
-  var element = document.createElementNS(this.ns, name)
-
-  // apply unique id
-  element.setAttribute('id', this.eid(name))
-
-  return element
-}
-
-// Method for extending objects
-SVG.extend = function() {
-  var modules, methods, key, i
-
-  // Get list of modules
-  modules = [].slice.call(arguments)
-
-  // Get object with extensions
-  methods = modules.pop()
-
-  for (i = modules.length - 1; i >= 0; i--)
-    if (modules[i])
-      for (key in methods)
-        modules[i].prototype[key] = methods[key]
-
-  // Make sure SVG.Set inherits any newly added methods
-  if (SVG.Set && SVG.Set.inherit)
-    SVG.Set.inherit()
-}
-
-// Invent new element
-SVG.invent = function(config) {
-  // Create element initializer
-  var initializer = typeof config.create == 'function' ?
-    config.create :
-    function() {
-      this.constructor.call(this, SVG.create(config.create))
-    }
-
-  // Inherit prototype
-  if (config.inherit)
-    initializer.prototype = new config.inherit
-
-  // Extend with methods
-  if (config.extend)
-    SVG.extend(initializer, config.extend)
-
-  // Attach construct method to parent
-  if (config.construct)
-    SVG.extend(config.parent || SVG.Container, config.construct)
-
-  return initializer
-}
-
-// Adopt existing svg elements
-SVG.adopt = function(node) {
-  // check for presence of node
-  if (!node) return null
-
-  // make sure a node isn't already adopted
-  if (node.instance) return node.instance
-
-  // initialize variables
-  var element
-
-  // adopt with element-specific settings
-  if (node.nodeName == 'svg')
-    element = node.parentNode instanceof window.SVGElement ? new SVG.Nested : new SVG.Doc
-  else if (node.nodeName == 'linearGradient')
-    element = new SVG.Gradient('linear')
-  else if (node.nodeName == 'radialGradient')
-    element = new SVG.Gradient('radial')
-  else if (SVG[capitalize(node.nodeName)])
-    element = new SVG[capitalize(node.nodeName)]
-  else
-    element = new SVG.Element(node)
-
-  // ensure references
-  element.type  = node.nodeName
-  element.node  = node
-  node.instance = element
-
-  // SVG.Class specific preparations
-  if (element instanceof SVG.Doc)
-    element.namespace().defs()
-
-  // pull svgjs data from the dom (getAttributeNS doesn't work in html5)
-  element.setData(JSON.parse(node.getAttribute('svgjs:data')) || {})
-
-  return element
-}
-
-// Initialize parsing element
-SVG.prepare = function() {
-  // Select document body and create invisible svg element
-  var body = document.getElementsByTagName('body')[0]
-    , draw = (body ? new SVG.Doc(body) : SVG.adopt(document.documentElement).nested()).size(2, 0)
-
-  // Create parser object
-  SVG.parser = {
-    body: body || document.documentElement
-  , draw: draw.style('opacity:0;position:absolute;left:-100%;top:-100%;overflow:hidden').attr('focusable', 'false').node
-  , poly: draw.polyline().node
-  , path: draw.path().node
-  , native: SVG.create('svg')
-  }
-}
-
-SVG.parser = {
-  native: SVG.create('svg')
-}
-
-document.addEventListener('DOMContentLoaded', function() {
-  if(!SVG.parser.draw)
-    SVG.prepare()
-}, false)
-
-// Storage for regular expressions
-SVG.regex = {
-  // Parse unit value
-  numberAndUnit:    /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i
-
-  // Parse hex value
-, hex:              /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
-
-  // Parse rgb value
-, rgb:              /rgb\((\d+),(\d+),(\d+)\)/
-
-  // Parse reference id
-, reference:        /#([a-z0-9\-_]+)/i
-
-  // splits a transformation chain
-, transforms:       /\)\s*,?\s*/
-
-  // Whitespace
-, whitespace:       /\s/g
-
-  // Test hex value
-, isHex:            /^#[a-f0-9]{3,6}$/i
-
-  // Test rgb value
-, isRgb:            /^rgb\(/
-
-  // Test css declaration
-, isCss:            /[^:]+:[^;]+;?/
-
-  // Test for blank string
-, isBlank:          /^(\s+)?$/
-
-  // Test for numeric string
-, isNumber:         /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i
-
-  // Test for percent value
-, isPercent:        /^-?[\d\.]+%$/
-
-  // Test for image url
-, isImage:          /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i
-
-  // split at whitespace and comma
-, delimiter:        /[\s,]+/
-
-  // The following regex are used to parse the d attribute of a path
-
-  // Matches all hyphens which are not after an exponent
-, hyphen:           /([^e])\-/gi
-
-  // Replaces and tests for all path letters
-, pathLetters:      /[MLHVCSQTAZ]/gi
-
-  // yes we need this one, too
-, isPathLetter:     /[MLHVCSQTAZ]/i
-
-  // matches 0.154.23.45
-, numbersWithDots:  /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi
-
-  // matches .
-, dots:             /\./g
-}
-
-SVG.utils = {
-  // Map function
-  map: function(array, block) {
-    var i
-      , il = array.length
-      , result = []
-
-    for (i = 0; i < il; i++)
-      result.push(block(array[i]))
-
-    return result
-  }
-
-  // Filter function
-, filter: function(array, block) {
-    var i
-      , il = array.length
-      , result = []
-
-    for (i = 0; i < il; i++)
-      if (block(array[i]))
-        result.push(array[i])
-
-    return result
-  }
-
-  // Degrees to radians
-, radians: function(d) {
-    return d % 360 * Math.PI / 180
-  }
-
-  // Radians to degrees
-, degrees: function(r) {
-    return r * 180 / Math.PI % 360
-  }
-
-, filterSVGElements: function(nodes) {
-    return this.filter( nodes, function(el) { return el instanceof window.SVGElement })
-  }
-
-}
-
-SVG.defaults = {
-  // Default attribute values
-  attrs: {
-    // fill and stroke
-    'fill-opacity':     1
-  , 'stroke-opacity':   1
-  , 'stroke-width':     0
-  , 'stroke-linejoin':  'miter'
-  , 'stroke-linecap':   'butt'
-  , fill:               '#000000'
-  , stroke:             '#000000'
-  , opacity:            1
-    // position
-  , x:                  0
-  , y:                  0
-  , cx:                 0
-  , cy:                 0
-    // size
-  , width:              0
-  , height:             0
-    // radius
-  , r:                  0
-  , rx:                 0
-  , ry:                 0
-    // gradient
-  , offset:             0
-  , 'stop-opacity':     1
-  , 'stop-color':       '#000000'
-    // text
-  , 'font-size':        16
-  , 'font-family':      'Helvetica, Arial, sans-serif'
-  , 'text-anchor':      'start'
-  }
-
-}
-// Module for color convertions
-SVG.Color = function(color) {
-  var match
-
-  // initialize defaults
-  this.r = 0
-  this.g = 0
-  this.b = 0
-
-  if(!color) return
-
-  // parse color
-  if (typeof color === 'string') {
-    if (SVG.regex.isRgb.test(color)) {
-      // get rgb values
-      match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace,''))
-
-      // parse numeric values
-      this.r = parseInt(match[1])
-      this.g = parseInt(match[2])
-      this.b = parseInt(match[3])
-
-    } else if (SVG.regex.isHex.test(color)) {
-      // get hex values
-      match = SVG.regex.hex.exec(fullHex(color))
-
-      // parse numeric values
-      this.r = parseInt(match[1], 16)
-      this.g = parseInt(match[2], 16)
-      this.b = parseInt(match[3], 16)
-
-    }
-
-  } else if (typeof color === 'object') {
-    this.r = color.r
-    this.g = color.g
-    this.b = color.b
-
-  }
-
-}
-
-SVG.extend(SVG.Color, {
-  // Default to hex conversion
-  toString: function() {
-    return this.toHex()
-  }
-  // Build hex value
-, toHex: function() {
-    return '#'
-      + compToHex(this.r)
-      + compToHex(this.g)
-      + compToHex(this.b)
-  }
-  // Build rgb value
-, toRgb: function() {
-    return 'rgb(' + [this.r, this.g, this.b].join() + ')'
-  }
-  // Calculate true brightness
-, brightness: function() {
-    return (this.r / 255 * 0.30)
-         + (this.g / 255 * 0.59)
-         + (this.b / 255 * 0.11)
-  }
-  // Make color morphable
-, morph: function(color) {
-    this.destination = new SVG.Color(color)
-
-    return this
-  }
-  // Get morphed color at given position
-, at: function(pos) {
-    // make sure a destination is defined
-    if (!this.destination) return this
-
-    // normalise pos
-    pos = pos < 0 ? 0 : pos > 1 ? 1 : pos
-
-    // generate morphed color
-    return new SVG.Color({
-      r: ~~(this.r + (this.destination.r - this.r) * pos)
-    , g: ~~(this.g + (this.destination.g - this.g) * pos)
-    , b: ~~(this.b + (this.destination.b - this.b) * pos)
-    })
-  }
-
-})
-
-// Testers
-
-// Test if given value is a color string
-SVG.Color.test = function(color) {
-  color += ''
-  return SVG.regex.isHex.test(color)
-      || SVG.regex.isRgb.test(color)
-}
-
-// Test if given value is a rgb object
-SVG.Color.isRgb = function(color) {
-  return color && typeof color.r == 'number'
-               && typeof color.g == 'number'
-               && typeof color.b == 'number'
-}
-
-// Test if given value is a color
-SVG.Color.isColor = function(color) {
-  return SVG.Color.isRgb(color) || SVG.Color.test(color)
-}
-// Module for array conversion
-SVG.Array = function(array, fallback) {
-  array = (array || []).valueOf()
-
-  // if array is empty and fallback is provided, use fallback
-  if (array.length == 0 && fallback)
-    array = fallback.valueOf()
-
-  // parse array
-  this.value = this.parse(array)
-}
-
-SVG.extend(SVG.Array, {
-  // Make array morphable
-  morph: function(array) {
-    this.destination = this.parse(array)
-
-    // normalize length of arrays
-    if (this.value.length != this.destination.length) {
-      var lastValue       = this.value[this.value.length - 1]
-        , lastDestination = this.destination[this.destination.length - 1]
-
-      while(this.value.length > this.destination.length)
-        this.destination.push(lastDestination)
-      while(this.value.length < this.destination.length)
-        this.value.push(lastValue)
-    }
-
-    return this
-  }
-  // Clean up any duplicate points
-, settle: function() {
-    // find all unique values
-    for (var i = 0, il = this.value.length, seen = []; i < il; i++)
-      if (seen.indexOf(this.value[i]) == -1)
-        seen.push(this.value[i])
-
-    // set new value
-    return this.value = seen
-  }
-  // Get morphed array at given position
-, at: function(pos) {
-    // make sure a destination is defined
-    if (!this.destination) return this
-
-    // generate morphed array
-    for (var i = 0, il = this.value.length, array = []; i < il; i++)
-      array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos)
-
-    return new SVG.Array(array)
-  }
-  // Convert array to string
-, toString: function() {
-    return this.value.join(' ')
-  }
-  // Real value
-, valueOf: function() {
-    return this.value
-  }
-  // Parse whitespace separated string
-, parse: function(array) {
-    array = array.valueOf()
-
-    // if already is an array, no need to parse it
-    if (Array.isArray(array)) return array
-
-    return this.split(array)
-  }
-  // Strip unnecessary whitespace
-, split: function(string) {
-    return string.trim().split(SVG.regex.delimiter).map(parseFloat)
-  }
-  // Reverse array
-, reverse: function() {
-    this.value.reverse()
-
-    return this
-  }
-, clone: function() {
-    var clone = new this.constructor()
-    clone.value = array_clone(this.value)
-    return clone
-  }
-})
-// Poly points array
-SVG.PointArray = function(array, fallback) {
-  SVG.Array.call(this, array, fallback || [[0,0]])
-}
-
-// Inherit from SVG.Array
-SVG.PointArray.prototype = new SVG.Array
-SVG.PointArray.prototype.constructor = SVG.PointArray
-
-SVG.extend(SVG.PointArray, {
-  // Convert array to string
-  toString: function() {
-    // convert to a poly point string
-    for (var i = 0, il = this.value.length, array = []; i < il; i++)
-      array.push(this.value[i].join(','))
-
-    return array.join(' ')
-  }
-  // Convert array to line object
-, toLine: function() {
-    return {
-      x1: this.value[0][0]
-    , y1: this.value[0][1]
-    , x2: this.value[1][0]
-    , y2: this.value[1][1]
-    }
-  }
-  // Get morphed array at given position
-, at: function(pos) {
-    // make sure a destination is defined
-    if (!this.destination) return this
-
-    // generate morphed point string
-    for (var i = 0, il = this.value.length, array = []; i < il; i++)
-      array.push([
-        this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos
-      , this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos
-      ])
-
-    return new SVG.PointArray(array)
-  }
-  // Parse point string and flat array
-, parse: function(array) {
-    var points = []
-
-    array = array.valueOf()
-
-    // if it is an array
-    if (Array.isArray(array)) {
-      // and it is not flat, there is no need to parse it
-      if(Array.isArray(array[0])) {
-        // make sure to use a clone
-        return array.map(function (el) { return el.slice() })
-      } else if (array[0].x != null){
-        // allow point objects to be passed
-        return array.map(function (el) { return [el.x, el.y] })
-      }
-    } else { // Else, it is considered as a string
-      // parse points
-      array = array.trim().split(SVG.regex.delimiter).map(parseFloat)
-    }
-
-    // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
-    // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.
-    if (array.length % 2 !== 0) array.pop()
-
-    // wrap points in two-tuples and parse points as floats
-    for(var i = 0, len = array.length; i < len; i = i + 2)
-      points.push([ array[i], array[i+1] ])
-
-    return points
-  }
-  // Move point string
-, move: function(x, y) {
-    var box = this.bbox()
-
-    // get relative offset
-    x -= box.x
-    y -= box.y
-
-    // move every point
-    if (!isNaN(x) && !isNaN(y))
-      for (var i = this.value.length - 1; i >= 0; i--)
-        this.value[i] = [this.value[i][0] + x, this.value[i][1] + y]
-
-    return this
-  }
-  // Resize poly string
-, size: function(width, height) {
-    var i, box = this.bbox()
-
-    // recalculate position of all points according to new size
-    for (i = this.value.length - 1; i >= 0; i--) {
-      if(box.width) this.value[i][0] = ((this.value[i][0] - box.x) * width)  / box.width  + box.x
-      if(box.height) this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
-    }
-
-    return this
-  }
-  // Get bounding box of points
-, bbox: function() {
-    SVG.parser.poly.setAttribute('points', this.toString())
-
-    return SVG.parser.poly.getBBox()
-  }
-})
-
-var pathHandlers = {
-  M: function(c, p, p0) {
-    p.x = p0.x = c[0]
-    p.y = p0.y = c[1]
-
-    return ['M', p.x, p.y]
-  },
-  L: function(c, p) {
-    p.x = c[0]
-    p.y = c[1]
-    return ['L', c[0], c[1]]
-  },
-  H: function(c, p) {
-    p.x = c[0]
-    return ['H', c[0]]
-  },
-  V: function(c, p) {
-    p.y = c[0]
-    return ['V', c[0]]
-  },
-  C: function(c, p) {
-    p.x = c[4]
-    p.y = c[5]
-    return ['C', c[0], c[1], c[2], c[3], c[4], c[5]]
-  },
-  S: function(c, p) {
-    p.x = c[2]
-    p.y = c[3]
-    return ['S', c[0], c[1], c[2], c[3]]
-  },
-  Q: function(c, p) {
-    p.x = c[2]
-    p.y = c[3]
-    return ['Q', c[0], c[1], c[2], c[3]]
-  },
-  T: function(c, p) {
-    p.x = c[0]
-    p.y = c[1]
-    return ['T', c[0], c[1]]
-  },
-  Z: function(c, p, p0) {
-    p.x = p0.x
-    p.y = p0.y
-    return ['Z']
-  },
-  A: function(c, p) {
-    p.x = c[5]
-    p.y = c[6]
-    return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]]
-  }
-}
-
-var mlhvqtcsa = 'mlhvqtcsaz'.split('')
-
-for(var i = 0, il = mlhvqtcsa.length; i < il; ++i){
-  pathHandlers[mlhvqtcsa[i]] = (function(i){
-    return function(c, p, p0) {
-      if(i == 'H') c[0] = c[0] + p.x
-      else if(i == 'V') c[0] = c[0] + p.y
-      else if(i == 'A'){
-        c[5] = c[5] + p.x,
-        c[6] = c[6] + p.y
-      }
-      else
-        for(var j = 0, jl = c.length; j < jl; ++j) {
-          c[j] = c[j] + (j%2 ? p.y : p.x)
-        }
-
-      return pathHandlers[i](c, p, p0)
-    }
-  })(mlhvqtcsa[i].toUpperCase())
-}
-
-// Path points array
-SVG.PathArray = function(array, fallback) {
-  SVG.Array.call(this, array, fallback || [['M', 0, 0]])
-}
-
-// Inherit from SVG.Array
-SVG.PathArray.prototype = new SVG.Array
-SVG.PathArray.prototype.constructor = SVG.PathArray
-
-SVG.extend(SVG.PathArray, {
-  // Convert array to string
-  toString: function() {
-    return arrayToString(this.value)
-  }
-  // Move path string
-, move: function(x, y) {
-    // get bounding box of current situation
-    var box = this.bbox()
-
-    // get relative offset
-    x -= box.x
-    y -= box.y
-
-    if (!isNaN(x) && !isNaN(y)) {
-      // move every point
-      for (var l, i = this.value.length - 1; i >= 0; i--) {
-        l = this.value[i][0]
-
-        if (l == 'M' || l == 'L' || l == 'T')  {
-          this.value[i][1] += x
-          this.value[i][2] += y
-
-        } else if (l == 'H')  {
-          this.value[i][1] += x
-
-        } else if (l == 'V')  {
-          this.value[i][1] += y
-
-        } else if (l == 'C' || l == 'S' || l == 'Q')  {
-          this.value[i][1] += x
-          this.value[i][2] += y
-          this.value[i][3] += x
-          this.value[i][4] += y
-
-          if (l == 'C')  {
-            this.value[i][5] += x
-            this.value[i][6] += y
-          }
-
-        } else if (l == 'A')  {
-          this.value[i][6] += x
-          this.value[i][7] += y
-        }
-
-      }
-    }
-
-    return this
-  }
-  // Resize path string
-, size: function(width, height) {
-    // get bounding box of current situation
-    var i, l, box = this.bbox()
-
-    // recalculate position of all points according to new size
-    for (i = this.value.length - 1; i >= 0; i--) {
-      l = this.value[i][0]
-
-      if (l == 'M' || l == 'L' || l == 'T')  {
-        this.value[i][1] = ((this.value[i][1] - box.x) * width)  / box.width  + box.x
-        this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
-
-      } else if (l == 'H')  {
-        this.value[i][1] = ((this.value[i][1] - box.x) * width)  / box.width  + box.x
-
-      } else if (l == 'V')  {
-        this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
-
-      } else if (l == 'C' || l == 'S' || l == 'Q')  {
-        this.value[i][1] = ((this.value[i][1] - box.x) * width)  / box.width  + box.x
-        this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
-        this.value[i][3] = ((this.value[i][3] - box.x) * width)  / box.width  + box.x
-        this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y
-
-        if (l == 'C')  {
-          this.value[i][5] = ((this.value[i][5] - box.x) * width)  / box.width  + box.x
-          this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y
-        }
-
-      } else if (l == 'A')  {
-        // resize radii
-        this.value[i][1] = (this.value[i][1] * width)  / box.width
-        this.value[i][2] = (this.value[i][2] * height) / box.height
-
-        // move position values
-        this.value[i][6] = ((this.value[i][6] - box.x) * width)  / box.width  + box.x
-        this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y
-      }
-
-    }
-
-    return this
-  }
-  // Test if the passed path array use the same path data commands as this path array
-, equalCommands: function(pathArray) {
-    var i, il, equalCommands
-
-    pathArray = new SVG.PathArray(pathArray)
-
-    equalCommands = this.value.length === pathArray.value.length
-    for(i = 0, il = this.value.length; equalCommands && i < il; i++) {
-      equalCommands = this.value[i][0] === pathArray.value[i][0]
-    }
-
-    return equalCommands
-  }
-  // Make path array morphable
-, morph: function(pathArray) {
-    pathArray = new SVG.PathArray(pathArray)
-
-    if(this.equalCommands(pathArray)) {
-      this.destination = pathArray
-    } else {
-      this.destination = null
-    }
-
-    return this
-  }
-  // Get morphed path array at given position
-, at: function(pos) {
-    // make sure a destination is defined
-    if (!this.destination) return this
-
-    var sourceArray = this.value
-      , destinationArray = this.destination.value
-      , array = [], pathArray = new SVG.PathArray()
-      , i, il, j, jl
-
-    // Animate has specified in the SVG spec
-    // See: https://www.w3.org/TR/SVG11/paths.html#PathElement
-    for (i = 0, il = sourceArray.length; i < il; i++) {
-      array[i] = [sourceArray[i][0]]
-      for(j = 1, jl = sourceArray[i].length; j < jl; j++) {
-        array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos
-      }
-      // For the two flags of the elliptical arc command, the SVG spec say:
-      // Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true
-      // Elliptical arc command as an array followed by corresponding indexes:
-      // ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
-      //   0    1   2        3                 4             5      6  7
-      if(array[i][0] === 'A') {
-        array[i][4] = +(array[i][4] != 0)
-        array[i][5] = +(array[i][5] != 0)
-      }
-    }
-
-    // Directly modify the value of a path array, this is done this way for performance
-    pathArray.value = array
-    return pathArray
-  }
-  // Absolutize and parse path to array
-, parse: function(array) {
-    // if it's already a patharray, no need to parse it
-    if (array instanceof SVG.PathArray) return array.valueOf()
-
-    // prepare for parsing
-    var i, x0, y0, s, seg, arr
-      , x = 0
-      , y = 0
-      , paramCnt = { 'M':2, 'L':2, 'H':1, 'V':1, 'C':6, 'S':4, 'Q':4, 'T':2, 'A':7, 'Z':0 }
-
-    if(typeof array == 'string'){
-
-      array = array
-        .replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123
-        .replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers
-        .replace(SVG.regex.hyphen, '$1 -')      // add space before hyphen
-        .trim()                                 // trim
-        .split(SVG.regex.delimiter)   // split into array
-
-    }else{
-      array = array.reduce(function(prev, curr){
-        return [].concat.call(prev, curr)
-      }, [])
-    }
-
-    // array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...]
-    var arr = []
-      , p = new SVG.Point()
-      , p0 = new SVG.Point()
-      , index = 0
-      , len = array.length
-
-    do{
-      // Test if we have a path letter
-      if(SVG.regex.isPathLetter.test(array[index])){
-        s = array[index]
-        ++index
-      // If last letter was a move command and we got no new, it defaults to [L]ine
-      }else if(s == 'M'){
-        s = 'L'
-      }else if(s == 'm'){
-        s = 'l'
-      }
-
-      arr.push(pathHandlers[s].call(null,
-          array.slice(index, (index = index + paramCnt[s.toUpperCase()])).map(parseFloat),
-          p, p0
-        )
-      )
-
-    }while(len > index)
-
-    return arr
-
-  }
-  // Get bounding box of path
-, bbox: function() {
-    SVG.parser.path.setAttribute('d', this.toString())
-
-    return SVG.parser.path.getBBox()
-  }
-
-})
-
-// Module for unit convertions
-SVG.Number = SVG.invent({
-  // Initialize
-  create: function(value, unit) {
-    // initialize defaults
-    this.value = 0
-    this.unit  = unit || ''
-
-    // parse value
-    if (typeof value === 'number') {
-      // ensure a valid numeric value
-      this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
-
-    } else if (typeof value === 'string') {
-      unit = value.match(SVG.regex.numberAndUnit)
-
-      if (unit) {
-        // make value numeric
-        this.value = parseFloat(unit[1])
-
-        // normalize
-        if (unit[5] == '%')
-          this.value /= 100
-        else if (unit[5] == 's')
-          this.value *= 1000
-
-        // store unit
-        this.unit = unit[5]
-      }
-
-    } else {
-      if (value instanceof SVG.Number) {
-        this.value = value.valueOf()
-        this.unit  = value.unit
-      }
-    }
-
-  }
-  // Add methods
-, extend: {
-    // Stringalize
-    toString: function() {
-      return (
-        this.unit == '%' ?
-          ~~(this.value * 1e8) / 1e6:
-        this.unit == 's' ?
-          this.value / 1e3 :
-          this.value
-      ) + this.unit
-    }
-  , toJSON: function() {
-      return this.toString()
-    }
-  , // Convert to primitive
-    valueOf: function() {
-      return this.value
-    }
-    // Add number
-  , plus: function(number) {
-      number = new SVG.Number(number)
-      return new SVG.Number(this + number, this.unit || number.unit)
-    }
-    // Subtract number
-  , minus: function(number) {
-      number = new SVG.Number(number)
-      return new SVG.Number(this - number, this.unit || number.unit)
-    }
-    // Multiply number
-  , times: function(number) {
-      number = new SVG.Number(number)
-      return new SVG.Number(this * number, this.unit || number.unit)
-    }
-    // Divide number
-  , divide: function(number) {
-      number = new SVG.Number(number)
-      return new SVG.Number(this / number, this.unit || number.unit)
-    }
-    // Convert to different unit
-  , to: function(unit) {
-      var number = new SVG.Number(this)
-
-      if (typeof unit === 'string')
-        number.unit = unit
-
-      return number
-    }
-    // Make number morphable
-  , morph: function(number) {
-      this.destination = new SVG.Number(number)
-
-      if(number.relative) {
-        this.destination.value += this.value
-      }
-
-      return this
-    }
-    // Get morphed number at given position
-  , at: function(pos) {
-      // Make sure a destination is defined
-      if (!this.destination) return this
-
-      // Generate new morphed number
-      return new SVG.Number(this.destination)
-          .minus(this)
-          .times(pos)
-          .plus(this)
-    }
-
-  }
-})
-
-
-SVG.Element = SVG.invent({
-  // Initialize node
-  create: function(node) {
-    // make stroke value accessible dynamically
-    this._stroke = SVG.defaults.attrs.stroke
-    this._event = null
-    this._events = {}
-
-    // initialize data object
-    this.dom = {}
-
-    // create circular reference
-    if (this.node = node) {
-      this.type = node.nodeName
-      this.node.instance = this
-      this._events = node._events || {}
-
-      // store current attribute value
-      this._stroke = node.getAttribute('stroke') || this._stroke
-    }
-  }
-
-  // Add class methods
-, extend: {
-    // Move over x-axis
-    x: function(x) {
-      return this.attr('x', x)
-    }
-    // Move over y-axis
-  , y: function(y) {
-      return this.attr('y', y)
-    }
-    // Move by center over x-axis
-  , cx: function(x) {
-      return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2)
-    }
-    // Move by center over y-axis
-  , cy: function(y) {
-      return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2)
-    }
-    // Move element to given x and y values
-  , move: function(x, y) {
-      return this.x(x).y(y)
-    }
-    // Move element by its center
-  , center: function(x, y) {
-      return this.cx(x).cy(y)
-    }
-    // Set width of element
-  , width: function(width) {
-      return this.attr('width', width)
-    }
-    // Set height of element
-  , height: function(height) {
-      return this.attr('height', height)
-    }
-    // Set element size to given width and height
-  , size: function(width, height) {
-      var p = proportionalSize(this, width, height)
-
-      return this
-        .width(new SVG.Number(p.width))
-        .height(new SVG.Number(p.height))
-    }
-    // Clone element
-  , clone: function(parent) {
-      // write dom data to the dom so the clone can pickup the data
-      this.writeDataToDom()
-
-      // clone element and assign new id
-      var clone = assignNewId(this.node.cloneNode(true))
-
-      // insert the clone in the given parent or after myself
-      if(parent) parent.add(clone)
-      else this.after(clone)
-
-      return clone
-    }
-    // Remove element
-  , remove: function() {
-      if (this.parent())
-        this.parent().removeElement(this)
-
-      return this
-    }
-    // Replace element
-  , replace: function(element) {
-      this.after(element).remove()
-
-      return element
-    }
-    // Add element to given container and return self
-  , addTo: function(parent) {
-      return parent.put(this)
-    }
-    // Add element to given container and return container
-  , putIn: function(parent) {
-      return parent.add(this)
-    }
-    // Get / set id
-  , id: function(id) {
-      return this.attr('id', id)
-    }
-    // Checks whether the given point inside the bounding box of the element
-  , inside: function(x, y) {
-      var box = this.bbox()
-
-      return x > box.x
-          && y > box.y
-          && x < box.x + box.width
-          && y < box.y + box.height
-    }
-    // Show element
-  , show: function() {
-      return this.style('display', '')
-    }
-    // Hide element
-  , hide: function() {
-      return this.style('display', 'none')
-    }
-    // Is element visible?
-  , visible: function() {
-      return this.style('display') != 'none'
-    }
-    // Return id on string conversion
-  , toString: function() {
-      return this.attr('id')
-    }
-    // Return array of classes on the node
-  , classes: function() {
-      var attr = this.attr('class')
-
-      return attr == null ? [] : attr.trim().split(SVG.regex.delimiter)
-    }
-    // Return true if class exists on the node, false otherwise
-  , hasClass: function(name) {
-      return this.classes().indexOf(name) != -1
-    }
-    // Add class to the node
-  , addClass: function(name) {
-      if (!this.hasClass(name)) {
-        var array = this.classes()
-        array.push(name)
-        this.attr('class', array.join(' '))
-      }
-
-      return this
-    }
-    // Remove class from the node
-  , removeClass: function(name) {
-      if (this.hasClass(name)) {
-        this.attr('class', this.classes().filter(function(c) {
-          return c != name
-        }).join(' '))
-      }
-
-      return this
-    }
-    // Toggle the presence of a class on the node
-  , toggleClass: function(name) {
-      return this.hasClass(name) ? this.removeClass(name) : this.addClass(name)
-    }
-    // Get referenced element form attribute value
-  , reference: function(attr) {
-      return SVG.get(this.attr(attr))
-    }
-    // Returns the parent element instance
-  , parent: function(type) {
-      var parent = this
-
-      // check for parent
-      if(!parent.node.parentNode) return null
-
-      // get parent element
-      parent = SVG.adopt(parent.node.parentNode)
-
-      if(!type) return parent
-
-      // loop trough ancestors if type is given
-      while(parent && parent.node instanceof window.SVGElement){
-        if(typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent
-        if(!parent.node.parentNode || parent.node.parentNode.nodeName == '#document' || parent.node.parentNode.nodeName == '#document-fragment') return null // #759, #720
-        parent = SVG.adopt(parent.node.parentNode)
-      }
-    }
-    // Get parent document
-  , doc: function() {
-      return this instanceof SVG.Doc ? this : this.parent(SVG.Doc)
-    }
-    // return array of all ancestors of given type up to the root svg
-  , parents: function(type) {
-      var parents = [], parent = this
-
-      do{
-        parent = parent.parent(type)
-        if(!parent || !parent.node) break
-
-        parents.push(parent)
-      } while(parent.parent)
-
-      return parents
-    }
-    // matches the element vs a css selector
-  , matches: function(selector){
-      return matches(this.node, selector)
-    }
-    // Returns the svg node to call native svg methods on it
-  , native: function() {
-      return this.node
-    }
-    // Import raw svg
-  , svg: function(svg) {
-      // create temporary holder
-      var well = document.createElement('svg')
-
-      // act as a setter if svg is given
-      if (svg && this instanceof SVG.Parent) {
-        // dump raw svg
-        well.innerHTML = '' + svg.replace(/\n/, '').replace(/<([\w:-]+)([^<]+?)\/>/g, '<$1$2>') + ''
-
-        // transplant nodes
-        for (var i = 0, il = well.firstChild.childNodes.length; i < il; i++)
-          this.node.appendChild(well.firstChild.firstChild)
-
-      // otherwise act as a getter
-      } else {
-        // create a wrapping svg element in case of partial content
-        well.appendChild(svg = document.createElement('svg'))
-
-        // write svgjs data to the dom
-        this.writeDataToDom()
-
-        // insert a copy of this node
-        svg.appendChild(this.node.cloneNode(true))
-
-        // return target element
-        return well.innerHTML.replace(/^/, '').replace(/<\/svg>$/, '')
-      }
-
-      return this
-    }
-  // write svgjs data to the dom
-  , writeDataToDom: function() {
-
-      // dump variables recursively
-      if(this.each || this.lines){
-        var fn = this.each ? this : this.lines();
-        fn.each(function(){
-          this.writeDataToDom()
-        })
-      }
-
-      // remove previously set data
-      this.node.removeAttribute('svgjs:data')
-
-      if(Object.keys(this.dom).length)
-        this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)) // see #428
-
-      return this
-    }
-  // set given data to the elements data property
-  , setData: function(o){
-      this.dom = o
-      return this
-    }
-  , is: function(obj){
-      return is(this, obj)
-    }
-  }
-})
-
-SVG.easing = {
-  '-': function(pos){return pos}
-, '<>':function(pos){return -Math.cos(pos * Math.PI) / 2 + 0.5}
-, '>': function(pos){return  Math.sin(pos * Math.PI / 2)}
-, '<': function(pos){return -Math.cos(pos * Math.PI / 2) + 1}
-}
-
-SVG.morph = function(pos){
-  return function(from, to) {
-    return new SVG.MorphObj(from, to).at(pos)
-  }
-}
-
-SVG.Situation = SVG.invent({
-
-  create: function(o){
-    this.init = false
-    this.reversed = false
-    this.reversing = false
-
-    this.duration = new SVG.Number(o.duration).valueOf()
-    this.delay = new SVG.Number(o.delay).valueOf()
-
-    this.start = +new Date() + this.delay
-    this.finish = this.start + this.duration
-    this.ease = o.ease
-
-    // this.loop is incremented from 0 to this.loops
-    // it is also incremented when in an infinite loop (when this.loops is true)
-    this.loop = 0
-    this.loops = false
-
-    this.animations = {
-      // functionToCall: [list of morphable objects]
-      // e.g. move: [SVG.Number, SVG.Number]
-    }
-
-    this.attrs = {
-      // holds all attributes which are not represented from a function svg.js provides
-      // e.g. someAttr: SVG.Number
-    }
-
-    this.styles = {
-      // holds all styles which should be animated
-      // e.g. fill-color: SVG.Color
-    }
-
-    this.transforms = [
-      // holds all transformations as transformation objects
-      // e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix]
-    ]
-
-    this.once = {
-      // functions to fire at a specific position
-      // e.g. "0.5": function foo(){}
-    }
-
-  }
-
-})
-
-
-SVG.FX = SVG.invent({
-
-  create: function(element) {
-    this._target = element
-    this.situations = []
-    this.active = false
-    this.situation = null
-    this.paused = false
-    this.lastPos = 0
-    this.pos = 0
-    // The absolute position of an animation is its position in the context of its complete duration (including delay and loops)
-    // When performing a delay, absPos is below 0 and when performing a loop, its value is above 1
-    this.absPos = 0
-    this._speed = 1
-  }
-
-, extend: {
-
-    /**
-     * sets or returns the target of this animation
-     * @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation
-     * @param ease function || string Function which should be used for easing or easing keyword
-     * @param delay Number indicating the delay before the animation starts
-     * @return target || this
-     */
-    animate: function(o, ease, delay){
-
-      if(typeof o == 'object'){
-        ease = o.ease
-        delay = o.delay
-        o = o.duration
-      }
-
-      var situation = new SVG.Situation({
-        duration: o || 1000,
-        delay: delay || 0,
-        ease: SVG.easing[ease || '-'] || ease
-      })
-
-      this.queue(situation)
-
-      return this
-    }
-
-    /**
-     * sets a delay before the next element of the queue is called
-     * @param delay Duration of delay in milliseconds
-     * @return this.target()
-     */
-  , delay: function(delay){
-      // The delay is performed by an empty situation with its duration
-      // attribute set to the duration of the delay
-      var situation = new SVG.Situation({
-        duration: delay,
-        delay: 0,
-        ease: SVG.easing['-']
-      })
-
-      return this.queue(situation)
-    }
-
-    /**
-     * sets or returns the target of this animation
-     * @param null || target SVG.Element which should be set as new target
-     * @return target || this
-     */
-  , target: function(target){
-      if(target && target instanceof SVG.Element){
-        this._target = target
-        return this
-      }
-
-      return this._target
-    }
-
-    // returns the absolute position at a given time
-  , timeToAbsPos: function(timestamp){
-      return (timestamp - this.situation.start) / (this.situation.duration/this._speed)
-    }
-
-    // returns the timestamp from a given absolute positon
-  , absPosToTime: function(absPos){
-      return this.situation.duration/this._speed * absPos + this.situation.start
-    }
-
-    // starts the animationloop
-  , startAnimFrame: function(){
-      this.stopAnimFrame()
-      this.animationFrame = window.requestAnimationFrame(function(){ this.step() }.bind(this))
-    }
-
-    // cancels the animationframe
-  , stopAnimFrame: function(){
-      window.cancelAnimationFrame(this.animationFrame)
-    }
-
-    // kicks off the animation - only does something when the queue is currently not active and at least one situation is set
-  , start: function(){
-      // dont start if already started
-      if(!this.active && this.situation){
-        this.active = true
-        this.startCurrent()
-      }
-
-      return this
-    }
-
-    // start the current situation
-  , startCurrent: function(){
-      this.situation.start = +new Date + this.situation.delay/this._speed
-      this.situation.finish = this.situation.start + this.situation.duration/this._speed
-      return this.initAnimations().step()
-    }
-
-    /**
-     * adds a function / Situation to the animation queue
-     * @param fn function / situation to add
-     * @return this
-     */
-  , queue: function(fn){
-      if(typeof fn == 'function' || fn instanceof SVG.Situation)
-        this.situations.push(fn)
-
-      if(!this.situation) this.situation = this.situations.shift()
-
-      return this
-    }
-
-    /**
-     * pulls next element from the queue and execute it
-     * @return this
-     */
-  , dequeue: function(){
-      // stop current animation
-      this.stop()
-
-      // get next animation from queue
-      this.situation = this.situations.shift()
-
-      if(this.situation){
-        if(this.situation instanceof SVG.Situation) {
-          this.start()
-        } else {
-          // If it is not a SVG.Situation, then it is a function, we execute it
-          this.situation.call(this)
-        }
-      }
-
-      return this
-    }
-
-    // updates all animations to the current state of the element
-    // this is important when one property could be changed from another property
-  , initAnimations: function() {
-      var i, j, source
-      var s = this.situation
-
-      if(s.init) return this
-
-      for(i in s.animations){
-        source = this.target()[i]()
-
-        if(!Array.isArray(source)) {
-          source = [source]
-        }
-
-        if(!Array.isArray(s.animations[i])) {
-          s.animations[i] = [s.animations[i]]
-        }
-
-        //if(s.animations[i].length > source.length) {
-        //  source.concat = source.concat(s.animations[i].slice(source.length, s.animations[i].length))
-        //}
-
-        for(j = source.length; j--;) {
-          // The condition is because some methods return a normal number instead
-          // of a SVG.Number
-          if(s.animations[i][j] instanceof SVG.Number)
-            source[j] = new SVG.Number(source[j])
-
-          s.animations[i][j] = source[j].morph(s.animations[i][j])
-        }
-      }
-
-      for(i in s.attrs){
-        s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i])
-      }
-
-      for(i in s.styles){
-        s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i])
-      }
-
-      s.initialTransformation = this.target().matrixify()
-
-      s.init = true
-      return this
-    }
-  , clearQueue: function(){
-      this.situations = []
-      return this
-    }
-  , clearCurrent: function(){
-      this.situation = null
-      return this
-    }
-    /** stops the animation immediately
-     * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately.
-     * @param clearQueue A Boolean indicating whether to remove queued animation as well.
-     * @return this
-     */
-  , stop: function(jumpToEnd, clearQueue){
-      var active = this.active
-      this.active = false
-
-      if(clearQueue){
-        this.clearQueue()
-      }
-
-      if(jumpToEnd && this.situation){
-        // initialize the situation if it was not
-        !active && this.startCurrent()
-        this.atEnd()
-      }
-
-      this.stopAnimFrame()
-
-      return this.clearCurrent()
-    }
-
-    /** resets the element to the state where the current element has started
-     * @return this
-     */
-  , reset: function(){
-      if(this.situation){
-        var temp = this.situation
-        this.stop()
-        this.situation = temp
-        this.atStart()
-      }
-      return this
-    }
-
-    // Stop the currently-running animation, remove all queued animations, and complete all animations for the element.
-  , finish: function(){
-
-      this.stop(true, false)
-
-      while(this.dequeue().situation && this.stop(true, false));
-
-      this.clearQueue().clearCurrent()
-
-      return this
-    }
-
-    // set the internal animation pointer at the start position, before any loops, and updates the visualisation
-  , atStart: function() {
-      return this.at(0, true)
-    }
-
-    // set the internal animation pointer at the end position, after all the loops, and updates the visualisation
-  , atEnd: function() {
-      if (this.situation.loops === true) {
-        // If in a infinite loop, we end the current iteration
-        this.situation.loops = this.situation.loop + 1
-      }
-
-      if(typeof this.situation.loops == 'number') {
-        // If performing a finite number of loops, we go after all the loops
-        return this.at(this.situation.loops, true)
-      } else {
-        // If no loops, we just go at the end
-        return this.at(1, true)
-      }
-    }
-
-    // set the internal animation pointer to the specified position and updates the visualisation
-    // if isAbsPos is true, pos is treated as an absolute position
-  , at: function(pos, isAbsPos){
-      var durDivSpd = this.situation.duration/this._speed
-
-      this.absPos = pos
-      // If pos is not an absolute position, we convert it into one
-      if (!isAbsPos) {
-        if (this.situation.reversed) this.absPos = 1 - this.absPos
-        this.absPos += this.situation.loop
-      }
-
-      this.situation.start = +new Date - this.absPos * durDivSpd
-      this.situation.finish = this.situation.start + durDivSpd
-
-      return this.step(true)
-    }
-
-    /**
-     * sets or returns the speed of the animations
-     * @param speed null || Number The new speed of the animations
-     * @return Number || this
-     */
-  , speed: function(speed){
-      if (speed === 0) return this.pause()
-
-      if (speed) {
-        this._speed = speed
-        // We use an absolute position here so that speed can affect the delay before the animation
-        return this.at(this.absPos, true)
-      } else return this._speed
-    }
-
-    // Make loopable
-  , loop: function(times, reverse) {
-      var c = this.last()
-
-      // store total loops
-      c.loops = (times != null) ? times : true
-      c.loop = 0
-
-      if(reverse) c.reversing = true
-      return this
-    }
-
-    // pauses the animation
-  , pause: function(){
-      this.paused = true
-      this.stopAnimFrame()
-
-      return this
-    }
-
-    // unpause the animation
-  , play: function(){
-      if(!this.paused) return this
-      this.paused = false
-      // We use an absolute position here so that the delay before the animation can be paused
-      return this.at(this.absPos, true)
-    }
-
-    /**
-     * toggle or set the direction of the animation
-     * true sets direction to backwards while false sets it to forwards
-     * @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status)
-     * @return this
-     */
-  , reverse: function(reversed){
-      var c = this.last()
-
-      if(typeof reversed == 'undefined') c.reversed = !c.reversed
-      else c.reversed = reversed
-
-      return this
-    }
-
-
-    /**
-     * returns a float from 0-1 indicating the progress of the current animation
-     * @param eased Boolean indicating whether the returned position should be eased or not
-     * @return number
-     */
-  , progress: function(easeIt){
-      return easeIt ? this.situation.ease(this.pos) : this.pos
-    }
-
-    /**
-     * adds a callback function which is called when the current animation is finished
-     * @param fn Function which should be executed as callback
-     * @return number
-     */
-  , after: function(fn){
-      var c = this.last()
-        , wrapper = function wrapper(e){
-            if(e.detail.situation == c){
-              fn.call(this, c)
-              this.off('finished.fx', wrapper) // prevent memory leak
-            }
-          }
-
-      this.target().on('finished.fx', wrapper)
-
-      return this._callStart()
-    }
-
-    // adds a callback which is called whenever one animation step is performed
-  , during: function(fn){
-      var c = this.last()
-        , wrapper = function(e){
-            if(e.detail.situation == c){
-              fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c)
-            }
-          }
-
-      // see above
-      this.target().off('during.fx', wrapper).on('during.fx', wrapper)
-
-      this.after(function(){
-        this.off('during.fx', wrapper)
-      })
-
-      return this._callStart()
-    }
-
-    // calls after ALL animations in the queue are finished
-  , afterAll: function(fn){
-      var wrapper = function wrapper(e){
-            fn.call(this)
-            this.off('allfinished.fx', wrapper)
-          }
-
-      // see above
-      this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper)
-
-      return this._callStart()
-    }
-
-    // calls on every animation step for all animations
-  , duringAll: function(fn){
-      var wrapper = function(e){
-            fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation)
-          }
-
-      this.target().off('during.fx', wrapper).on('during.fx', wrapper)
-
-      this.afterAll(function(){
-        this.off('during.fx', wrapper)
-      })
-
-      return this._callStart()
-    }
-
-  , last: function(){
-      return this.situations.length ? this.situations[this.situations.length-1] : this.situation
-    }
-
-    // adds one property to the animations
-  , add: function(method, args, type){
-      this.last()[type || 'animations'][method] = args
-      return this._callStart()
-    }
-
-    /** perform one step of the animation
-     *  @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time
-     *  @return this
-     */
-  , step: function(ignoreTime){
-
-      // convert current time to an absolute position
-      if(!ignoreTime) this.absPos = this.timeToAbsPos(+new Date)
-
-      // This part convert an absolute position to a position
-      if(this.situation.loops !== false) {
-        var absPos, absPosInt, lastLoop
-
-        // If the absolute position is below 0, we just treat it as if it was 0
-        absPos = Math.max(this.absPos, 0)
-        absPosInt = Math.floor(absPos)
-
-        if(this.situation.loops === true || absPosInt < this.situation.loops) {
-          this.pos = absPos - absPosInt
-          lastLoop = this.situation.loop
-          this.situation.loop = absPosInt
-        } else {
-          this.absPos = this.situation.loops
-          this.pos = 1
-          // The -1 here is because we don't want to toggle reversed when all the loops have been completed
-          lastLoop = this.situation.loop - 1
-          this.situation.loop = this.situation.loops
-        }
-
-        if(this.situation.reversing) {
-          // Toggle reversed if an odd number of loops as occured since the last call of step
-          this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2)
-        }
-
-      } else {
-        // If there are no loop, the absolute position must not be above 1
-        this.absPos = Math.min(this.absPos, 1)
-        this.pos = this.absPos
-      }
-
-      // while the absolute position can be below 0, the position must not be below 0
-      if(this.pos < 0) this.pos = 0
-
-      if(this.situation.reversed) this.pos = 1 - this.pos
-
-
-      // apply easing
-      var eased = this.situation.ease(this.pos)
-
-      // call once-callbacks
-      for(var i in this.situation.once){
-        if(i > this.lastPos && i <= eased){
-          this.situation.once[i].call(this.target(), this.pos, eased)
-          delete this.situation.once[i]
-        }
-      }
-
-      // fire during callback with position, eased position and current situation as parameter
-      if(this.active) this.target().fire('during', {pos: this.pos, eased: eased, fx: this, situation: this.situation})
-
-      // the user may call stop or finish in the during callback
-      // so make sure that we still have a valid situation
-      if(!this.situation){
-        return this
-      }
-
-      // apply the actual animation to every property
-      this.eachAt()
-
-      // do final code when situation is finished
-      if((this.pos == 1 && !this.situation.reversed) || (this.situation.reversed && this.pos == 0)){
-
-        // stop animation callback
-        this.stopAnimFrame()
-
-        // fire finished callback with current situation as parameter
-        this.target().fire('finished', {fx:this, situation: this.situation})
-
-        if(!this.situations.length){
-          this.target().fire('allfinished')
-
-          // Recheck the length since the user may call animate in the afterAll callback
-          if(!this.situations.length){
-            this.target().off('.fx') // there shouldnt be any binding left, but to make sure...
-            this.active = false
-          }
-        }
-
-        // start next animation
-        if(this.active) this.dequeue()
-        else this.clearCurrent()
-
-      }else if(!this.paused && this.active){
-        // we continue animating when we are not at the end
-        this.startAnimFrame()
-      }
-
-      // save last eased position for once callback triggering
-      this.lastPos = eased
-      return this
-
-    }
-
-    // calculates the step for every property and calls block with it
-  , eachAt: function(){
-      var i, len, at, self = this, target = this.target(), s = this.situation
-
-      // apply animations which can be called trough a method
-      for(i in s.animations){
-
-        at = [].concat(s.animations[i]).map(function(el){
-          return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
-        })
-
-        target[i].apply(target, at)
-
-      }
-
-      // apply animation which has to be applied with attr()
-      for(i in s.attrs){
-
-        at = [i].concat(s.attrs[i]).map(function(el){
-          return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
-        })
-
-        target.attr.apply(target, at)
-
-      }
-
-      // apply animation which has to be applied with style()
-      for(i in s.styles){
-
-        at = [i].concat(s.styles[i]).map(function(el){
-          return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
-        })
-
-        target.style.apply(target, at)
-
-      }
-
-      // animate initialTransformation which has to be chained
-      if(s.transforms.length){
-
-        // get initial initialTransformation
-        at = s.initialTransformation
-        for(i = 0, len = s.transforms.length; i < len; i++){
-
-          // get next transformation in chain
-          var a = s.transforms[i]
-
-          // multiply matrix directly
-          if(a instanceof SVG.Matrix){
-
-            if(a.relative){
-              at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos)))
-            }else{
-              at = at.morph(a).at(s.ease(this.pos))
-            }
-            continue
-          }
-
-          // when transformation is absolute we have to reset the needed transformation first
-          if(!a.relative)
-            a.undo(at.extract())
-
-          // and reapply it after
-          at = at.multiply(a.at(s.ease(this.pos)))
-
-        }
-
-        // set new matrix on element
-        target.matrix(at)
-      }
-
-      return this
-
-    }
-
-
-    // adds an once-callback which is called at a specific position and never again
-  , once: function(pos, fn, isEased){
-      var c = this.last()
-      if(!isEased) pos = c.ease(pos)
-
-      c.once[pos] = fn
-
-      return this
-    }
-
-  , _callStart: function() {
-      setTimeout(function(){this.start()}.bind(this), 0)
-      return this
-    }
-
-  }
-
-, parent: SVG.Element
-
-  // Add method to parent elements
-, construct: {
-    // Get fx module or create a new one, then animate with given duration and ease
-    animate: function(o, ease, delay) {
-      return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay)
-    }
-  , delay: function(delay){
-      return (this.fx || (this.fx = new SVG.FX(this))).delay(delay)
-    }
-  , stop: function(jumpToEnd, clearQueue) {
-      if (this.fx)
-        this.fx.stop(jumpToEnd, clearQueue)
-
-      return this
-    }
-  , finish: function() {
-      if (this.fx)
-        this.fx.finish()
-
-      return this
-    }
-    // Pause current animation
-  , pause: function() {
-      if (this.fx)
-        this.fx.pause()
-
-      return this
-    }
-    // Play paused current animation
-  , play: function() {
-      if (this.fx)
-        this.fx.play()
-
-      return this
-    }
-    // Set/Get the speed of the animations
-  , speed: function(speed) {
-      if (this.fx)
-        if (speed == null)
-          return this.fx.speed()
-        else
-          this.fx.speed(speed)
-
-      return this
-    }
-  }
-
-})
-
-// MorphObj is used whenever no morphable object is given
-SVG.MorphObj = SVG.invent({
-
-  create: function(from, to){
-    // prepare color for morphing
-    if(SVG.Color.isColor(to)) return new SVG.Color(from).morph(to)
-    // check if we have a list of values
-    if(SVG.regex.delimiter.test(from)) {
-      // prepare path for morphing
-      if(SVG.regex.pathLetters.test(from)) return new SVG.PathArray(from).morph(to)
-      // prepare value list for morphing
-      else return new SVG.Array(from).morph(to)
-    }
-    // prepare number for morphing
-    if(SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to)
-
-    // prepare for plain morphing
-    this.value = from
-    this.destination = to
-  }
-
-, extend: {
-    at: function(pos, real){
-      return real < 1 ? this.value : this.destination
-    },
-
-    valueOf: function(){
-      return this.value
-    }
-  }
-
-})
-
-SVG.extend(SVG.FX, {
-  // Add animatable attributes
-  attr: function(a, v, relative) {
-    // apply attributes individually
-    if (typeof a == 'object') {
-      for (var key in a)
-        this.attr(key, a[key])
-
-    } else {
-      this.add(a, v, 'attrs')
-    }
-
-    return this
-  }
-  // Add animatable styles
-, style: function(s, v) {
-    if (typeof s == 'object')
-      for (var key in s)
-        this.style(key, s[key])
-
-    else
-      this.add(s, v, 'styles')
-
-    return this
-  }
-  // Animatable x-axis
-, x: function(x, relative) {
-    if(this.target() instanceof SVG.G){
-      this.transform({x:x}, relative)
-      return this
-    }
-
-    var num = new SVG.Number(x)
-    num.relative = relative
-    return this.add('x', num)
-  }
-  // Animatable y-axis
-, y: function(y, relative) {
-    if(this.target() instanceof SVG.G){
-      this.transform({y:y}, relative)
-      return this
-    }
-
-    var num = new SVG.Number(y)
-    num.relative = relative
-    return this.add('y', num)
-  }
-  // Animatable center x-axis
-, cx: function(x) {
-    return this.add('cx', new SVG.Number(x))
-  }
-  // Animatable center y-axis
-, cy: function(y) {
-    return this.add('cy', new SVG.Number(y))
-  }
-  // Add animatable move
-, move: function(x, y) {
-    return this.x(x).y(y)
-  }
-  // Add animatable center
-, center: function(x, y) {
-    return this.cx(x).cy(y)
-  }
-  // Add animatable size
-, size: function(width, height) {
-    if (this.target() instanceof SVG.Text) {
-      // animate font size for Text elements
-      this.attr('font-size', width)
-
-    } else {
-      // animate bbox based size for all other elements
-      var box
-
-      if(!width || !height){
-        box = this.target().bbox()
-      }
-
-      if(!width){
-        width = box.width / box.height  * height
-      }
-
-      if(!height){
-        height = box.height / box.width  * width
-      }
-
-      this.add('width' , new SVG.Number(width))
-          .add('height', new SVG.Number(height))
-
-    }
-
-    return this
-  }
-  // Add animatable width
-, width: function(width) {
-    return this.add('width', new SVG.Number(width))
-  }
-  // Add animatable height
-, height: function(height) {
-    return this.add('height', new SVG.Number(height))
-  }
-  // Add animatable plot
-, plot: function(a, b, c, d) {
-    // Lines can be plotted with 4 arguments
-    if(arguments.length == 4) {
-      return this.plot([a, b, c, d])
-    }
-
-    return this.add('plot', new (this.target().morphArray)(a))
-  }
-  // Add leading method
-, leading: function(value) {
-    return this.target().leading ?
-      this.add('leading', new SVG.Number(value)) :
-      this
-  }
-  // Add animatable viewbox
-, viewbox: function(x, y, width, height) {
-    if (this.target() instanceof SVG.Container) {
-      this.add('viewbox', new SVG.ViewBox(x, y, width, height))
-    }
-
-    return this
-  }
-, update: function(o) {
-    if (this.target() instanceof SVG.Stop) {
-      if (typeof o == 'number' || o instanceof SVG.Number) {
-        return this.update({
-          offset:  arguments[0]
-        , color:   arguments[1]
-        , opacity: arguments[2]
-        })
-      }
-
-      if (o.opacity != null) this.attr('stop-opacity', o.opacity)
-      if (o.color   != null) this.attr('stop-color', o.color)
-      if (o.offset  != null) this.attr('offset', o.offset)
-    }
-
-    return this
-  }
-})
-
-SVG.Box = SVG.invent({
-  create: function(x, y, width, height) {
-    if (typeof x == 'object' && !(x instanceof SVG.Element)) {
-      // chromes getBoundingClientRect has no x and y property
-      return SVG.Box.call(this, x.left != null ? x.left : x.x , x.top != null ? x.top : x.y, x.width, x.height)
-    } else if (arguments.length == 4) {
-      this.x = x
-      this.y = y
-      this.width = width
-      this.height = height
-    }
-
-    // add center, right, bottom...
-    fullBox(this)
-  }
-, extend: {
-    // Merge rect box with another, return a new instance
-    merge: function(box) {
-      var b = new this.constructor()
-
-      // merge boxes
-      b.x      = Math.min(this.x, box.x)
-      b.y      = Math.min(this.y, box.y)
-      b.width  = Math.max(this.x + this.width,  box.x + box.width)  - b.x
-      b.height = Math.max(this.y + this.height, box.y + box.height) - b.y
-
-      return fullBox(b)
-    }
-
-  , transform: function(m) {
-      var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p, bbox
-
-      var pts = [
-        new SVG.Point(this.x, this.y),
-        new SVG.Point(this.x2, this.y),
-        new SVG.Point(this.x, this.y2),
-        new SVG.Point(this.x2, this.y2)
-      ]
-
-      pts.forEach(function(p) {
-        p = p.transform(m)
-        xMin = Math.min(xMin,p.x)
-        xMax = Math.max(xMax,p.x)
-        yMin = Math.min(yMin,p.y)
-        yMax = Math.max(yMax,p.y)
-      })
-
-      bbox = new this.constructor()
-      bbox.x = xMin
-      bbox.width = xMax-xMin
-      bbox.y = yMin
-      bbox.height = yMax-yMin
-
-      fullBox(bbox)
-
-      return bbox
-    }
-  }
-})
-
-SVG.BBox = SVG.invent({
-  // Initialize
-  create: function(element) {
-    SVG.Box.apply(this, [].slice.call(arguments))
-
-    // get values if element is given
-    if (element instanceof SVG.Element) {
-      var box
-
-      // yes this is ugly, but Firefox can be a pain when it comes to elements that are not yet rendered
-      try {
-
-        if (!document.documentElement.contains){
-          // This is IE - it does not support contains() for top-level SVGs
-          var topParent = element.node
-          while (topParent.parentNode){
-            topParent = topParent.parentNode
-          }
-          if (topParent != document) throw new Exception('Element not in the dom')
-        } else {
-          // the element is NOT in the dom, throw error
-          if(!document.documentElement.contains(element.node)) throw new Exception('Element not in the dom')
-        }
-
-        // find native bbox
-        box = element.node.getBBox()
-      } catch(e) {
-        if(element instanceof SVG.Shape){
-          var clone = element.clone(SVG.parser.draw.instance).show()
-          box = clone.node.getBBox()
-          clone.remove()
-        }else{
-          box = {
-            x:      element.node.clientLeft
-          , y:      element.node.clientTop
-          , width:  element.node.clientWidth
-          , height: element.node.clientHeight
-          }
-        }
-      }
-
-      SVG.Box.call(this, box)
-    }
-
-  }
-
-  // Define ancestor
-, inherit: SVG.Box
-
-  // Define Parent
-, parent: SVG.Element
-
-  // Constructor
-, construct: {
-    // Get bounding box
-    bbox: function() {
-      return new SVG.BBox(this)
-    }
-  }
-
-})
-
-SVG.BBox.prototype.constructor = SVG.BBox
-
-
-SVG.extend(SVG.Element, {
-  tbox: function(){
-    console.warn('Use of TBox is deprecated and mapped to RBox. Use .rbox() instead.')
-    return this.rbox(this.doc())
-  }
-})
-
-SVG.RBox = SVG.invent({
-  // Initialize
-  create: function(element) {
-    SVG.Box.apply(this, [].slice.call(arguments))
-
-    if (element instanceof SVG.Element) {
-      SVG.Box.call(this, element.node.getBoundingClientRect())
-    }
-  }
-
-, inherit: SVG.Box
-
-  // define Parent
-, parent: SVG.Element
-
-, extend: {
-    addOffset: function() {
-      // offset by window scroll position, because getBoundingClientRect changes when window is scrolled
-      this.x += window.pageXOffset
-      this.y += window.pageYOffset
-      return this
-    }
-  }
-
-  // Constructor
-, construct: {
-    // Get rect box
-    rbox: function(el) {
-      if (el) return new SVG.RBox(this).transform(el.screenCTM().inverse())
-      return new SVG.RBox(this).addOffset()
-    }
-  }
-
-})
-
-SVG.RBox.prototype.constructor = SVG.RBox
-
-SVG.Matrix = SVG.invent({
-  // Initialize
-  create: function(source) {
-    var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0])
-
-    // ensure source as object
-    source = source instanceof SVG.Element ?
-      source.matrixify() :
-    typeof source === 'string' ?
-      arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) :
-    arguments.length == 6 ?
-      arrayToMatrix([].slice.call(arguments)) :
-    Array.isArray(source) ?
-      arrayToMatrix(source) :
-    typeof source === 'object' ?
-      source : base
-
-    // merge source
-    for (i = abcdef.length - 1; i >= 0; --i)
-      this[abcdef[i]] = source[abcdef[i]] != null ?
-        source[abcdef[i]] : base[abcdef[i]]
-  }
-
-  // Add methods
-, extend: {
-    // Extract individual transformations
-    extract: function() {
-      // find delta transform points
-      var px    = deltaTransformPoint(this, 0, 1)
-        , py    = deltaTransformPoint(this, 1, 0)
-        , skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90
-
-      return {
-        // translation
-        x:        this.e
-      , y:        this.f
-      , transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b)
-      , transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d)
-        // skew
-      , skewX:    -skewX
-      , skewY:    180 / Math.PI * Math.atan2(py.y, py.x)
-        // scale
-      , scaleX:   Math.sqrt(this.a * this.a + this.b * this.b)
-      , scaleY:   Math.sqrt(this.c * this.c + this.d * this.d)
-        // rotation
-      , rotation: skewX
-      , a: this.a
-      , b: this.b
-      , c: this.c
-      , d: this.d
-      , e: this.e
-      , f: this.f
-      , matrix: new SVG.Matrix(this)
-      }
-    }
-    // Clone matrix
-  , clone: function() {
-      return new SVG.Matrix(this)
-    }
-    // Morph one matrix into another
-  , morph: function(matrix) {
-      // store new destination
-      this.destination = new SVG.Matrix(matrix)
-
-      return this
-    }
-    // Get morphed matrix at a given position
-  , at: function(pos) {
-      // make sure a destination is defined
-      if (!this.destination) return this
-
-      // calculate morphed matrix at a given position
-      var matrix = new SVG.Matrix({
-        a: this.a + (this.destination.a - this.a) * pos
-      , b: this.b + (this.destination.b - this.b) * pos
-      , c: this.c + (this.destination.c - this.c) * pos
-      , d: this.d + (this.destination.d - this.d) * pos
-      , e: this.e + (this.destination.e - this.e) * pos
-      , f: this.f + (this.destination.f - this.f) * pos
-      })
-
-      return matrix
-    }
-    // Multiplies by given matrix
-  , multiply: function(matrix) {
-      return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native()))
-    }
-    // Inverses matrix
-  , inverse: function() {
-      return new SVG.Matrix(this.native().inverse())
-    }
-    // Translate matrix
-  , translate: function(x, y) {
-      return new SVG.Matrix(this.native().translate(x || 0, y || 0))
-    }
-    // Scale matrix
-  , scale: function(x, y, cx, cy) {
-      // support uniformal scale
-      if (arguments.length == 1) {
-        y = x
-      } else if (arguments.length == 3) {
-        cy = cx
-        cx = y
-        y = x
-      }
-
-      return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0))
-    }
-    // Rotate matrix
-  , rotate: function(r, cx, cy) {
-      // convert degrees to radians
-      r = SVG.utils.radians(r)
-
-      return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0))
-    }
-    // Flip matrix on x or y, at a given offset
-  , flip: function(a, o) {
-      return a == 'x' ?
-          this.scale(-1, 1, o, 0) :
-        a == 'y' ?
-          this.scale(1, -1, 0, o) :
-          this.scale(-1, -1, a, o != null ? o : a)
-    }
-    // Skew
-  , skew: function(x, y, cx, cy) {
-      // support uniformal skew
-      if (arguments.length == 1) {
-        y = x
-      } else if (arguments.length == 3) {
-        cy = cx
-        cx = y
-        y = x
-      }
-
-      // convert degrees to radians
-      x = SVG.utils.radians(x)
-      y = SVG.utils.radians(y)
-
-      return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0))
-    }
-    // SkewX
-  , skewX: function(x, cx, cy) {
-      return this.skew(x, 0, cx, cy)
-    }
-    // SkewY
-  , skewY: function(y, cx, cy) {
-      return this.skew(0, y, cx, cy)
-    }
-    // Transform around a center point
-  , around: function(cx, cy, matrix) {
-      return this
-        .multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0))
-        .multiply(matrix)
-        .multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0))
-    }
-    // Convert to native SVGMatrix
-  , native: function() {
-      // create new matrix
-      var matrix = SVG.parser.native.createSVGMatrix()
-
-      // update with current values
-      for (var i = abcdef.length - 1; i >= 0; i--)
-        matrix[abcdef[i]] = this[abcdef[i]]
-
-      return matrix
-    }
-    // Convert matrix to string
-  , toString: function() {
-      // Construct the matrix directly, avoid values that are too small
-      return 'matrix(' + float32String(this.a) + ',' + float32String(this.b)
-        + ',' + float32String(this.c) + ',' + float32String(this.d)
-        + ',' + float32String(this.e) + ',' + float32String(this.f)
-        + ')'
-    }
-  }
-
-  // Define parent
-, parent: SVG.Element
-
-  // Add parent method
-, construct: {
-    // Get current matrix
-    ctm: function() {
-      return new SVG.Matrix(this.node.getCTM())
-    },
-    // Get current screen matrix
-    screenCTM: function() {
-      /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
-         This is needed because FF does not return the transformation matrix
-         for the inner coordinate system when getScreenCTM() is called on nested svgs.
-         However all other Browsers do that */
-      if(this instanceof SVG.Nested) {
-        var rect = this.rect(1,1)
-        var m = rect.node.getScreenCTM()
-        rect.remove()
-        return new SVG.Matrix(m)
-      }
-      return new SVG.Matrix(this.node.getScreenCTM())
-    }
-
-  }
-
-})
-
-SVG.Point = SVG.invent({
-  // Initialize
-  create: function(x,y) {
-    var i, source, base = {x:0, y:0}
-
-    // ensure source as object
-    source = Array.isArray(x) ?
-      {x:x[0], y:x[1]} :
-    typeof x === 'object' ?
-      {x:x.x, y:x.y} :
-    x != null ?
-      {x:x, y:(y != null ? y : x)} : base // If y has no value, then x is used has its value
-
-    // merge source
-    this.x = source.x
-    this.y = source.y
-  }
-
-  // Add methods
-, extend: {
-    // Clone point
-    clone: function() {
-      return new SVG.Point(this)
-    }
-    // Morph one point into another
-  , morph: function(x, y) {
-      // store new destination
-      this.destination = new SVG.Point(x, y)
-
-      return this
-    }
-    // Get morphed point at a given position
-  , at: function(pos) {
-      // make sure a destination is defined
-      if (!this.destination) return this
-
-      // calculate morphed matrix at a given position
-      var point = new SVG.Point({
-        x: this.x + (this.destination.x - this.x) * pos
-      , y: this.y + (this.destination.y - this.y) * pos
-      })
-
-      return point
-    }
-    // Convert to native SVGPoint
-  , native: function() {
-      // create new point
-      var point = SVG.parser.native.createSVGPoint()
-
-      // update with current values
-      point.x = this.x
-      point.y = this.y
-
-      return point
-    }
-    // transform point with matrix
-  , transform: function(matrix) {
-      return new SVG.Point(this.native().matrixTransform(matrix.native()))
-    }
-
-  }
-
-})
-
-SVG.extend(SVG.Element, {
-
-  // Get point
-  point: function(x, y) {
-    return new SVG.Point(x,y).transform(this.screenCTM().inverse());
-  }
-
-})
-
-SVG.extend(SVG.Element, {
-  // Set svg element attribute
-  attr: function(a, v, n) {
-    // act as full getter
-    if (a == null) {
-      // get an object of attributes
-      a = {}
-      v = this.node.attributes
-      for (n = v.length - 1; n >= 0; n--)
-        a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue
-
-      return a
-
-    } else if (typeof a == 'object') {
-      // apply every attribute individually if an object is passed
-      for (v in a) this.attr(v, a[v])
-
-    } else if (v === null) {
-        // remove value
-        this.node.removeAttribute(a)
-
-    } else if (v == null) {
-      // act as a getter if the first and only argument is not an object
-      v = this.node.getAttribute(a)
-      return v == null ?
-        SVG.defaults.attrs[a] :
-      SVG.regex.isNumber.test(v) ?
-        parseFloat(v) : v
-
-    } else {
-      // BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0
-      if (a == 'stroke-width')
-        this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null)
-      else if (a == 'stroke')
-        this._stroke = v
-
-      // convert image fill and stroke to patterns
-      if (a == 'fill' || a == 'stroke') {
-        if (SVG.regex.isImage.test(v))
-          v = this.doc().defs().image(v, 0, 0)
-
-        if (v instanceof SVG.Image)
-          v = this.doc().defs().pattern(0, 0, function() {
-            this.add(v)
-          })
-      }
-
-      // ensure correct numeric values (also accepts NaN and Infinity)
-      if (typeof v === 'number')
-        v = new SVG.Number(v)
-
-      // ensure full hex color
-      else if (SVG.Color.isColor(v))
-        v = new SVG.Color(v)
-
-      // parse array values
-      else if (Array.isArray(v))
-        v = new SVG.Array(v)
-
-      // if the passed attribute is leading...
-      if (a == 'leading') {
-        // ... call the leading method instead
-        if (this.leading)
-          this.leading(v)
-      } else {
-        // set given attribute on node
-        typeof n === 'string' ?
-          this.node.setAttributeNS(n, a, v.toString()) :
-          this.node.setAttribute(a, v.toString())
-      }
-
-      // rebuild if required
-      if (this.rebuild && (a == 'font-size' || a == 'x'))
-        this.rebuild(a, v)
-    }
-
-    return this
-  }
-})
-SVG.extend(SVG.Element, {
-  // Add transformations
-  transform: function(o, relative) {
-    // get target in case of the fx module, otherwise reference this
-    var target = this
-      , matrix, bbox
-
-    // act as a getter
-    if (typeof o !== 'object') {
-      // get current matrix
-      matrix = new SVG.Matrix(target).extract()
-
-      return typeof o === 'string' ? matrix[o] : matrix
-    }
-
-    // get current matrix
-    matrix = new SVG.Matrix(target)
-
-    // ensure relative flag
-    relative = !!relative || !!o.relative
-
-    // act on matrix
-    if (o.a != null) {
-      matrix = relative ?
-        // relative
-        matrix.multiply(new SVG.Matrix(o)) :
-        // absolute
-        new SVG.Matrix(o)
-
-    // act on rotation
-    } else if (o.rotation != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // apply transformation
-      matrix = relative ?
-        // relative
-        matrix.rotate(o.rotation, o.cx, o.cy) :
-        // absolute
-        matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy)
-
-    // act on scale
-    } else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // ensure scale values on both axes
-      o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
-      o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
-
-      if (!relative) {
-        // absolute; multiply inversed values
-        var e = matrix.extract()
-        o.scaleX = o.scaleX * 1 / e.scaleX
-        o.scaleY = o.scaleY * 1 / e.scaleY
-      }
-
-      matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy)
-
-    // act on skew
-    } else if (o.skew != null || o.skewX != null || o.skewY != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // ensure skew values on both axes
-      o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0
-      o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0
-
-      if (!relative) {
-        // absolute; reset skew values
-        var e = matrix.extract()
-        matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse())
-      }
-
-      matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy)
-
-    // act on flip
-    } else if (o.flip) {
-      if(o.flip == 'x' || o.flip == 'y') {
-        o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
-      } else {
-        if(o.offset == null) {
-          bbox = target.bbox()
-          o.flip = bbox.cx
-          o.offset = bbox.cy
-        } else {
-          o.flip = o.offset
-        }
-      }
-
-      matrix = new SVG.Matrix().flip(o.flip, o.offset)
-
-    // act on translate
-    } else if (o.x != null || o.y != null) {
-      if (relative) {
-        // relative
-        matrix = matrix.translate(o.x, o.y)
-      } else {
-        // absolute
-        if (o.x != null) matrix.e = o.x
-        if (o.y != null) matrix.f = o.y
-      }
-    }
-
-    return this.attr('transform', matrix)
-  }
-})
-
-SVG.extend(SVG.FX, {
-  transform: function(o, relative) {
-    // get target in case of the fx module, otherwise reference this
-    var target = this.target()
-      , matrix, bbox
-
-    // act as a getter
-    if (typeof o !== 'object') {
-      // get current matrix
-      matrix = new SVG.Matrix(target).extract()
-
-      return typeof o === 'string' ? matrix[o] : matrix
-    }
-
-    // ensure relative flag
-    relative = !!relative || !!o.relative
-
-    // act on matrix
-    if (o.a != null) {
-      matrix = new SVG.Matrix(o)
-
-    // act on rotation
-    } else if (o.rotation != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // apply transformation
-      matrix = new SVG.Rotate(o.rotation, o.cx, o.cy)
-
-    // act on scale
-    } else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // ensure scale values on both axes
-      o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
-      o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
-
-      matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy)
-
-    // act on skew
-    } else if (o.skewX != null || o.skewY != null) {
-      // ensure centre point
-      ensureCentre(o, target)
-
-      // ensure skew values on both axes
-      o.skewX = o.skewX != null ? o.skewX : 0
-      o.skewY = o.skewY != null ? o.skewY : 0
-
-      matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy)
-
-    // act on flip
-    } else if (o.flip) {
-      if(o.flip == 'x' || o.flip == 'y') {
-        o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
-      } else {
-        if(o.offset == null) {
-          bbox = target.bbox()
-          o.flip = bbox.cx
-          o.offset = bbox.cy
-        } else {
-          o.flip = o.offset
-        }
-      }
-
-      matrix = new SVG.Matrix().flip(o.flip, o.offset)
-
-    // act on translate
-    } else if (o.x != null || o.y != null) {
-      matrix = new SVG.Translate(o.x, o.y)
-    }
-
-    if(!matrix) return this
-
-    matrix.relative = relative
-
-    this.last().transforms.push(matrix)
-
-    return this._callStart()
-  }
-})
-
-SVG.extend(SVG.Element, {
-  // Reset all transformations
-  untransform: function() {
-    return this.attr('transform', null)
-  },
-  // merge the whole transformation chain into one matrix and returns it
-  matrixify: function() {
-
-    var matrix = (this.attr('transform') || '')
-      // split transformations
-      .split(SVG.regex.transforms).slice(0,-1).map(function(str){
-        // generate key => value pairs
-        var kv = str.trim().split('(')
-        return [kv[0], kv[1].split(SVG.regex.delimiter).map(function(str){ return parseFloat(str) })]
-      })
-      // merge every transformation into one matrix
-      .reduce(function(matrix, transform){
-
-        if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1]))
-        return matrix[transform[0]].apply(matrix, transform[1])
-
-      }, new SVG.Matrix())
-
-    return matrix
-  },
-  // add an element to another parent without changing the visual representation on the screen
-  toParent: function(parent) {
-    if(this == parent) return this
-    var ctm = this.screenCTM()
-    var pCtm = parent.screenCTM().inverse()
-
-    this.addTo(parent).untransform().transform(pCtm.multiply(ctm))
-
-    return this
-  },
-  // same as above with parent equals root-svg
-  toDoc: function() {
-    return this.toParent(this.doc())
-  }
-
-})
-
-SVG.Transformation = SVG.invent({
-
-  create: function(source, inversed){
-
-    if(arguments.length > 1 && typeof inversed != 'boolean'){
-      return this.constructor.call(this, [].slice.call(arguments))
-    }
-
-    if(Array.isArray(source)){
-      for(var i = 0, len = this.arguments.length; i < len; ++i){
-        this[this.arguments[i]] = source[i]
-      }
-    } else if(typeof source == 'object'){
-      for(var i = 0, len = this.arguments.length; i < len; ++i){
-        this[this.arguments[i]] = source[this.arguments[i]]
-      }
-    }
-
-    this.inversed = false
-
-    if(inversed === true){
-      this.inversed = true
-    }
-
-  }
-
-, extend: {
-
-    arguments: []
-  , method: ''
-
-  , at: function(pos){
-
-      var params = []
-
-      for(var i = 0, len = this.arguments.length; i < len; ++i){
-        params.push(this[this.arguments[i]])
-      }
-
-      var m = this._undo || new SVG.Matrix()
-
-      m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos)
-
-      return this.inversed ? m.inverse() : m
-
-    }
-
-  , undo: function(o){
-      for(var i = 0, len = this.arguments.length; i < len; ++i){
-        o[this.arguments[i]] = typeof this[this.arguments[i]] == 'undefined' ? 0 : o[this.arguments[i]]
-      }
-
-      // The method SVG.Matrix.extract which was used before calling this
-      // method to obtain a value for the parameter o doesn't return a cx and
-      // a cy so we use the ones that were provided to this object at its creation
-      o.cx = this.cx
-      o.cy = this.cy
-
-      this._undo = new SVG[capitalize(this.method)](o, true).at(1)
-
-      return this
-    }
-
-  }
-
-})
-
-SVG.Translate = SVG.invent({
-
-  parent: SVG.Matrix
-, inherit: SVG.Transformation
-
-, create: function(source, inversed){
-    this.constructor.apply(this, [].slice.call(arguments))
-  }
-
-, extend: {
-    arguments: ['transformedX', 'transformedY']
-  , method: 'translate'
-  }
-
-})
-
-SVG.Rotate = SVG.invent({
-
-  parent: SVG.Matrix
-, inherit: SVG.Transformation
-
-, create: function(source, inversed){
-    this.constructor.apply(this, [].slice.call(arguments))
-  }
-
-, extend: {
-    arguments: ['rotation', 'cx', 'cy']
-  , method: 'rotate'
-  , at: function(pos){
-      var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy)
-      return this.inversed ? m.inverse() : m
-    }
-  , undo: function(o){
-      this._undo = o
-      return this
-    }
-  }
-
-})
-
-SVG.Scale = SVG.invent({
-
-  parent: SVG.Matrix
-, inherit: SVG.Transformation
-
-, create: function(source, inversed){
-    this.constructor.apply(this, [].slice.call(arguments))
-  }
-
-, extend: {
-    arguments: ['scaleX', 'scaleY', 'cx', 'cy']
-  , method: 'scale'
-  }
-
-})
-
-SVG.Skew = SVG.invent({
-
-  parent: SVG.Matrix
-, inherit: SVG.Transformation
-
-, create: function(source, inversed){
-    this.constructor.apply(this, [].slice.call(arguments))
-  }
-
-, extend: {
-    arguments: ['skewX', 'skewY', 'cx', 'cy']
-  , method: 'skew'
-  }
-
-})
-
-SVG.extend(SVG.Element, {
-  // Dynamic style generator
-  style: function(s, v) {
-    if (arguments.length == 0) {
-      // get full style
-      return this.node.style.cssText || ''
-
-    } else if (arguments.length < 2) {
-      // apply every style individually if an object is passed
-      if (typeof s == 'object') {
-        for (v in s) this.style(v, s[v])
-
-      } else if (SVG.regex.isCss.test(s)) {
-        // parse css string
-        s = s.split(/\s*;\s*/)
-          // filter out suffix ; and stuff like ;;
-          .filter(function(e) { return !!e })
-          .map(function(e){ return e.split(/\s*:\s*/) })
-
-        // apply every definition individually
-        while (v = s.pop()) {
-          this.style(v[0], v[1])
-        }
-      } else {
-        // act as a getter if the first and only argument is not an object
-        return this.node.style[camelCase(s)]
-      }
-
-    } else {
-      this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v
-    }
-
-    return this
-  }
-})
-SVG.Parent = SVG.invent({
-  // Initialize node
-  create: function(element) {
-    this.constructor.call(this, element)
-  }
-
-  // Inherit from
-, inherit: SVG.Element
-
-  // Add class methods
-, extend: {
-    // Returns all child elements
-    children: function() {
-      return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) {
-        return SVG.adopt(node)
-      })
-    }
-    // Add given element at a position
-  , add: function(element, i) {
-      if (i == null)
-        this.node.appendChild(element.node)
-      else if (element.node != this.node.childNodes[i])
-        this.node.insertBefore(element.node, this.node.childNodes[i])
-
-      return this
-    }
-    // Basically does the same as `add()` but returns the added element instead
-  , put: function(element, i) {
-      this.add(element, i)
-      return element
-    }
-    // Checks if the given element is a child
-  , has: function(element) {
-      return this.index(element) >= 0
-    }
-    // Gets index of given element
-  , index: function(element) {
-      return [].slice.call(this.node.childNodes).indexOf(element.node)
-    }
-    // Get a element at the given index
-  , get: function(i) {
-      return SVG.adopt(this.node.childNodes[i])
-    }
-    // Get first child
-  , first: function() {
-      return this.get(0)
-    }
-    // Get the last child
-  , last: function() {
-      return this.get(this.node.childNodes.length - 1)
-    }
-    // Iterates over all children and invokes a given block
-  , each: function(block, deep) {
-      var i, il
-        , children = this.children()
-
-      for (i = 0, il = children.length; i < il; i++) {
-        if (children[i] instanceof SVG.Element)
-          block.apply(children[i], [i, children])
-
-        if (deep && (children[i] instanceof SVG.Container))
-          children[i].each(block, deep)
-      }
-
-      return this
-    }
-    // Remove a given child
-  , removeElement: function(element) {
-      this.node.removeChild(element.node)
-
-      return this
-    }
-    // Remove all elements in this container
-  , clear: function() {
-      // remove children
-      while(this.node.hasChildNodes())
-        this.node.removeChild(this.node.lastChild)
-
-      // remove defs reference
-      delete this._defs
-
-      return this
-    }
-  , // Get defs
-    defs: function() {
-      return this.doc().defs()
-    }
-  }
-
-})
-
-SVG.extend(SVG.Parent, {
-
-  ungroup: function(parent, depth) {
-    if(depth === 0 || this instanceof SVG.Defs || this.node == SVG.parser.draw) return this
-
-    parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent))
-    depth = depth || Infinity
-
-    this.each(function(){
-      if(this instanceof SVG.Defs) return this
-      if(this instanceof SVG.Parent) return this.ungroup(parent, depth-1)
-      return this.toParent(parent)
-    })
-
-    this.node.firstChild || this.remove()
-
-    return this
-  },
-
-  flatten: function(parent, depth) {
-    return this.ungroup(parent, depth)
-  }
-
-})
-SVG.Container = SVG.invent({
-  // Initialize node
-  create: function(element) {
-    this.constructor.call(this, element)
-  }
-
-  // Inherit from
-, inherit: SVG.Parent
-
-})
-
-SVG.ViewBox = SVG.invent({
-
-  create: function(source) {
-    var i, base = [0, 0, 0, 0]
-
-    var x, y, width, height, box, view, we, he
-      , wm   = 1 // width multiplier
-      , hm   = 1 // height multiplier
-      , reg  = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/gi
-
-    if(source instanceof SVG.Element){
-
-      we = source
-      he = source
-      view = (source.attr('viewBox') || '').match(reg)
-      box = source.bbox
-
-      // get dimensions of current node
-      width  = new SVG.Number(source.width())
-      height = new SVG.Number(source.height())
-
-      // find nearest non-percentual dimensions
-      while (width.unit == '%') {
-        wm *= width.value
-        width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width())
-        we = we.parent()
-      }
-      while (height.unit == '%') {
-        hm *= height.value
-        height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height())
-        he = he.parent()
-      }
-
-      // ensure defaults
-      this.x      = 0
-      this.y      = 0
-      this.width  = width  * wm
-      this.height = height * hm
-      this.zoom   = 1
-
-      if (view) {
-        // get width and height from viewbox
-        x      = parseFloat(view[0])
-        y      = parseFloat(view[1])
-        width  = parseFloat(view[2])
-        height = parseFloat(view[3])
-
-        // calculate zoom accoring to viewbox
-        this.zoom = ((this.width / this.height) > (width / height)) ?
-          this.height / height :
-          this.width  / width
-
-        // calculate real pixel dimensions on parent SVG.Doc element
-        this.x      = x
-        this.y      = y
-        this.width  = width
-        this.height = height
-
-      }
-
-    }else{
-
-      // ensure source as object
-      source = typeof source === 'string' ?
-        source.match(reg).map(function(el){ return parseFloat(el) }) :
-      Array.isArray(source) ?
-        source :
-      typeof source == 'object' ?
-        [source.x, source.y, source.width, source.height] :
-      arguments.length == 4 ?
-        [].slice.call(arguments) :
-        base
-
-      this.x = source[0]
-      this.y = source[1]
-      this.width = source[2]
-      this.height = source[3]
-    }
-
-
-  }
-
-, extend: {
-
-    toString: function() {
-      return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height
-    }
-  , morph: function(x, y, width, height){
-      this.destination = new SVG.ViewBox(x, y, width, height)
-      return this
-    }
-
-  , at: function(pos) {
-
-      if(!this.destination) return this
-
-      return new SVG.ViewBox([
-          this.x + (this.destination.x - this.x) * pos
-        , this.y + (this.destination.y - this.y) * pos
-        , this.width + (this.destination.width - this.width) * pos
-        , this.height + (this.destination.height - this.height) * pos
-      ])
-
-    }
-
-  }
-
-  // Define parent
-, parent: SVG.Container
-
-  // Add parent method
-, construct: {
-
-    // get/set viewbox
-    viewbox: function(x, y, width, height) {
-      if (arguments.length == 0)
-        // act as a getter if there are no arguments
-        return new SVG.ViewBox(this)
-
-      // otherwise act as a setter
-      return this.attr('viewBox', new SVG.ViewBox(x, y, width, height))
-    }
-
-  }
-
-})
-// Add events to elements
-
-;[ 'click',
-  'dblclick',
-  'mousedown',
-  'mouseup',
-  'mouseover',
-  'mouseout',
-  'mousemove',
-  'mouseenter',
-  'mouseleave',
-  'touchstart',
-  'touchmove',
-  'touchleave',
-  'touchend',
-  'touchcancel' ].forEach(function (event) {
-    // add event to SVG.Element
-    SVG.Element.prototype[event] = function (f) {
-      // bind event to element rather than element node
-      if (f == null) {
-        SVG.off(this, event)
-      } else {
-        SVG.on(this, event, f)
-      }
-      return this
-    }
-  })
-
-SVG.listenerId = 0
-
-// Add event binder in the SVG namespace
-SVG.on = function (node, events, listener, binding, options) {
-  var l = listener.bind(binding || node)
-  var n = node instanceof SVG.Element ? node.node : node
-
-  // ensure instance object for nodes which are not adopted
-  n.instance = n.instance || {_events: {}}
-
-  var bag = n.instance._events
-
-  // add id to listener
-  if (!listener._svgjsListenerId) { listener._svgjsListenerId = ++SVG.listenerId }
-
-  events.split(SVG.regex.delimiter).forEach(function (event) {
-    var ev = event.split('.')[0]
-    var ns = event.split('.')[1] || '*'
-
-    // ensure valid object
-    bag[ev] = bag[ev] || {}
-    bag[ev][ns] = bag[ev][ns] || {}
-
-    // reference listener
-    bag[ev][ns][listener._svgjsListenerId] = l
-
-    // add listener
-    n.addEventListener(ev, l, options || false)
-  })
-}
-
-// Add event unbinder in the SVG namespace
-SVG.off = function (node, events, listener, options) {
-  var n = node instanceof SVG.Element ? node.node : node
-  if (!n.instance) return
-
-  // listener can be a function or a number
-  if (typeof listener === 'function') {
-    listener = listener._svgjsListenerId
-    if (!listener) return
-  }
-
-  var bag = n.instance._events
-
-  ;(events || '').split(SVG.regex.delimiter).forEach(function (event) {
-    var ev = event && event.split('.')[0]
-    var ns = event && event.split('.')[1]
-    var namespace, l
-
-    if (listener) {
-      // remove listener reference
-      if (bag[ev] && bag[ev][ns || '*']) {
-        // removeListener
-        n.removeEventListener(ev, bag[ev][ns || '*'][listener], options || false)
-
-        delete bag[ev][ns || '*'][listener]
-      }
-    } else if (ev && ns) {
-      // remove all listeners for a namespaced event
-      if (bag[ev] && bag[ev][ns]) {
-        for (l in bag[ev][ns]) { SVG.off(n, [ev, ns].join('.'), l) }
-
-        delete bag[ev][ns]
-      }
-    } else if (ns) {
-      // remove all listeners for a specific namespace
-      for (event in bag) {
-        for (namespace in bag[event]) {
-          if (ns === namespace) { SVG.off(n, [event, ns].join('.')) }
-        }
-      }
-    } else if (ev) {
-      // remove all listeners for the event
-      if (bag[ev]) {
-        for (namespace in bag[ev]) { SVG.off(n, [ev, namespace].join('.')) }
-
-        delete bag[ev]
-      }
-    } else {
-      // remove all listeners on a given node
-      for (event in bag) { SVG.off(n, event) }
-
-      n.instance._events = {}
-    }
-  })
-}
-
-SVG.extend(SVG.Element, {
-  // Bind given event to listener
-  on: function (event, listener, binding, options) {
-    SVG.on(this, event, listener, binding, options)
-    return this
-  },
-  // Unbind event from listener
-  off: function (event, listener) {
-    SVG.off(this.node, event, listener)
-    return this
-  },
-  fire: function (event, data) {
-    // Dispatch event
-    if (event instanceof window.Event) {
-      this.node.dispatchEvent(event)
-    } else {
-      this.node.dispatchEvent(event = new SVG.CustomEvent(event, {detail: data, cancelable: true}))
-    }
-    this._event = event
-    return this
-  },
-  event: function() {
-    return this._event
-  }
-})
-
-
-SVG.Defs = SVG.invent({
-  // Initialize node
-  create: 'defs'
-
-  // Inherit from
-, inherit: SVG.Container
-
-})
-SVG.G = SVG.invent({
-  // Initialize node
-  create: 'g'
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Move over x-axis
-    x: function(x) {
-      return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true)
-    }
-    // Move over y-axis
-  , y: function(y) {
-      return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true)
-    }
-    // Move by center over x-axis
-  , cx: function(x) {
-      return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2)
-    }
-    // Move by center over y-axis
-  , cy: function(y) {
-      return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2)
-    }
-  , gbox: function() {
-
-      var bbox  = this.bbox()
-        , trans = this.transform()
-
-      bbox.x  += trans.x
-      bbox.x2 += trans.x
-      bbox.cx += trans.x
-
-      bbox.y  += trans.y
-      bbox.y2 += trans.y
-      bbox.cy += trans.y
-
-      return bbox
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create a group element
-    group: function() {
-      return this.put(new SVG.G)
-    }
-  }
-})
-
-SVG.Doc = SVG.invent({
-  // Initialize node
-  create: function(element) {
-    if (element) {
-      // ensure the presence of a dom element
-      element = typeof element == 'string' ?
-        document.getElementById(element) :
-        element
-
-      // If the target is an svg element, use that element as the main wrapper.
-      // This allows svg.js to work with svg documents as well.
-      if (element.nodeName == 'svg') {
-        this.constructor.call(this, element)
-      } else {
-        this.constructor.call(this, SVG.create('svg'))
-        element.appendChild(this.node)
-        this.size('100%', '100%')
-      }
-
-      // set svg element attributes and ensure defs node
-      this.namespace().defs()
-    }
-  }
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Add namespaces
-    namespace: function() {
-      return this
-        .attr({ xmlns: SVG.ns, version: '1.1' })
-        .attr('xmlns:xlink', SVG.xlink, SVG.xmlns)
-        .attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns)
-    }
-    // Creates and returns defs element
-  , defs: function() {
-      if (!this._defs) {
-        var defs
-
-        // Find or create a defs element in this instance
-        if (defs = this.node.getElementsByTagName('defs')[0])
-          this._defs = SVG.adopt(defs)
-        else
-          this._defs = new SVG.Defs
-
-        // Make sure the defs node is at the end of the stack
-        this.node.appendChild(this._defs.node)
-      }
-
-      return this._defs
-    }
-    // custom parent method
-  , parent: function() {
-      if(!this.node.parentNode || this.node.parentNode.nodeName == '#document' || this.node.parentNode.nodeName == '#document-fragment') return null
-      return this.node.parentNode
-    }
-    // Fix for possible sub-pixel offset. See:
-    // https://bugzilla.mozilla.org/show_bug.cgi?id=608812
-  , spof: function() {
-      var pos = this.node.getScreenCTM()
-
-      if (pos)
-        this
-          .style('left', (-pos.e % 1) + 'px')
-          .style('top',  (-pos.f % 1) + 'px')
-
-      return this
-    }
-
-      // Removes the doc from the DOM
-  , remove: function() {
-      if(this.parent()) {
-        this.parent().removeChild(this.node)
-      }
-
-      return this
-    }
-  , clear: function() {
-      // remove children
-      while(this.node.hasChildNodes())
-        this.node.removeChild(this.node.lastChild)
-
-      // remove defs reference
-      delete this._defs
-
-      // add back parser
-      if(!SVG.parser.draw.parentNode)
-        this.node.appendChild(SVG.parser.draw)
-
-      return this
-    }
-  , clone: function (parent) {
-      // write dom data to the dom so the clone can pickup the data
-      this.writeDataToDom()
-
-      // get reference to node
-      var node = this.node
-
-      // clone element and assign new id
-      var clone = assignNewId(node.cloneNode(true))
-
-      // insert the clone in the given parent or after myself
-      if(parent) {
-        (parent.node || parent).appendChild(clone.node)
-      } else {
-        node.parentNode.insertBefore(clone.node, node.nextSibling)
-      }
-
-      return clone
-    }
-  }
-
-})
-
-// ### This module adds backward / forward functionality to elements.
-
-//
-SVG.extend(SVG.Element, {
-  // Get all siblings, including myself
-  siblings: function() {
-    return this.parent().children()
-  }
-  // Get the curent position siblings
-, position: function() {
-    return this.parent().index(this)
-  }
-  // Get the next element (will return null if there is none)
-, next: function() {
-    return this.siblings()[this.position() + 1]
-  }
-  // Get the next element (will return null if there is none)
-, previous: function() {
-    return this.siblings()[this.position() - 1]
-  }
-  // Send given element one step forward
-, forward: function() {
-    var i = this.position() + 1
-      , p = this.parent()
-
-    // move node one step forward
-    p.removeElement(this).add(this, i)
-
-    // make sure defs node is always at the top
-    if (p instanceof SVG.Doc)
-      p.node.appendChild(p.defs().node)
-
-    return this
-  }
-  // Send given element one step backward
-, backward: function() {
-    var i = this.position()
-
-    if (i > 0)
-      this.parent().removeElement(this).add(this, i - 1)
-
-    return this
-  }
-  // Send given element all the way to the front
-, front: function() {
-    var p = this.parent()
-
-    // Move node forward
-    p.node.appendChild(this.node)
-
-    // Make sure defs node is always at the top
-    if (p instanceof SVG.Doc)
-      p.node.appendChild(p.defs().node)
-
-    return this
-  }
-  // Send given element all the way to the back
-, back: function() {
-    if (this.position() > 0)
-      this.parent().removeElement(this).add(this, 0)
-
-    return this
-  }
-  // Inserts a given element before the targeted element
-, before: function(element) {
-    element.remove()
-
-    var i = this.position()
-
-    this.parent().add(element, i)
-
-    return this
-  }
-  // Insters a given element after the targeted element
-, after: function(element) {
-    element.remove()
-
-    var i = this.position()
-
-    this.parent().add(element, i + 1)
-
-    return this
-  }
-
-})
-SVG.Mask = SVG.invent({
-  // Initialize node
-  create: function() {
-    this.constructor.call(this, SVG.create('mask'))
-
-    // keep references to masked elements
-    this.targets = []
-  }
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Unmask all masked elements and remove itself
-    remove: function() {
-      // unmask all targets
-      for (var i = this.targets.length - 1; i >= 0; i--)
-        if (this.targets[i])
-          this.targets[i].unmask()
-      this.targets = []
-
-      // remove mask from parent
-      SVG.Element.prototype.remove.call(this)
-
-      return this
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create masking element
-    mask: function() {
-      return this.defs().put(new SVG.Mask)
-    }
-  }
-})
-
-
-SVG.extend(SVG.Element, {
-  // Distribute mask to svg element
-  maskWith: function(element) {
-    // use given mask or create a new one
-    this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element)
-
-    // store reverence on self in mask
-    this.masker.targets.push(this)
-
-    // apply mask
-    return this.attr('mask', 'url("#' + this.masker.attr('id') + '")')
-  }
-  // Unmask element
-, unmask: function() {
-    delete this.masker
-    return this.attr('mask', null)
-  }
-
-})
-
-SVG.ClipPath = SVG.invent({
-  // Initialize node
-  create: function() {
-    this.constructor.call(this, SVG.create('clipPath'))
-
-    // keep references to clipped elements
-    this.targets = []
-  }
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Unclip all clipped elements and remove itself
-    remove: function() {
-      // unclip all targets
-      for (var i = this.targets.length - 1; i >= 0; i--)
-        if (this.targets[i])
-          this.targets[i].unclip()
-      this.targets = []
-
-      // remove clipPath from parent
-      this.parent().removeElement(this)
-
-      return this
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create clipping element
-    clip: function() {
-      return this.defs().put(new SVG.ClipPath)
-    }
-  }
-})
-
-//
-SVG.extend(SVG.Element, {
-  // Distribute clipPath to svg element
-  clipWith: function(element) {
-    // use given clip or create a new one
-    this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element)
-
-    // store reverence on self in mask
-    this.clipper.targets.push(this)
-
-    // apply mask
-    return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")')
-  }
-  // Unclip element
-, unclip: function() {
-    delete this.clipper
-    return this.attr('clip-path', null)
-  }
-
-})
-SVG.Gradient = SVG.invent({
-  // Initialize node
-  create: function(type) {
-    this.constructor.call(this, SVG.create(type + 'Gradient'))
-
-    // store type
-    this.type = type
-  }
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Add a color stop
-    at: function(offset, color, opacity) {
-      return this.put(new SVG.Stop).update(offset, color, opacity)
-    }
-    // Update gradient
-  , update: function(block) {
-      // remove all stops
-      this.clear()
-
-      // invoke passed block
-      if (typeof block == 'function')
-        block.call(this, this)
-
-      return this
-    }
-    // Return the fill id
-  , fill: function() {
-      return 'url(#' + this.id() + ')'
-    }
-    // Alias string convertion to fill
-  , toString: function() {
-      return this.fill()
-    }
-    // custom attr to handle transform
-  , attr: function(a, b, c) {
-      if(a == 'transform') a = 'gradientTransform'
-      return SVG.Container.prototype.attr.call(this, a, b, c)
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create gradient element in defs
-    gradient: function(type, block) {
-      return this.defs().gradient(type, block)
-    }
-  }
-})
-
-// Add animatable methods to both gradient and fx module
-SVG.extend(SVG.Gradient, SVG.FX, {
-  // From position
-  from: function(x, y) {
-    return (this._target || this).type == 'radial' ?
-      this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) :
-      this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) })
-  }
-  // To position
-, to: function(x, y) {
-    return (this._target || this).type == 'radial' ?
-      this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) :
-      this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) })
-  }
-})
-
-// Base gradient generation
-SVG.extend(SVG.Defs, {
-  // define gradient
-  gradient: function(type, block) {
-    return this.put(new SVG.Gradient(type)).update(block)
-  }
-
-})
-
-SVG.Stop = SVG.invent({
-  // Initialize node
-  create: 'stop'
-
-  // Inherit from
-, inherit: SVG.Element
-
-  // Add class methods
-, extend: {
-    // add color stops
-    update: function(o) {
-      if (typeof o == 'number' || o instanceof SVG.Number) {
-        o = {
-          offset:  arguments[0]
-        , color:   arguments[1]
-        , opacity: arguments[2]
-        }
-      }
-
-      // set attributes
-      if (o.opacity != null) this.attr('stop-opacity', o.opacity)
-      if (o.color   != null) this.attr('stop-color', o.color)
-      if (o.offset  != null) this.attr('offset', new SVG.Number(o.offset))
-
-      return this
-    }
-  }
-
-})
-
-SVG.Pattern = SVG.invent({
-  // Initialize node
-  create: 'pattern'
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Return the fill id
-    fill: function() {
-      return 'url(#' + this.id() + ')'
-    }
-    // Update pattern by rebuilding
-  , update: function(block) {
-      // remove content
-      this.clear()
-
-      // invoke passed block
-      if (typeof block == 'function')
-        block.call(this, this)
-
-      return this
-    }
-    // Alias string convertion to fill
-  , toString: function() {
-      return this.fill()
-    }
-    // custom attr to handle transform
-  , attr: function(a, b, c) {
-      if(a == 'transform') a = 'patternTransform'
-      return SVG.Container.prototype.attr.call(this, a, b, c)
-    }
-
-  }
-
-  // Add parent method
-, construct: {
-    // Create pattern element in defs
-    pattern: function(width, height, block) {
-      return this.defs().pattern(width, height, block)
-    }
-  }
-})
-
-SVG.extend(SVG.Defs, {
-  // Define gradient
-  pattern: function(width, height, block) {
-    return this.put(new SVG.Pattern).update(block).attr({
-      x:            0
-    , y:            0
-    , width:        width
-    , height:       height
-    , patternUnits: 'userSpaceOnUse'
-    })
-  }
-
-})
-SVG.Shape = SVG.invent({
-  // Initialize node
-  create: function(element) {
-    this.constructor.call(this, element)
-  }
-
-  // Inherit from
-, inherit: SVG.Element
-
-})
-
-SVG.Bare = SVG.invent({
-  // Initialize
-  create: function(element, inherit) {
-    // construct element
-    this.constructor.call(this, SVG.create(element))
-
-    // inherit custom methods
-    if (inherit)
-      for (var method in inherit.prototype)
-        if (typeof inherit.prototype[method] === 'function')
-          this[method] = inherit.prototype[method]
-  }
-
-  // Inherit from
-, inherit: SVG.Element
-
-  // Add methods
-, extend: {
-    // Insert some plain text
-    words: function(text) {
-      // remove contents
-      while (this.node.hasChildNodes())
-        this.node.removeChild(this.node.lastChild)
-
-      // create text node
-      this.node.appendChild(document.createTextNode(text))
-
-      return this
-    }
-  }
-})
-
-
-SVG.extend(SVG.Parent, {
-  // Create an element that is not described by SVG.js
-  element: function(element, inherit) {
-    return this.put(new SVG.Bare(element, inherit))
-  }
-})
-
-SVG.Symbol = SVG.invent({
-  // Initialize node
-  create: 'symbol'
-
-  // Inherit from
-, inherit: SVG.Container
-
-, construct: {
-    // create symbol
-    symbol: function() {
-      return this.put(new SVG.Symbol)
-    }
-  }
-})
-
-SVG.Use = SVG.invent({
-  // Initialize node
-  create: 'use'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // Use element as a reference
-    element: function(element, file) {
-      // Set lined element
-      return this.attr('href', (file || '') + '#' + element, SVG.xlink)
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create a use element
-    use: function(element, file) {
-      return this.put(new SVG.Use).element(element, file)
-    }
-  }
-})
-SVG.Rect = SVG.invent({
-  // Initialize node
-  create: 'rect'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add parent method
-, construct: {
-    // Create a rect element
-    rect: function(width, height) {
-      return this.put(new SVG.Rect()).size(width, height)
-    }
-  }
-})
-SVG.Circle = SVG.invent({
-  // Initialize node
-  create: 'circle'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add parent method
-, construct: {
-    // Create circle element, based on ellipse
-    circle: function(size) {
-      return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0)
-    }
-  }
-})
-
-SVG.extend(SVG.Circle, SVG.FX, {
-  // Radius x value
-  rx: function(rx) {
-    return this.attr('r', rx)
-  }
-  // Alias radius x value
-, ry: function(ry) {
-    return this.rx(ry)
-  }
-})
-
-SVG.Ellipse = SVG.invent({
-  // Initialize node
-  create: 'ellipse'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add parent method
-, construct: {
-    // Create an ellipse
-    ellipse: function(width, height) {
-      return this.put(new SVG.Ellipse).size(width, height).move(0, 0)
-    }
-  }
-})
-
-SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, {
-  // Radius x value
-  rx: function(rx) {
-    return this.attr('rx', rx)
-  }
-  // Radius y value
-, ry: function(ry) {
-    return this.attr('ry', ry)
-  }
-})
-
-// Add common method
-SVG.extend(SVG.Circle, SVG.Ellipse, {
-    // Move over x-axis
-    x: function(x) {
-      return x == null ? this.cx() - this.rx() : this.cx(x + this.rx())
-    }
-    // Move over y-axis
-  , y: function(y) {
-      return y == null ? this.cy() - this.ry() : this.cy(y + this.ry())
-    }
-    // Move by center over x-axis
-  , cx: function(x) {
-      return x == null ? this.attr('cx') : this.attr('cx', x)
-    }
-    // Move by center over y-axis
-  , cy: function(y) {
-      return y == null ? this.attr('cy') : this.attr('cy', y)
-    }
-    // Set width of element
-  , width: function(width) {
-      return width == null ? this.rx() * 2 : this.rx(new SVG.Number(width).divide(2))
-    }
-    // Set height of element
-  , height: function(height) {
-      return height == null ? this.ry() * 2 : this.ry(new SVG.Number(height).divide(2))
-    }
-    // Custom size function
-  , size: function(width, height) {
-      var p = proportionalSize(this, width, height)
-
-      return this
-        .rx(new SVG.Number(p.width).divide(2))
-        .ry(new SVG.Number(p.height).divide(2))
-    }
-})
-SVG.Line = SVG.invent({
-  // Initialize node
-  create: 'line'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // Get array
-    array: function() {
-      return new SVG.PointArray([
-        [ this.attr('x1'), this.attr('y1') ]
-      , [ this.attr('x2'), this.attr('y2') ]
-      ])
-    }
-    // Overwrite native plot() method
-  , plot: function(x1, y1, x2, y2) {
-      if (x1 == null)
-        return this.array()
-      else if (typeof y1 !== 'undefined')
-        x1 = { x1: x1, y1: y1, x2: x2, y2: y2 }
-      else
-        x1 = new SVG.PointArray(x1).toLine()
-
-      return this.attr(x1)
-    }
-    // Move by left top corner
-  , move: function(x, y) {
-      return this.attr(this.array().move(x, y).toLine())
-    }
-    // Set element size to given width and height
-  , size: function(width, height) {
-      var p = proportionalSize(this, width, height)
-
-      return this.attr(this.array().size(p.width, p.height).toLine())
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create a line element
-    line: function(x1, y1, x2, y2) {
-      // make sure plot is called as a setter
-      // x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray
-      return SVG.Line.prototype.plot.apply(
-        this.put(new SVG.Line)
-      , x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0]
-      )
-    }
-  }
-})
-
-SVG.Polyline = SVG.invent({
-  // Initialize node
-  create: 'polyline'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add parent method
-, construct: {
-    // Create a wrapped polyline element
-    polyline: function(p) {
-      // make sure plot is called as a setter
-      return this.put(new SVG.Polyline).plot(p || new SVG.PointArray)
-    }
-  }
-})
-
-SVG.Polygon = SVG.invent({
-  // Initialize node
-  create: 'polygon'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add parent method
-, construct: {
-    // Create a wrapped polygon element
-    polygon: function(p) {
-      // make sure plot is called as a setter
-      return this.put(new SVG.Polygon).plot(p || new SVG.PointArray)
-    }
-  }
-})
-
-// Add polygon-specific functions
-SVG.extend(SVG.Polyline, SVG.Polygon, {
-  // Get array
-  array: function() {
-    return this._array || (this._array = new SVG.PointArray(this.attr('points')))
-  }
-  // Plot new path
-, plot: function(p) {
-    return (p == null) ?
-      this.array() :
-      this.clear().attr('points', typeof p == 'string' ? p : (this._array = new SVG.PointArray(p)))
-  }
-  // Clear array cache
-, clear: function() {
-    delete this._array
-    return this
-  }
-  // Move by left top corner
-, move: function(x, y) {
-    return this.attr('points', this.array().move(x, y))
-  }
-  // Set element size to given width and height
-, size: function(width, height) {
-    var p = proportionalSize(this, width, height)
-
-    return this.attr('points', this.array().size(p.width, p.height))
-  }
-
-})
-
-// unify all point to point elements
-SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, {
-  // Define morphable array
-  morphArray:  SVG.PointArray
-  // Move by left top corner over x-axis
-, x: function(x) {
-    return x == null ? this.bbox().x : this.move(x, this.bbox().y)
-  }
-  // Move by left top corner over y-axis
-, y: function(y) {
-    return y == null ? this.bbox().y : this.move(this.bbox().x, y)
-  }
-  // Set width of element
-, width: function(width) {
-    var b = this.bbox()
-
-    return width == null ? b.width : this.size(width, b.height)
-  }
-  // Set height of element
-, height: function(height) {
-    var b = this.bbox()
-
-    return height == null ? b.height : this.size(b.width, height)
-  }
-})
-SVG.Path = SVG.invent({
-  // Initialize node
-  create: 'path'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // Define morphable array
-    morphArray:  SVG.PathArray
-    // Get array
-  , array: function() {
-      return this._array || (this._array = new SVG.PathArray(this.attr('d')))
-    }
-    // Plot new path
-  , plot: function(d) {
-      return (d == null) ?
-        this.array() :
-        this.clear().attr('d', typeof d == 'string' ? d : (this._array = new SVG.PathArray(d)))
-    }
-    // Clear array cache
-  , clear: function() {
-      delete this._array
-      return this
-    }
-    // Move by left top corner
-  , move: function(x, y) {
-      return this.attr('d', this.array().move(x, y))
-    }
-    // Move by left top corner over x-axis
-  , x: function(x) {
-      return x == null ? this.bbox().x : this.move(x, this.bbox().y)
-    }
-    // Move by left top corner over y-axis
-  , y: function(y) {
-      return y == null ? this.bbox().y : this.move(this.bbox().x, y)
-    }
-    // Set element size to given width and height
-  , size: function(width, height) {
-      var p = proportionalSize(this, width, height)
-
-      return this.attr('d', this.array().size(p.width, p.height))
-    }
-    // Set width of element
-  , width: function(width) {
-      return width == null ? this.bbox().width : this.size(width, this.bbox().height)
-    }
-    // Set height of element
-  , height: function(height) {
-      return height == null ? this.bbox().height : this.size(this.bbox().width, height)
-    }
-
-  }
-
-  // Add parent method
-, construct: {
-    // Create a wrapped path element
-    path: function(d) {
-      // make sure plot is called as a setter
-      return this.put(new SVG.Path).plot(d || new SVG.PathArray)
-    }
-  }
-})
-
-SVG.Image = SVG.invent({
-  // Initialize node
-  create: 'image'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // (re)load image
-    load: function(url) {
-      if (!url) return this
-
-      var self = this
-        , img  = new window.Image()
-
-      // preload image
-      SVG.on(img, 'load', function() {
-        SVG.off(img)
-
-        var p = self.parent(SVG.Pattern)
-
-        if(p === null) return
-
-        // ensure image size
-        if (self.width() == 0 && self.height() == 0)
-          self.size(img.width, img.height)
-
-        // ensure pattern size if not set
-        if (p && p.width() == 0 && p.height() == 0)
-          p.size(self.width(), self.height())
-
-        // callback
-        if (typeof self._loaded === 'function')
-          self._loaded.call(self, {
-            width:  img.width
-          , height: img.height
-          , ratio:  img.width / img.height
-          , url:    url
-          })
-      })
-
-      SVG.on(img, 'error', function(e){
-        SVG.off(img)
-
-        if (typeof self._error === 'function'){
-            self._error.call(self, e)
-        }
-      })
-
-      return this.attr('href', (img.src = this.src = url), SVG.xlink)
-    }
-    // Add loaded callback
-  , loaded: function(loaded) {
-      this._loaded = loaded
-      return this
-    }
-
-  , error: function(error) {
-      this._error = error
-      return this
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // create image element, load image and set its size
-    image: function(source, width, height) {
-      return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0)
-    }
-  }
-
-})
-SVG.Text = SVG.invent({
-  // Initialize node
-  create: function() {
-    this.constructor.call(this, SVG.create('text'))
-
-    this.dom.leading = new SVG.Number(1.3)    // store leading value for rebuilding
-    this._rebuild = true                      // enable automatic updating of dy values
-    this._build   = false                     // disable build mode for adding multiple lines
-
-    // set default font
-    this.attr('font-family', SVG.defaults.attrs['font-family'])
-  }
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // Move over x-axis
-    x: function(x) {
-      // act as getter
-      if (x == null)
-        return this.attr('x')
-
-      return this.attr('x', x)
-    }
-    // Move over y-axis
-  , y: function(y) {
-      var oy = this.attr('y')
-        , o  = typeof oy === 'number' ? oy - this.bbox().y : 0
-
-      // act as getter
-      if (y == null)
-        return typeof oy === 'number' ? oy - o : oy
-
-      return this.attr('y', typeof y.valueOf() === 'number' ? y + o : y)
-    }
-    // Move center over x-axis
-  , cx: function(x) {
-      return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2)
-    }
-    // Move center over y-axis
-  , cy: function(y) {
-      return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2)
-    }
-    // Set the text content
-  , text: function(text) {
-      // act as getter
-      if (typeof text === 'undefined'){
-        var text = ''
-        var children = this.node.childNodes
-        for(var i = 0, len = children.length; i < len; ++i){
-
-          // add newline if its not the first child and newLined is set to true
-          if(i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true){
-            text += '\n'
-          }
-
-          // add content of this node
-          text += children[i].textContent
-        }
-
-        return text
-      }
-
-      // remove existing content
-      this.clear().build(true)
-
-      if (typeof text === 'function') {
-        // call block
-        text.call(this, this)
-
-      } else {
-        // store text and make sure text is not blank
-        text = text.split('\n')
-
-        // build new lines
-        for (var i = 0, il = text.length; i < il; i++)
-          this.tspan(text[i]).newLine()
-      }
-
-      // disable build mode and rebuild lines
-      return this.build(false).rebuild()
-    }
-    // Set font size
-  , size: function(size) {
-      return this.attr('font-size', size).rebuild()
-    }
-    // Set / get leading
-  , leading: function(value) {
-      // act as getter
-      if (value == null)
-        return this.dom.leading
-
-      // act as setter
-      this.dom.leading = new SVG.Number(value)
-
-      return this.rebuild()
-    }
-    // Get all the first level lines
-  , lines: function() {
-      var node = (this.textPath && this.textPath() || this).node
-
-      // filter tspans and map them to SVG.js instances
-      var lines = SVG.utils.map(SVG.utils.filterSVGElements(node.childNodes), function(el){
-        return SVG.adopt(el)
-      })
-
-      // return an instance of SVG.set
-      return new SVG.Set(lines)
-    }
-    // Rebuild appearance type
-  , rebuild: function(rebuild) {
-      // store new rebuild flag if given
-      if (typeof rebuild == 'boolean')
-        this._rebuild = rebuild
-
-      // define position of all lines
-      if (this._rebuild) {
-        var self = this
-          , blankLineOffset = 0
-          , dy = this.dom.leading * new SVG.Number(this.attr('font-size'))
-
-        this.lines().each(function() {
-          if (this.dom.newLined) {
-            if (!self.textPath())
-              this.attr('x', self.attr('x'))
-            if(this.text() == '\n') {
-              blankLineOffset += dy
-            }else{
-              this.attr('dy', dy + blankLineOffset)
-              blankLineOffset = 0
-            }
-          }
-        })
-
-        this.fire('rebuild')
-      }
-
-      return this
-    }
-    // Enable / disable build mode
-  , build: function(build) {
-      this._build = !!build
-      return this
-    }
-    // overwrite method from parent to set data properly
-  , setData: function(o){
-      this.dom = o
-      this.dom.leading = new SVG.Number(o.leading || 1.3)
-      return this
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create text element
-    text: function(text) {
-      return this.put(new SVG.Text).text(text)
-    }
-    // Create plain text element
-  , plain: function(text) {
-      return this.put(new SVG.Text).plain(text)
-    }
-  }
-
-})
-
-SVG.Tspan = SVG.invent({
-  // Initialize node
-  create: 'tspan'
-
-  // Inherit from
-, inherit: SVG.Shape
-
-  // Add class methods
-, extend: {
-    // Set text content
-    text: function(text) {
-      if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '')
-
-      typeof text === 'function' ? text.call(this, this) : this.plain(text)
-
-      return this
-    }
-    // Shortcut dx
-  , dx: function(dx) {
-      return this.attr('dx', dx)
-    }
-    // Shortcut dy
-  , dy: function(dy) {
-      return this.attr('dy', dy)
-    }
-    // Create new line
-  , newLine: function() {
-      // fetch text parent
-      var t = this.parent(SVG.Text)
-
-      // mark new line
-      this.dom.newLined = true
-
-      // apply new hy¡n
-      return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x())
-    }
-  }
-
-})
-
-SVG.extend(SVG.Text, SVG.Tspan, {
-  // Create plain text node
-  plain: function(text) {
-    // clear if build mode is disabled
-    if (this._build === false)
-      this.clear()
-
-    // create text node
-    this.node.appendChild(document.createTextNode(text))
-
-    return this
-  }
-  // Create a tspan
-, tspan: function(text) {
-    var node  = (this.textPath && this.textPath() || this).node
-      , tspan = new SVG.Tspan
-
-    // clear if build mode is disabled
-    if (this._build === false)
-      this.clear()
-
-    // add new tspan
-    node.appendChild(tspan.node)
-
-    return tspan.text(text)
-  }
-  // Clear all lines
-, clear: function() {
-    var node = (this.textPath && this.textPath() || this).node
-
-    // remove existing child nodes
-    while (node.hasChildNodes())
-      node.removeChild(node.lastChild)
-
-    return this
-  }
-  // Get length of text element
-, length: function() {
-    return this.node.getComputedTextLength()
-  }
-})
-
-SVG.TextPath = SVG.invent({
-  // Initialize node
-  create: 'textPath'
-
-  // Inherit from
-, inherit: SVG.Parent
-
-  // Define parent class
-, parent: SVG.Text
-
-  // Add parent method
-, construct: {
-    morphArray: SVG.PathArray
-    // Create path for text to run on
-  , path: function(d) {
-      // create textPath element
-      var path  = new SVG.TextPath
-        , track = this.doc().defs().path(d)
-
-      // move lines to textpath
-      while (this.node.hasChildNodes())
-        path.node.appendChild(this.node.firstChild)
-
-      // add textPath element as child node
-      this.node.appendChild(path.node)
-
-      // link textPath to path and add content
-      path.attr('href', '#' + track, SVG.xlink)
-
-      return this
-    }
-    // return the array of the path track element
-  , array: function() {
-      var track = this.track()
-
-      return track ? track.array() : null
-    }
-    // Plot path if any
-  , plot: function(d) {
-      var track = this.track()
-        , pathArray = null
-
-      if (track) {
-        pathArray = track.plot(d)
-      }
-
-      return (d == null) ? pathArray : this
-    }
-    // Get the path track element
-  , track: function() {
-      var path = this.textPath()
-
-      if (path)
-        return path.reference('href')
-    }
-    // Get the textPath child
-  , textPath: function() {
-      if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath')
-        return SVG.adopt(this.node.firstChild)
-    }
-  }
-})
-
-SVG.Nested = SVG.invent({
-  // Initialize node
-  create: function() {
-    this.constructor.call(this, SVG.create('svg'))
-
-    this.style('overflow', 'visible')
-  }
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add parent method
-, construct: {
-    // Create nested svg document
-    nested: function() {
-      return this.put(new SVG.Nested)
-    }
-  }
-})
-SVG.A = SVG.invent({
-  // Initialize node
-  create: 'a'
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Link url
-    to: function(url) {
-      return this.attr('href', url, SVG.xlink)
-    }
-    // Link show attribute
-  , show: function(target) {
-      return this.attr('show', target, SVG.xlink)
-    }
-    // Link target attribute
-  , target: function(target) {
-      return this.attr('target', target)
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create a hyperlink element
-    link: function(url) {
-      return this.put(new SVG.A).to(url)
-    }
-  }
-})
-
-SVG.extend(SVG.Element, {
-  // Create a hyperlink element
-  linkTo: function(url) {
-    var link = new SVG.A
-
-    if (typeof url == 'function')
-      url.call(link, link)
-    else
-      link.to(url)
-
-    return this.parent().put(link).put(this)
-  }
-
-})
-SVG.Marker = SVG.invent({
-  // Initialize node
-  create: 'marker'
-
-  // Inherit from
-, inherit: SVG.Container
-
-  // Add class methods
-, extend: {
-    // Set width of element
-    width: function(width) {
-      return this.attr('markerWidth', width)
-    }
-    // Set height of element
-  , height: function(height) {
-      return this.attr('markerHeight', height)
-    }
-    // Set marker refX and refY
-  , ref: function(x, y) {
-      return this.attr('refX', x).attr('refY', y)
-    }
-    // Update marker
-  , update: function(block) {
-      // remove all content
-      this.clear()
-
-      // invoke passed block
-      if (typeof block == 'function')
-        block.call(this, this)
-
-      return this
-    }
-    // Return the fill id
-  , toString: function() {
-      return 'url(#' + this.id() + ')'
-    }
-  }
-
-  // Add parent method
-, construct: {
-    marker: function(width, height, block) {
-      // Create marker element in defs
-      return this.defs().marker(width, height, block)
-    }
-  }
-
-})
-
-SVG.extend(SVG.Defs, {
-  // Create marker
-  marker: function(width, height, block) {
-    // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
-    return this.put(new SVG.Marker)
-      .size(width, height)
-      .ref(width / 2, height / 2)
-      .viewbox(0, 0, width, height)
-      .attr('orient', 'auto')
-      .update(block)
-  }
-
-})
-
-SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, {
-  // Create and attach markers
-  marker: function(marker, width, height, block) {
-    var attr = ['marker']
-
-    // Build attribute name
-    if (marker != 'all') attr.push(marker)
-    attr = attr.join('-')
-
-    // Set marker attribute
-    marker = arguments[1] instanceof SVG.Marker ?
-      arguments[1] :
-      this.doc().marker(width, height, block)
-
-    return this.attr(attr, marker)
-  }
-
-})
-// Define list of available attributes for stroke and fill
-var sugar = {
-  stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset']
-, fill:   ['color', 'opacity', 'rule']
-, prefix: function(t, a) {
-    return a == 'color' ? t : t + '-' + a
-  }
-}
-
-// Add sugar for fill and stroke
-;['fill', 'stroke'].forEach(function(m) {
-  var i, extension = {}
-
-  extension[m] = function(o) {
-    if (typeof o == 'undefined')
-      return this
-    if (typeof o == 'string' || SVG.Color.isRgb(o) || (o && typeof o.fill === 'function'))
-      this.attr(m, o)
-
-    else
-      // set all attributes from sugar.fill and sugar.stroke list
-      for (i = sugar[m].length - 1; i >= 0; i--)
-        if (o[sugar[m][i]] != null)
-          this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]])
-
-    return this
-  }
-
-  SVG.extend(SVG.Element, SVG.FX, extension)
-
-})
-
-SVG.extend(SVG.Element, SVG.FX, {
-  // Map rotation to transform
-  rotate: function(d, cx, cy) {
-    return this.transform({ rotation: d, cx: cx, cy: cy })
-  }
-  // Map skew to transform
-, skew: function(x, y, cx, cy) {
-    return arguments.length == 1  || arguments.length == 3 ?
-      this.transform({ skew: x, cx: y, cy: cx }) :
-      this.transform({ skewX: x, skewY: y, cx: cx, cy: cy })
-  }
-  // Map scale to transform
-, scale: function(x, y, cx, cy) {
-    return arguments.length == 1  || arguments.length == 3 ?
-      this.transform({ scale: x, cx: y, cy: cx }) :
-      this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy })
-  }
-  // Map translate to transform
-, translate: function(x, y) {
-    return this.transform({ x: x, y: y })
-  }
-  // Map flip to transform
-, flip: function(a, o) {
-    o = typeof a == 'number' ? a : o
-    return this.transform({ flip: a || 'both', offset: o })
-  }
-  // Map matrix to transform
-, matrix: function(m) {
-    return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m))
-  }
-  // Opacity
-, opacity: function(value) {
-    return this.attr('opacity', value)
-  }
-  // Relative move over x axis
-, dx: function(x) {
-    return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true)
-  }
-  // Relative move over y axis
-, dy: function(y) {
-    return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true)
-  }
-  // Relative move over x and y axes
-, dmove: function(x, y) {
-    return this.dx(x).dy(y)
-  }
-})
-
-SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, {
-  // Add x and y radius
-  radius: function(x, y) {
-    var type = (this._target || this).type;
-    return type == 'radial' || type == 'circle' ?
-      this.attr('r', new SVG.Number(x)) :
-      this.rx(x).ry(y == null ? x : y)
-  }
-})
-
-SVG.extend(SVG.Path, {
-  // Get path length
-  length: function() {
-    return this.node.getTotalLength()
-  }
-  // Get point at length
-, pointAt: function(length) {
-    return this.node.getPointAtLength(length)
-  }
-})
-
-SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, {
-  // Set font
-  font: function(a, v) {
-    if (typeof a == 'object') {
-      for (v in a) this.font(v, a[v])
-    }
-
-    return a == 'leading' ?
-        this.leading(v) :
-      a == 'anchor' ?
-        this.attr('text-anchor', v) :
-      a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ?
-        this.attr('font-'+ a, v) :
-        this.attr(a, v)
-  }
-})
-
-SVG.Set = SVG.invent({
-  // Initialize
-  create: function(members) {
-    if (members instanceof SVG.Set) {
-      this.members = members.members.slice()
-    } else {
-      Array.isArray(members) ? this.members = members : this.clear()
-    }
-  }
-
-  // Add class methods
-, extend: {
-    // Add element to set
-    add: function() {
-      var i, il, elements = [].slice.call(arguments)
-
-      for (i = 0, il = elements.length; i < il; i++)
-        this.members.push(elements[i])
-
-      return this
-    }
-    // Remove element from set
-  , remove: function(element) {
-      var i = this.index(element)
-
-      // remove given child
-      if (i > -1)
-        this.members.splice(i, 1)
-
-      return this
-    }
-    // Iterate over all members
-  , each: function(block) {
-      for (var i = 0, il = this.members.length; i < il; i++)
-        block.apply(this.members[i], [i, this.members])
-
-      return this
-    }
-    // Restore to defaults
-  , clear: function() {
-      // initialize store
-      this.members = []
-
-      return this
-    }
-    // Get the length of a set
-  , length: function() {
-      return this.members.length
-    }
-    // Checks if a given element is present in set
-  , has: function(element) {
-      return this.index(element) >= 0
-    }
-    // retuns index of given element in set
-  , index: function(element) {
-      return this.members.indexOf(element)
-    }
-    // Get member at given index
-  , get: function(i) {
-      return this.members[i]
-    }
-    // Get first member
-  , first: function() {
-      return this.get(0)
-    }
-    // Get last member
-  , last: function() {
-      return this.get(this.members.length - 1)
-    }
-    // Default value
-  , valueOf: function() {
-      return this.members
-    }
-    // Get the bounding box of all members included or empty box if set has no items
-  , bbox: function(){
-      // return an empty box of there are no members
-      if (this.members.length == 0)
-        return new SVG.RBox()
-
-      // get the first rbox and update the target bbox
-      var rbox = this.members[0].rbox(this.members[0].doc())
-
-      this.each(function() {
-        // user rbox for correct position and visual representation
-        rbox = rbox.merge(this.rbox(this.doc()))
-      })
-
-      return rbox
-    }
-  }
-
-  // Add parent method
-, construct: {
-    // Create a new set
-    set: function(members) {
-      return new SVG.Set(members)
-    }
-  }
-})
-
-SVG.FX.Set = SVG.invent({
-  // Initialize node
-  create: function(set) {
-    // store reference to set
-    this.set = set
-  }
-
-})
-
-// Alias methods
-SVG.Set.inherit = function() {
-  var m
-    , methods = []
-
-  // gather shape methods
-  for(var m in SVG.Shape.prototype)
-    if (typeof SVG.Shape.prototype[m] == 'function' && typeof SVG.Set.prototype[m] != 'function')
-      methods.push(m)
-
-  // apply shape aliasses
-  methods.forEach(function(method) {
-    SVG.Set.prototype[method] = function() {
-      for (var i = 0, il = this.members.length; i < il; i++)
-        if (this.members[i] && typeof this.members[i][method] == 'function')
-          this.members[i][method].apply(this.members[i], arguments)
-
-      return method == 'animate' ? (this.fx || (this.fx = new SVG.FX.Set(this))) : this
-    }
-  })
-
-  // clear methods for the next round
-  methods = []
-
-  // gather fx methods
-  for(var m in SVG.FX.prototype)
-    if (typeof SVG.FX.prototype[m] == 'function' && typeof SVG.FX.Set.prototype[m] != 'function')
-      methods.push(m)
-
-  // apply fx aliasses
-  methods.forEach(function(method) {
-    SVG.FX.Set.prototype[method] = function() {
-      for (var i = 0, il = this.set.members.length; i < il; i++)
-        this.set.members[i].fx[method].apply(this.set.members[i].fx, arguments)
-
-      return this
-    }
-  })
-}
-
-
-SVG.extend(SVG.Element, {
-  // Store data values on svg nodes
-  data: function(a, v, r) {
-    if (typeof a == 'object') {
-      for (v in a)
-        this.data(v, a[v])
-
-    } else if (arguments.length < 2) {
-      try {
-        return JSON.parse(this.attr('data-' + a))
-      } catch(e) {
-        return this.attr('data-' + a)
-      }
-
-    } else {
-      this.attr(
-        'data-' + a
-      , v === null ?
-          null :
-        r === true || typeof v === 'string' || typeof v === 'number' ?
-          v :
-          JSON.stringify(v)
-      )
-    }
-
-    return this
-  }
-})
-SVG.extend(SVG.Element, {
-  // Remember arbitrary data
-  remember: function(k, v) {
-    // remember every item in an object individually
-    if (typeof arguments[0] == 'object')
-      for (var v in k)
-        this.remember(v, k[v])
-
-    // retrieve memory
-    else if (arguments.length == 1)
-      return this.memory()[k]
-
-    // store memory
-    else
-      this.memory()[k] = v
-
-    return this
-  }
-
-  // Erase a given memory
-, forget: function() {
-    if (arguments.length == 0)
-      this._memory = {}
-    else
-      for (var i = arguments.length - 1; i >= 0; i--)
-        delete this.memory()[arguments[i]]
-
-    return this
-  }
-
-  // Initialize or return local memory object
-, memory: function() {
-    return this._memory || (this._memory = {})
-  }
-
-})
-// Method for getting an element by id
-SVG.get = function(id) {
-  var node = document.getElementById(idFromReference(id) || id)
-  return SVG.adopt(node)
-}
-
-// Select elements by query string
-SVG.select = function(query, parent) {
-  return new SVG.Set(
-    SVG.utils.map((parent || document).querySelectorAll(query), function(node) {
-      return SVG.adopt(node)
-    })
-  )
-}
-
-SVG.extend(SVG.Parent, {
-  // Scoped select method
-  select: function(query) {
-    return SVG.select(query, this.node)
-  }
-
-})
-function pathRegReplace(a, b, c, d) {
-  return c + d.replace(SVG.regex.dots, ' .')
-}
-
-// creates deep clone of array
-function array_clone(arr){
-  var clone = arr.slice(0)
-  for(var i = clone.length; i--;){
-    if(Array.isArray(clone[i])){
-      clone[i] = array_clone(clone[i])
-    }
-  }
-  return clone
-}
-
-// tests if a given element is instance of an object
-function is(el, obj){
-  return el instanceof obj
-}
-
-// tests if a given selector matches an element
-function matches(el, selector) {
-  return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
-}
-
-// Convert dash-separated-string to camelCase
-function camelCase(s) {
-  return s.toLowerCase().replace(/-(.)/g, function(m, g) {
-    return g.toUpperCase()
-  })
-}
-
-// Capitalize first letter of a string
-function capitalize(s) {
-  return s.charAt(0).toUpperCase() + s.slice(1)
-}
-
-// Ensure to six-based hex
-function fullHex(hex) {
-  return hex.length == 4 ?
-    [ '#',
-      hex.substring(1, 2), hex.substring(1, 2)
-    , hex.substring(2, 3), hex.substring(2, 3)
-    , hex.substring(3, 4), hex.substring(3, 4)
-    ].join('') : hex
-}
-
-// Component to hex value
-function compToHex(comp) {
-  var hex = comp.toString(16)
-  return hex.length == 1 ? '0' + hex : hex
-}
-
-// Calculate proportional width and height values when necessary
-function proportionalSize(element, width, height) {
-  if (width == null || height == null) {
-    var box = element.bbox()
-
-    if (width == null)
-      width = box.width / box.height * height
-    else if (height == null)
-      height = box.height / box.width * width
-  }
-
-  return {
-    width:  width
-  , height: height
-  }
-}
-
-// Delta transform point
-function deltaTransformPoint(matrix, x, y) {
-  return {
-    x: x * matrix.a + y * matrix.c + 0
-  , y: x * matrix.b + y * matrix.d + 0
-  }
-}
-
-// Map matrix array to object
-function arrayToMatrix(a) {
-  return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] }
-}
-
-// Parse matrix if required
-function parseMatrix(matrix) {
-  if (!(matrix instanceof SVG.Matrix))
-    matrix = new SVG.Matrix(matrix)
-
-  return matrix
-}
-
-// Add centre point to transform object
-function ensureCentre(o, target) {
-  o.cx = o.cx == null ? target.bbox().cx : o.cx
-  o.cy = o.cy == null ? target.bbox().cy : o.cy
-}
-
-// PathArray Helpers
-function arrayToString(a) {
-  for (var i = 0, il = a.length, s = ''; i < il; i++) {
-    s += a[i][0]
-
-    if (a[i][1] != null) {
-      s += a[i][1]
-
-      if (a[i][2] != null) {
-        s += ' '
-        s += a[i][2]
-
-        if (a[i][3] != null) {
-          s += ' '
-          s += a[i][3]
-          s += ' '
-          s += a[i][4]
-
-          if (a[i][5] != null) {
-            s += ' '
-            s += a[i][5]
-            s += ' '
-            s += a[i][6]
-
-            if (a[i][7] != null) {
-              s += ' '
-              s += a[i][7]
-            }
-          }
-        }
-      }
-    }
-  }
-
-  return s + ' '
-}
-
-// Deep new id assignment
-function assignNewId(node) {
-  // do the same for SVG child nodes as well
-  for (var i = node.childNodes.length - 1; i >= 0; i--)
-    if (node.childNodes[i] instanceof window.SVGElement)
-      assignNewId(node.childNodes[i])
-
-  return SVG.adopt(node).id(SVG.eid(node.nodeName))
-}
-
-// Add more bounding box properties
-function fullBox(b) {
-  if (b.x == null) {
-    b.x      = 0
-    b.y      = 0
-    b.width  = 0
-    b.height = 0
-  }
-
-  b.w  = b.width
-  b.h  = b.height
-  b.x2 = b.x + b.width
-  b.y2 = b.y + b.height
-  b.cx = b.x + b.width / 2
-  b.cy = b.y + b.height / 2
-
-  return b
-}
-
-// Get id from reference string
-function idFromReference(url) {
-  var m = (url || '').toString().match(SVG.regex.reference)
-
-  if (m) return m[1]
-}
-
-// If values like 1e-88 are passed, this is not a valid 32 bit float,
-// but in those cases, we are so close to 0 that 0 works well!
-function float32String(v) {
-  return Math.abs(v) > 1e-37 ? v : 0
-}
-
-// Create matrix array for looping
-var abcdef = 'abcdef'.split('')
-
-// Add CustomEvent to IE9 and IE10
-if (typeof window.CustomEvent !== 'function') {
-  // Code from: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
-  var CustomEventPoly = function(event, options) {
-    options = options || { bubbles: false, cancelable: false, detail: undefined }
-    var e = document.createEvent('CustomEvent')
-    e.initCustomEvent(event, options.bubbles, options.cancelable, options.detail)
-    return e
-  }
-
-  CustomEventPoly.prototype = window.Event.prototype
-
-  SVG.CustomEvent = CustomEventPoly
-} else {
-  SVG.CustomEvent = window.CustomEvent
-}
-
-// requestAnimationFrame / cancelAnimationFrame Polyfill with fallback based on Paul Irish
-(function(w) {
-  var lastTime = 0
-  var vendors = ['moz', 'webkit']
-
-  for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
-    w.requestAnimationFrame = w[vendors[x] + 'RequestAnimationFrame']
-    w.cancelAnimationFrame  = w[vendors[x] + 'CancelAnimationFrame'] ||
-                              w[vendors[x] + 'CancelRequestAnimationFrame']
-  }
-
-  w.requestAnimationFrame = w.requestAnimationFrame ||
-    function(callback) {
-      var currTime = new Date().getTime()
-      var timeToCall = Math.max(0, 16 - (currTime - lastTime))
-
-      var id = w.setTimeout(function() {
-        callback(currTime + timeToCall)
-      }, timeToCall)
-
-      lastTime = currTime + timeToCall
-      return id
-    }
-
-  w.cancelAnimationFrame = w.cancelAnimationFrame || w.clearTimeout;
-
-}(window))
-
-return SVG
-
-}));
\ No newline at end of file
diff --git a/playable.js b/playable.js
deleted file mode 100644
index 5d3b0a9..0000000
--- a/playable.js
+++ /dev/null
@@ -1,134 +0,0 @@
-// TODO clean changeVolume, use Tone.Draw
-
-// pauseOffset = sound time after the start point = position of the animation in sound time
-// startTime = date of the corresponding start = date of the last 0% of the animation
-// startPercent = percent of the whole sound where to start
-
-function prepare(model, rate = 1) {
-    model.paused = true
-    model.pauseOffset = 0
-    if (model.view && model.id) {
-        model.view = SVG.adopt(document.getElementById(model.id))
-       /* model.once
-          ? model.view.animate(model.length * 1000).transform({rotation:360, cx:0, cy:0}).pause()
-          : */model.view.animate(model.length * 1000).transform({rotation:360, cx:0, cy:0}).loop().pause()
-    }
-    if (model.soundName) {
-        model.player = new Tone.Player(buffers[model.soundName]).toMaster()
-        model.duration = model.loopPoints[1] - model.loopPoints[0]
-        model.player.playbackRate = model.rate = rate * model.duration / model.length
-        model.player.setLoopPoints.apply(model.player, model.loopPoints)
-        model.player.loop = true
-    }
-    if (model.mobile) {
-        model.duration = model.mobile.length
-        model.rate = rate * model.duration / model.length
-        model.gears = model.mobile.gears.map(v => prepare(v, model.rate))
-    }
-    if (model.collar) {
-        model.duration = model.collar.length // TODO when preparing top collar, duration should ignored
-        model.rate = (rate * model.duration / model.length) || 1 // TODO when preparing top collar, no model.length
-        model.durs = model.collar.beads.map(v => v.length / model.rate)
-        let totalDur = model.durs.reduce((a,b) => a+b, 0)
-        model.players = model.collar.beads.map(v => prepare(v, model.rate))
-        model.clocks = model.players.map((subModel,i,a) => {
-            return new Tone.Clock(t => {
-                if (model.paused && (model.progPause <= t)) return;
-              // if paused, clock t < progPause
-                model.progClock = t
-                model.current = i
-                let prec = (i + a.length - 1) % a.length
-                play(subModel, t, subModel, model.volume, model.mute)
-                pause(a[prec], t, model.paused, true) // hence force recalculation
-                if (model.paused) pause(subModel, model.progPause) // and pause next
-                // console.log(i, Math.min(model.players[i].duration - model.players[i].pauseOffset, model.players[i].pauseOffset)) // TODO Small drift…
-            }, 1/totalDur)
-        })
-    }
-    setVolume(model)
-    return model
-}
-
-function play(model, t, newModel = {}, volume = 1, mute = false) { // TODO What if no new model (first play)
-    if (!model.paused) return;
-    model.paused = false
-    model.volume = newModel.volume || model.volume // TODO cf first TODO
-    model.mute = newModel.mute || model.mute // TODO cf first TODO
-    model.startTime = t - model.pauseOffset / model.rate
-    if (model.view) {
-        Tone.Draw.schedule(() => model.view.animate().play(), t)
-    }
-    if (model.soundName && model.player.output) {
-        model.player.start(t, model.pauseOffset + (model.startPercent * model.player.buffer.duration))
-    }
-    if (model.mobile) {
-        model.gears.map((v,i) => play(v, t, model.gears[i], model.volume * volume, model.mute || mute))
-    }
-    if (model.collar) {
-        let current = 0
-          , acc = 0
-          , ratedOffset = model.pauseOffset / model.rate
-        while (acc <= ratedOffset) {
-          acc += model.durs[current]
-          current = (current + 1) % model.durs.length
-        }
-        let modelToPlay = model.players[(current + model.durs.length - 1) % model.durs.length]
-        play(modelToPlay, t, modelToPlay, model.volume, model.mute)
-        acc = t + acc - ratedOffset
-        for (let i = 0 ; i < model.clocks.length ; i++) {
-          let j = (i + current) % model.clocks.length
-          model.clocks[j].start(acc)
-          acc += model.durs[j]
-        }
-    }
-}
-
-function pause(model, t, force = false, clocked = false) {
-    if (model.paused && !force) return;
-    model.paused = true
-    model.pauseOffset = ((t - model.startTime) * model.rate) % model.duration
-    if (model.view){//} && !clocked) {
-        Tone.Draw.schedule(() => model.view.animate().pause().at((model.pauseOffset/model.length/model.rate) % 1), t)
-    }
-    if (model.soundName && model.player.output) {
-        model.player.stop(t)
-    }
-    if (model.mobile) {
-        model.gears.map(v => pause(v, t))
-    }
-    if (model.collar) {
-        model.progPause = t
-        if (t <= model.progClock) {
-            let prec = (model.current + model.clocks.length - 1) % model.clocks.length
-            pause(model.players[prec], t, true)
-            pause(model.players[model.current], model.progClock)
-        }
-        model.clocks.map(v => v.stop(t))
-        model.players.map(v => pause(v, t))
-    }
-}
-
-function stop(model) {
-    if (model.view) model.view.animate().play().finish().stop()
-    if (model.soundName) model.player.stop().dispose()
-    if (model.mobile) model.gears.map(stop)
-    if (model.collar) {
-        model.clocks.map(v => v.stop())
-        model.players.map(stop)
-    }
-}
-
-function setVolume(model, volume = 1, mute = false) {
-    if (model.soundName) {
-        if (mute || model.mute) {
-            model.player.toMaster()
-            model.player.disconnect(Tone.Master)
-        }
-        else {
-            model.player.toMaster()
-            model.player.volume.value = ((model.volume * volume) - 1) * 60
-        }
-    }
-    if (model.mobile) model.gears.map(v => setVolume(v, model.volume * volume, model.mute || mute))
-    if (model.collar) model.players.map(v => setVolume(v, model.volume * volume, model.mute || mute))
-}
\ No newline at end of file
diff --git a/ports.html b/ports.html
index cc39cf9..cd8937b 100644
--- a/ports.html
+++ b/ports.html
@@ -9,8 +9,6 @@
 
   
     
-    
-    
     
     
     
diff --git a/ports.js b/ports.js
index e8ee3ea..1d036dd 100644
--- a/ports.js
+++ b/ports.js
@@ -10,14 +10,9 @@ if (app.ports.inputRec) app.ports.inputRec.subscribe(inputRec)
 
 const buffers = {}
     , ro = new ResizeObserver(sendSize)
-//    , ctx = new AudioContext()
-//ctx.suspend()
-//    , ctx = new AudioContext()
     , recorder = new Recorder(masterGain)
 ro.observe(document.getElementById('svgResizeObserver'))
 
-//let playing = {}
-
 let deb = null
 
 function sendSize(entries) {
@@ -57,7 +52,7 @@ function loadOk(soundName) {
 }
 
 function loadErr(err, soundName) {
-  console.log(err)
+  console.error(err)
   app.ports.soundLoaded.send(soundName + ' got ' + err)
 }
 
@@ -119,23 +114,14 @@ function cutSample(infos) {
     app.ports.gotNewSample.send(new File([audioBufferToWav(newBuf)], infos.newFileName + ".wav", {type: "audio/wav"}))
 }
 
-//let playPauseLatency = .1
-//  , masterGain = ctx.createGain()
-//masterGain.connect(ctx.destination)
 function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
   let model = null
   switch ( o.action ) {
     case "stopReset" :
         scheduler.stop()
-//        for ( id in playing) {
-//            stop(playing[id])
-//        }
-//        playing = {}
         break;
     case "playPause" :
         scheduler.startThenPlay(o.gears)
-//        let t = scheduler.getTime() + playPauseLatency
-//        o.gears.map(g => scheduler.playPause(g, t))
         break;
     case "mute" :
         model = o.beadIndexes.reduce(
@@ -164,18 +150,6 @@ function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
     }
 }
 
-function playPause(model,t) {
-    if (!playing[model.id]) {
-        playing[model.id] = prepare(model)
-    }
-    if (playing[model.id].paused) {
-        play(playing[model.id], t, model)
-    }
-    else {
-        pause(playing[model.id], t)
-    }
-}
-
 function drawSamples(samples) {
   setTimeout(() => {
       let canvas = document.getElementById('waveform')
diff --git a/scheduler.js b/scheduler.js
index de15d08..8e3fcaf 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -64,7 +64,7 @@ let scheduler = {
     }
     
     if (!recording) ctx.suspend()
-    
+
     this.intervalId = -1
     this.nextRequestId = -1
     this.startTime = -1

From d2b873bd2170722dc4fb11a497050440f9a0c0f8 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 24 Oct 2020 22:15:25 +0200
Subject: [PATCH 78/85] update pkgConfig

---
 pkgConfig.json | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/pkgConfig.json b/pkgConfig.json
index cf9244f..2155dfd 100644
--- a/pkgConfig.json
+++ b/pkgConfig.json
@@ -2,14 +2,14 @@
 , "pkg":
   { "scripts":  []
   , "assets":
-    [ "playable.js"
+    [ "scheduler.js"
     , "ports.html"
+    , "style.css"
+    , "icone.svg"
     , "ports.js"
     , "elmApp.js"
     , "lib/recorder.js"
     , "lib/audiobuffer-to-wav.js"
-    , "lib/svg.js"
-    , "lib/Tone.js"
     , "LICENSE.md"
     ]
   }

From 2af44b756c5d9a0fc176c57ebb1256f256b65b61 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 26 Oct 2020 00:29:44 +0100
Subject: [PATCH 79/85] deactivate shortcuts when in text input

---
 src/Keys.elm | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/src/Keys.elm b/src/Keys.elm
index 64b0ddc..504f79f 100644
--- a/src/Keys.elm
+++ b/src/Keys.elm
@@ -53,6 +53,19 @@ update msg state =
 
 subs : List (Sub Msg)
 subs =
-    [ BE.onKeyDown <| D.andThen (\str -> D.succeed <| HoldDown str) <| D.field "code" D.string
+    [ BE.onKeyDown <|
+        D.andThen
+            (\node ->
+                if node == "INPUT" || node == "TEXTAREA" then
+                    D.fail "ignored from text input"
+
+                else
+                    D.andThen
+                        (\str -> D.succeed <| HoldDown str)
+                    <|
+                        D.field "code" D.string
+            )
+        <|
+            D.at [ "target", "nodeName" ] D.string
     , BE.onKeyUp <| D.andThen (\str -> D.succeed <| HoldUp str) <| D.field "code" D.string
     ]

From 7cb5681bb6711a69184e7a56dac7df2dd0db1e4a Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 26 Oct 2020 00:32:03 +0100
Subject: [PATCH 80/85] better fract input

---
 src/Editor/Mobile.elm | 89 ++++++++++++++++++++++++++++++-------------
 1 file changed, 62 insertions(+), 27 deletions(-)

diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index ad940ad..2361ed2 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -133,7 +133,7 @@ type alias LinkInfo =
 
 
 type FractInput
-    = FractionInput Fraction
+    = FractionInput Fraction Bool Bool -- non empty numerator then denominator
     | TextInput String
 
 
@@ -539,9 +539,9 @@ update msg ( model, mobile ) =
             }
 
         EnteredFract isNumerator str ->
-            Maybe.map2 Tuple.pair model.link (String.toInt str)
+            Maybe.map2 Tuple.pair model.link (toIntOrEmpty str)
                 |> Maybe.map
-                    (\( link, i ) ->
+                    (\( link, iOr ) ->
                         { return
                             | model =
                                 { model
@@ -550,12 +550,17 @@ update msg ( model, mobile ) =
                                             { link
                                                 | fractInput =
                                                     case link.fractInput of
-                                                        FractionInput fract ->
-                                                            if isNumerator then
-                                                                FractionInput { fract | num = i }
+                                                        FractionInput fract numB denB ->
+                                                            case iOr of
+                                                                Empty ->
+                                                                    FractionInput fract (not isNumerator) isNumerator
 
-                                                            else
-                                                                FractionInput { fract | den = i }
+                                                                Int i ->
+                                                                    if isNumerator then
+                                                                        FractionInput { fract | num = i } True denB
+
+                                                                    else
+                                                                        FractionInput { fract | den = i } numB True
 
                                                         TextInput s ->
                                                             TextInput s
@@ -576,17 +581,21 @@ update msg ( model, mobile ) =
             }
 
         EnteredTextFract str ->
-            case model.link of
-                Nothing ->
-                    return
+            if String.all (\c -> Char.isDigit c || c == '/') str then
+                case model.link of
+                    Nothing ->
+                        return
 
-                Just link ->
-                    case link.fractInput of
-                        FractionInput _ ->
-                            return
+                    Just link ->
+                        case link.fractInput of
+                            FractionInput _ _ _ ->
+                                return
+
+                            TextInput _ ->
+                                { return | model = { model | link = Just { link | fractInput = TextInput str } } }
 
-                        TextInput _ ->
-                            { return | model = { model | link = Just { link | fractInput = TextInput str } } }
+            else
+                return
 
         ForcedFract l fract ->
             -- TODO FIXME URGENTLY Abuses Harmo internals, as Gear.copy
@@ -680,7 +689,7 @@ update msg ( model, mobile ) =
                 , model =
                     case model.link of
                         Just link ->
-                            { model | link = Just { link | fractInput = FractionInput fract } }
+                            { model | link = Just { link | fractInput = FractionInput fract True True } }
 
                         Nothing ->
                             model
@@ -691,14 +700,14 @@ update msg ( model, mobile ) =
                 |> Maybe.map
                     (\link ->
                         case link.fractInput of
-                            FractionInput fract ->
+                            FractionInput fract numB denB ->
                                 { return
                                     | model =
                                         { model
                                             | link =
                                                 Just
                                                     { link
-                                                        | fractInput = FractionInput <| Fract.simplify fract
+                                                        | fractInput = FractionInput (Fract.simplify fract) numB denB
                                                     }
                                         }
                                 }
@@ -1344,7 +1353,7 @@ viewContent ( model, mobile ) =
                                                 Just { link, fractInput } ->
                                                     Link.viewSelectedLink (Gear.toDrawLink mobile.gears link) <|
                                                         case fractInput of
-                                                            FractionInput _ ->
+                                                            FractionInput _ _ _ ->
                                                                 Just <|
                                                                     Fract.simplify <|
                                                                         Fract.division
@@ -1730,19 +1739,29 @@ viewHarmonizeDetails model mobile =
             [ viewDetailsColumn (rgb 0.5 0.5 0.5)
                 ([ text <| (Gear.toUID <| Tuple.first link) ++ (Gear.toUID <| Tuple.second link) ]
                     ++ (case fractInput of
-                            FractionInput fract ->
+                            FractionInput fract numB denB ->
                                 [ Input.text [ Font.color (rgb 0 0 0) ]
-                                    { text = String.fromInt fract.num
+                                    { text =
+                                        if numB then
+                                            String.fromInt fract.num
+
+                                        else
+                                            ""
                                     , onChange = EnteredFract True
                                     , label = Input.labelHidden "Numerator"
-                                    , placeholder = Nothing
+                                    , placeholder = Just <| Input.placeholder [] <| text <| String.fromInt fract.num
                                     }
                                 , text "/"
                                 , Input.text [ Font.color (rgb 0 0 0) ]
-                                    { text = String.fromInt fract.den
+                                    { text =
+                                        if denB then
+                                            String.fromInt fract.den
+
+                                        else
+                                            ""
                                     , onChange = EnteredFract False
                                     , label = Input.labelHidden "Denominator"
-                                    , placeholder = Nothing
+                                    , placeholder = Just <| Input.placeholder [] <| text <| String.fromInt fract.den
                                     }
                                 , Input.button []
                                     { label = text "Change"
@@ -2439,7 +2458,9 @@ interactHarmonize event model mobile =
                         , link =
                             Just
                                 { link = l
-                                , fractInput = Maybe.withDefault (TextInput "") <| Maybe.map FractionInput mayFract
+                                , fractInput =
+                                    Maybe.withDefault (TextInput "") <|
+                                        Maybe.map (\f -> FractionInput f True True) mayFract
                                 }
                     }
                 , mobile = { mobile | gears = newGears }
@@ -2741,3 +2762,17 @@ hexToInt s =
 hexToFloat : String -> Float
 hexToFloat s =
     toFloat (hexToInt (String.slice 0 1 s) * 16 + (hexToInt <| String.slice 1 2 s)) / 255
+
+
+type IntOrEmpty
+    = Int Int
+    | Empty
+
+
+toIntOrEmpty : String -> Maybe IntOrEmpty
+toIntOrEmpty str =
+    if String.isEmpty str then
+        Just Empty
+
+    else
+        Maybe.map Int <| String.toInt str

From 43d9989318272b486337dd33d89c51c8b729fe06 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 26 Oct 2020 00:32:41 +0100
Subject: [PATCH 81/85] minor

forgotten log
---
 ports.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ports.js b/ports.js
index 1d036dd..0cde196 100644
--- a/ports.js
+++ b/ports.js
@@ -114,7 +114,7 @@ function cutSample(infos) {
     app.ports.gotNewSample.send(new File([audioBufferToWav(newBuf)], infos.newFileName + ".wav", {type: "audio/wav"}))
 }
 
-function engine(o) {console.log(JSON.stringify(o, 'utf8', 2))
+function engine(o) {
   let model = null
   switch ( o.action ) {
     case "stopReset" :

From 37d3dede2ef4c67534d79bbe56d8ae8b9bcfad8d Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 26 Oct 2020 00:39:13 +0100
Subject: [PATCH 82/85] collar Mult

---
 src/Data/Collar.elm   |   9 ++++
 src/Editor/Mobile.elm | 102 ++++++++++++++++++++++++++++++++++++------
 2 files changed, 98 insertions(+), 13 deletions(-)

diff --git a/src/Data/Collar.elm b/src/Data/Collar.elm
index f7d64a0..d415278 100644
--- a/src/Data/Collar.elm
+++ b/src/Data/Collar.elm
@@ -47,6 +47,15 @@ fromWheel w l =
     }
 
 
+fromWheelMult : Wheel -> Int -> Float -> Colleer
+fromWheelMult w m l =
+    { matrice = m
+    , loop = l * toFloat m
+    , head = { length = l, wheel = w }
+    , beads = List.repeat (m - 1) { length = l, wheel = w }
+    }
+
+
 length : Colleer -> Int
 length =
     List.length << getBeads
diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index 2361ed2..73f73a1 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -81,6 +81,7 @@ type alias Model =
     , edit : List (Id Geer)
     , beadCursor : Int
     , link : Maybe LinkInfo
+    , collarMult : ( Int, Bool )
     , newSampleName : String
     , parentUid : String -- TODO Two sources of truth !! same in Engine
     , engine : Engine
@@ -165,6 +166,7 @@ init =
     , edit = []
     , beadCursor = 0
     , link = Nothing
+    , collarMult = ( 4, True )
     , newSampleName = ""
     , parentUid = ""
     , engine = Engine.init
@@ -218,8 +220,9 @@ type Msg
     | SimplifyFractView
     | ResizeToContent (Id Geer)
     | Capsuled (List (Id Geer))
-    | Collared (Id Geer)
+    | Collared (Id Geer) Collaring
     | UnCollar (Id Geer)
+    | EnteredCollarMult String
     | EnteredNewSampleName String
     | CutNewSample
     | Blink
@@ -256,6 +259,11 @@ type ToUndo
     | NOOP
 
 
+type Collaring
+    = Simple
+    | Mult Int
+
+
 update : Msg -> ( Model, Mobeel ) -> Return
 update msg ( model, mobile ) =
     let
@@ -779,16 +787,35 @@ update msg ( model, mobile ) =
                 , toUndo = Do
             }
 
-        Collared id ->
+        Collared id collaring ->
             let
                 g =
                     Coll.get id mobile.gears
 
+                l =
+                    Harmo.getLength g.harmony mobile.gears
+
                 collar =
-                    Collar.fromWheel g.wheel <| Harmo.getLength g.harmony mobile.gears
+                    case collaring of
+                        Simple ->
+                            Collar.fromWheel g.wheel l
+
+                        Mult i ->
+                            Collar.fromWheelMult g.wheel i l
+
+                tmp =
+                    Coll.update id (Wheel.setContent <| Content.C collar) mobile.gears
+
+                res =
+                    case collaring of
+                        Mult i ->
+                            Harmo.changeSelf id (toFloat i * l) tmp
+
+                        _ ->
+                            tmp
             in
             { return
-                | mobile = { mobile | gears = Coll.update id (Wheel.setContent <| Content.C collar) mobile.gears }
+                | mobile = { mobile | gears = res }
                 , toUndo = Do
             }
 
@@ -807,6 +834,21 @@ update msg ( model, mobile ) =
                 _ ->
                     return
 
+        EnteredCollarMult str ->
+            case toIntOrEmpty str of
+                Just (Int i) ->
+                    if i >= 2 then
+                        { return | model = { model | collarMult = ( i, True ) } }
+
+                    else
+                        return
+
+                Just Empty ->
+                    { return | model = { model | collarMult = Tuple.mapSecond (always False) model.collarMult } }
+
+                _ ->
+                    return
+
         EnteredNewSampleName str ->
             { return
                 | model =
@@ -1586,7 +1628,43 @@ viewEditDetails model mobile =
                         { label = text "Encapsuler"
                         , onPress = Just <| Capsuled [ id ]
                         }
-                    , case Wheel.getContent g of
+                    , let
+                        multBtns =
+                            Input.button []
+                                { label = text "x"
+                                , onPress = Just <| Collared id <| Mult <| Tuple.first model.collarMult
+                                }
+                                :: [ Input.text
+                                        [ paddingXY 0 0
+                                        , width <| minimum 40 <| fill
+                                        , Font.color <| rgb 0 0 0
+                                        , htmlAttribute <| Html.Attributes.type_ "number"
+                                        , htmlAttribute <| Html.Attributes.min "2"
+                                        ]
+                                        { onChange = EnteredCollarMult
+                                        , text =
+                                            if Tuple.second model.collarMult then
+                                                String.fromInt <| Tuple.first model.collarMult
+
+                                            else
+                                                ""
+                                        , placeholder =
+                                            Just <|
+                                                Input.placeholder [] <|
+                                                    text <|
+                                                        String.fromInt <|
+                                                            Tuple.first model.collarMult
+                                        , label = Input.labelHidden "Collar Multiplier"
+                                        }
+                                   ]
+
+                        simpleBtn =
+                            Input.button []
+                                { label = text "Collier"
+                                , onPress = Just <| Collared id Simple
+                                }
+                      in
+                      case Wheel.getContent g of
                         Content.C col ->
                             if List.length col.beads == 0 then
                                 Input.button []
@@ -1595,16 +1673,14 @@ viewEditDetails model mobile =
                                     }
 
                             else
-                                Input.button []
-                                    { label = text "Collier"
-                                    , onPress = Just <| Collared id
-                                    }
+                                row [ spacing 16 ] <|
+                                    simpleBtn
+                                        :: multBtns
 
                         _ ->
-                            Input.button []
-                                { label = text "Collier"
-                                , onPress = Just <| Collared id
-                                }
+                            row [ spacing 16 ] <|
+                                simpleBtn
+                                    :: multBtns
                     , if id == mobile.motor then
                         Input.button []
                             { onPress = Just <| ChangedMode SelectMotor

From 28813818a7dac374e9406b3d5f86c50d15ea92fa Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Mon, 26 Oct 2020 14:56:28 +0100
Subject: [PATCH 83/85] collar Division

---
 src/Data/Collar.elm   | 25 ++++++++++++++++++++++
 src/Editor/Mobile.elm | 50 ++++++++++++++++++++++++++++++++++++-------
 src/Sound.elm         | 18 ++++++++++++++++
 3 files changed, 85 insertions(+), 8 deletions(-)

diff --git a/src/Data/Collar.elm b/src/Data/Collar.elm
index d415278..cb87819 100644
--- a/src/Data/Collar.elm
+++ b/src/Data/Collar.elm
@@ -5,6 +5,7 @@ import Data.Content as Content exposing (Bead, Collar, Content)
 import Data.Wheel as Wheel exposing (Conteet, Wheel)
 import Json.Decode as D
 import Json.Encode as E
+import Sound exposing (Sound)
 
 
 type alias Colleer =
@@ -56,6 +57,30 @@ fromWheelMult w m l =
     }
 
 
+fromSoundDiv : Sound -> Int -> Float -> Colleer
+fromSoundDiv s d l =
+    let
+        sounds =
+            Sound.division d s
+
+        contents =
+            List.map Content.S sounds
+
+        beads =
+            List.map beadFromContent contents
+    in
+    case beads of
+        head :: rest ->
+            { matrice = d
+            , loop = l
+            , head = head
+            , beads = rest
+            }
+
+        _ ->
+            fromWheel (Wheel.fromContent <| Content.S s) l
+
+
 length : Colleer -> Int
 length =
     List.length << getBeads
diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index 73f73a1..02ebdf3 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -82,6 +82,7 @@ type alias Model =
     , beadCursor : Int
     , link : Maybe LinkInfo
     , collarMult : ( Int, Bool )
+    , collarDiv : ( Int, Bool )
     , newSampleName : String
     , parentUid : String -- TODO Two sources of truth !! same in Engine
     , engine : Engine
@@ -167,6 +168,7 @@ init =
     , beadCursor = 0
     , link = Nothing
     , collarMult = ( 4, True )
+    , collarDiv = ( 4, True )
     , newSampleName = ""
     , parentUid = ""
     , engine = Engine.init
@@ -223,6 +225,7 @@ type Msg
     | Collared (Id Geer) Collaring
     | UnCollar (Id Geer)
     | EnteredCollarMult String
+    | EnteredCollarDiv String
     | EnteredNewSampleName String
     | CutNewSample
     | Blink
@@ -262,6 +265,7 @@ type ToUndo
 type Collaring
     = Simple
     | Mult Int
+    | Div Sound Int
 
 
 update : Msg -> ( Model, Mobeel ) -> Return
@@ -803,6 +807,9 @@ update msg ( model, mobile ) =
                         Mult i ->
                             Collar.fromWheelMult g.wheel i l
 
+                        Div s i ->
+                            Collar.fromSoundDiv s i l
+
                 tmp =
                     Coll.update id (Wheel.setContent <| Content.C collar) mobile.gears
 
@@ -849,6 +856,21 @@ update msg ( model, mobile ) =
                 _ ->
                     return
 
+        EnteredCollarDiv str ->
+            case toIntOrEmpty str of
+                Just (Int i) ->
+                    if i >= 2 then
+                        { return | model = { model | collarDiv = ( i, True ) } }
+
+                    else
+                        return
+
+                Just Empty ->
+                    { return | model = { model | collarDiv = Tuple.mapSecond (always False) model.collarDiv } }
+
+                _ ->
+                    return
+
         EnteredNewSampleName str ->
             { return
                 | model =
@@ -1629,10 +1651,10 @@ viewEditDetails model mobile =
                         , onPress = Just <| Capsuled [ id ]
                         }
                     , let
-                        multBtns =
+                        btns label pressMsg changeMsg tuple =
                             Input.button []
-                                { label = text "x"
-                                , onPress = Just <| Collared id <| Mult <| Tuple.first model.collarMult
+                                { label = text label
+                                , onPress = Just <| Collared id <| pressMsg <| Tuple.first tuple
                                 }
                                 :: [ Input.text
                                         [ paddingXY 0 0
@@ -1641,10 +1663,10 @@ viewEditDetails model mobile =
                                         , htmlAttribute <| Html.Attributes.type_ "number"
                                         , htmlAttribute <| Html.Attributes.min "2"
                                         ]
-                                        { onChange = EnteredCollarMult
+                                        { onChange = changeMsg
                                         , text =
-                                            if Tuple.second model.collarMult then
-                                                String.fromInt <| Tuple.first model.collarMult
+                                            if Tuple.second tuple then
+                                                String.fromInt <| Tuple.first tuple
 
                                             else
                                                 ""
@@ -1653,11 +1675,17 @@ viewEditDetails model mobile =
                                                 Input.placeholder [] <|
                                                     text <|
                                                         String.fromInt <|
-                                                            Tuple.first model.collarMult
-                                        , label = Input.labelHidden "Collar Multiplier"
+                                                            Tuple.first tuple
+                                        , label = Input.labelHidden <| "Collar " ++ label
                                         }
                                    ]
 
+                        multBtns =
+                            btns "x" Mult EnteredCollarMult model.collarMult
+
+                        divBtns s =
+                            btns "/" (Div s) EnteredCollarDiv model.collarDiv
+
                         simpleBtn =
                             Input.button []
                                 { label = text "Collier"
@@ -1677,6 +1705,12 @@ viewEditDetails model mobile =
                                     simpleBtn
                                         :: multBtns
 
+                        Content.S s ->
+                            row [ spacing 16 ] <|
+                                simpleBtn
+                                    :: multBtns
+                                    ++ divBtns s
+
                         _ ->
                             row [ spacing 16 ] <|
                                 simpleBtn
diff --git a/src/Sound.elm b/src/Sound.elm
index abe5522..87261c3 100644
--- a/src/Sound.elm
+++ b/src/Sound.elm
@@ -77,6 +77,24 @@ setLoop mays (S s) =
             S s
 
 
+division : Int -> Sound -> List Sound
+division n (S s) =
+    let
+        durPercent =
+            s.endPercent - s.startPercent
+
+        loopPoints ( f1, f2 ) =
+            ( Just <| s.startPercent + f1 * durPercent, Just <| s.startPercent + f2 * durPercent )
+
+        nn =
+            toFloat n
+    in
+    List.range 1 n
+        |> List.map toFloat
+        |> List.map (\i -> ( (i - 1) / nn, i / nn ))
+        |> List.map (\fs -> setLoop (loopPoints fs) <| S s)
+
+
 chgPath : Sound -> String -> Sound
 chgPath (S s) p =
     S { s | path = p }

From 027bf1a10b6043bef3b4e8721d9531709e3b649f Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Wed, 28 Oct 2020 11:38:56 +0100
Subject: [PATCH 84/85] view divided collars in waveform

---
 src/Data/Collar.elm        | 20 ++++++++-
 src/Data/Common.elm        | 30 ++++++++++++--
 src/Data/Content.elm       | 68 +++++++++++++++++++++++++------
 src/Editor/Interacting.elm |  1 +
 src/Editor/Mobile.elm      | 46 +++++++++++++++------
 src/Sound.elm              | 25 ++++++++----
 src/Waveform.elm           | 83 ++++++++++++++++++++++++--------------
 7 files changed, 203 insertions(+), 70 deletions(-)

diff --git a/src/Data/Collar.elm b/src/Data/Collar.elm
index cb87819..dd4d60a 100644
--- a/src/Data/Collar.elm
+++ b/src/Data/Collar.elm
@@ -45,6 +45,7 @@ fromWheel w l =
     , loop = l
     , head = { length = l, wheel = w }
     , beads = []
+    , oneSound = Nothing
     }
 
 
@@ -54,14 +55,18 @@ fromWheelMult w m l =
     , loop = l * toFloat m
     , head = { length = l, wheel = w }
     , beads = List.repeat (m - 1) { length = l, wheel = w }
+    , oneSound = Nothing
     }
 
 
 fromSoundDiv : Sound -> Int -> Float -> Colleer
 fromSoundDiv s d l =
     let
-        sounds =
-            Sound.division d s
+        ( sounds, divs ) =
+            Sound.divide d s
+
+        loopPercents =
+            Sound.getLoopPercents s
 
         contents =
             List.map Content.S sounds
@@ -75,6 +80,13 @@ fromSoundDiv s d l =
             , loop = l
             , head = head
             , beads = rest
+            , oneSound =
+                Just
+                    { soundName = Sound.toString s
+                    , start = Tuple.first loopPercents
+                    , end = Tuple.second loopPercents
+                    , divs = divs
+                    }
             }
 
         _ ->
@@ -123,12 +135,14 @@ add i b c =
             | head = b
             , beads = c.head :: c.beads
             , matrice = c.matrice + 1
+            , oneSound = Nothing
         }
 
     else
         { c
             | beads = List.concat [ List.take (i - 1) c.beads, [ b ], List.drop (i - 1) c.beads ]
             , matrice = c.matrice + 1
+            , oneSound = Nothing
         }
 
 
@@ -144,6 +158,7 @@ rm i c =
                     | head = head
                     , beads = beads
                     , matrice = c.matrice - 1
+                    , oneSound = Nothing
                 }
 
             ( j, beads ) ->
@@ -155,6 +170,7 @@ rm i c =
 
                         else
                             c.matrice
+                    , oneSound = Nothing
                 }
 
 
diff --git a/src/Data/Common.elm b/src/Data/Common.elm
index a31c9fe..41773ae 100644
--- a/src/Data/Common.elm
+++ b/src/Data/Common.elm
@@ -134,6 +134,20 @@ deleteWheel ( id, l ) mobile gRm bRm =
 updateWheel : Identifier -> Wheel.Msg -> Mobile Wheel -> Mobile Wheel
 updateWheel ( id, list ) msg m =
     let
+        modify =
+            case msg of
+                Wheel.ChangeContent _ ->
+                    True
+
+                Wheel.ChangeStart _ ->
+                    True
+
+                Wheel.ChangeLoop _ ->
+                    True
+
+                _ ->
+                    False
+
         rec : List Int -> Wheel -> Wheel
         rec l w =
             case l of
@@ -144,10 +158,18 @@ updateWheel ( id, list ) msg m =
                 i :: ll ->
                     case Wheel.getWheelContent w of
                         Content.C col ->
-                            (Wheel.setContent
-                                (Content.C <| Content.updateBead i (\bead -> { bead | wheel = rec ll bead.wheel }) col)
-                                { wheel = w }
-                            ).wheel
+                            let
+                                upCol =
+                                    Content.updateBead i (\bead -> { bead | wheel = rec ll bead.wheel }) col
+
+                                newCol =
+                                    if modify then
+                                        { upCol | oneSound = Nothing }
+
+                                    else
+                                        upCol
+                            in
+                            (Wheel.setContent (Content.C newCol) { wheel = w }).wheel
 
                         _ ->
                             let
diff --git a/src/Data/Content.elm b/src/Data/Content.elm
index 4eb57d7..8fbaed0 100644
--- a/src/Data/Content.elm
+++ b/src/Data/Content.elm
@@ -100,7 +100,14 @@ beadDecoder wheelDecoder =
 
 
 type alias Collar item =
-    { matrice : Int, loop : Float, head : Bead item, beads : List (Bead item) }
+    { matrice : Int
+    , loop : Float
+    , head : Bead item
+    , beads : List (Bead item)
+
+    -- WARNING second source of truth, just a shortcut to sounds internals
+    , oneSound : Maybe { soundName : String, start : Float, end : Float, divs : List Float }
+    }
 
 
 getBeads : Collar item -> List (Bead item)
@@ -159,13 +166,24 @@ getMatriceLength c =
 
 collarEncoder : (item -> List ( String, E.Value )) -> Collar item -> E.Value
 collarEncoder wheelEncoder c =
-    E.object
+    E.object <|
         [ ( "matriceSize", E.int c.matrice )
         , ( "loopStart", E.float c.loop )
         , ( "beads"
           , E.list (beadEncoder wheelEncoder) <| getBeads c
           )
         ]
+            ++ (Maybe.withDefault [] <|
+                    Maybe.map
+                        (\oneSound ->
+                            [ ( "oneSoundName", E.string oneSound.soundName )
+                            , ( "divs", E.list E.float oneSound.divs )
+                            , ( "start", E.float oneSound.start )
+                            , ( "end", E.float oneSound.end )
+                            ]
+                        )
+                        c.oneSound
+               )
 
 
 collarDecoder : D.Decoder item -> D.Decoder (Collar item)
@@ -176,13 +194,39 @@ collarDecoder wheelDecoder =
                 \loop ->
                     Field.require "beads" (D.list <| beadDecoder wheelDecoder) <|
                         \beads ->
-                            let
-                                matrice =
-                                    Maybe.withDefault (List.length beads) mayMatrice
-                            in
-                            case beads of
-                                head :: list ->
-                                    D.succeed { matrice = matrice, loop = loop, head = head, beads = list }
-
-                                _ ->
-                                    D.fail "Collar should have at least one bead"
+                            Field.attempt "oneSoundName" D.string <|
+                                \oneSoundStr ->
+                                    Field.attempt "divs" (D.list D.float) <|
+                                        \oneSoundDivs ->
+                                            Field.attempt "start" D.float <|
+                                                \oneSoundStart ->
+                                                    Field.attempt "end" D.float <|
+                                                        \oneSoundEnd ->
+                                                            let
+                                                                matrice =
+                                                                    Maybe.withDefault (List.length beads) mayMatrice
+                                                            in
+                                                            case beads of
+                                                                head :: list ->
+                                                                    D.succeed
+                                                                        { matrice = matrice
+                                                                        , loop = loop
+                                                                        , head = head
+                                                                        , beads = list
+                                                                        , oneSound =
+                                                                            Maybe.map4
+                                                                                (\str start end divs ->
+                                                                                    { soundName = str
+                                                                                    , start = start
+                                                                                    , end = end
+                                                                                    , divs = divs
+                                                                                    }
+                                                                                )
+                                                                                oneSoundStr
+                                                                                oneSoundStart
+                                                                                oneSoundEnd
+                                                                                oneSoundDivs
+                                                                        }
+
+                                                                _ ->
+                                                                    D.fail "Collar should have at least one bead"
diff --git a/src/Editor/Interacting.elm b/src/Editor/Interacting.elm
index fadbebd..bb20542 100644
--- a/src/Editor/Interacting.elm
+++ b/src/Editor/Interacting.elm
@@ -30,3 +30,4 @@ type Cursor
     = LoopStart
     | LoopEnd
     | StartOffset
+    | Divide Int
diff --git a/src/Editor/Mobile.elm b/src/Editor/Mobile.elm
index 02ebdf3..99ef2c0 100644
--- a/src/Editor/Mobile.elm
+++ b/src/Editor/Mobile.elm
@@ -1144,9 +1144,9 @@ viewExtraTools model =
 viewContent : ( Model, Mobeel ) -> Element Msg
 viewContent ( model, mobile ) =
     let
-        ( wavePoints, viewWave ) =
-            case model.edit of
-                [ id ] ->
+        mayWavePoints =
+            case ( model.tool, model.edit ) of
+                ( Edit _, [ id ] ) ->
                     let
                         g =
                             Coll.get id mobile.gears
@@ -1154,18 +1154,36 @@ viewContent ( model, mobile ) =
                         ( start, end ) =
                             Wheel.getLoopPercents g
                     in
-                    ( { offset = g.wheel.startPercent, start = start, end = end }
-                    , case ( model.tool, Wheel.getContent g ) of
-                        ( Edit _, Content.S s ) ->
-                            (model.wave.drawn == (Waveform.SoundDrawn <| Sound.toString s))
-                                && g.wheel.viewContent
+                    case ( g.wheel.viewContent, Wheel.getContent g ) of
+                        ( True, Content.S s ) ->
+                            if model.wave.drawn == (Waveform.SoundDrawn <| Sound.toString s) then
+                                Just <| Waveform.Sound { offset = g.wheel.startPercent, start = start, end = end }
+
+                            else
+                                Nothing
+
+                        ( True, Content.C c ) ->
+                            case c.oneSound of
+                                Just oneSound ->
+                                    if model.wave.drawn == Waveform.SoundDrawn oneSound.soundName then
+                                        Just <|
+                                            Waveform.CollarDiv
+                                                { start = oneSound.start
+                                                , end = oneSound.end
+                                                , divs = oneSound.divs
+                                                }
+
+                                    else
+                                        Nothing
+
+                                _ ->
+                                    Nothing
 
                         _ ->
-                            False
-                    )
+                            Nothing
 
                 _ ->
-                    ( { offset = 0, start = 0, end = 0 }, False )
+                    Nothing
 
         getMod : Id Geer -> Wheel.Mod
         getMod id =
@@ -1234,9 +1252,8 @@ viewContent ( model, mobile ) =
                 InteractMsg
         , Element.inFront <|
             Waveform.view
-                viewWave
                 model.wave
-                wavePoints
+                mayWavePoints
                 model.interact
                 InteractMsg
         ]
@@ -2814,6 +2831,9 @@ interactWave g event model mobile =
                 StartOffset ->
                     Just <| Wheel.ChangeStart <| move absD <| g.wheel.startPercent
 
+                Divide i ->
+                    Nothing
+
         ( IWaveSel, Interact.Dragged { absD } _ _ ) ->
             let
                 mv =
diff --git a/src/Sound.elm b/src/Sound.elm
index 87261c3..1a64c36 100644
--- a/src/Sound.elm
+++ b/src/Sound.elm
@@ -77,22 +77,31 @@ setLoop mays (S s) =
             S s
 
 
-division : Int -> Sound -> List Sound
-division n (S s) =
+divide : Int -> Sound -> ( List Sound, List Float )
+divide n (S s) =
     let
         durPercent =
             s.endPercent - s.startPercent
 
-        loopPoints ( f1, f2 ) =
-            ( Just <| s.startPercent + f1 * durPercent, Just <| s.startPercent + f2 * durPercent )
+        mapPercent f =
+            s.startPercent + f * durPercent
 
         nn =
             toFloat n
+
+        fs =
+            List.range 1 n
+                |> List.map toFloat
+                |> List.map (\i -> ( (i - 1) / nn, i / nn ))
+                |> List.map (Tuple.mapBoth mapPercent mapPercent)
+
+        divs =
+            List.map Tuple.first <| List.drop 1 fs
+
+        sounds =
+            List.map (\tfs -> setLoop (Tuple.mapBoth Just Just tfs) <| S s) fs
     in
-    List.range 1 n
-        |> List.map toFloat
-        |> List.map (\i -> ( (i - 1) / nn, i / nn ))
-        |> List.map (\fs -> setLoop (loopPoints fs) <| S s)
+    ( sounds, divs )
 
 
 chgPath : Sound -> String -> Sound
diff --git a/src/Waveform.elm b/src/Waveform.elm
index 4e1cdfe..c639ab0 100644
--- a/src/Waveform.elm
+++ b/src/Waveform.elm
@@ -143,52 +143,68 @@ sub =
     soundDrawn (GotDrawn << D.decodeValue D.string)
 
 
+type Cursors
+    = Sound { offset : Float, start : Float, end : Float }
+    | CollarDiv { start : Float, end : Float, divs : List Float }
+
+
 view :
-    Bool
-    -> Waveform
-    -> { offset : Float, start : Float, end : Float }
+    Waveform
+    -> Maybe Cursors
     -> Interact.State Interactable Zone
     -> (Interact.Msg Interactable Zone -> msg)
     -> Element msg
-view visible wave cursors interState wrapInter =
+view wave mayCursors interState wrapInter =
     let
         toPx =
             round << ((*) <| toFloat wave.size)
     in
     el
-        (if visible then
-            (List.map (htmlAttribute << Attr.map wrapInter) <| Interact.dragSpaceEvents interState ZWave)
-                ++ [ Border.color <| rgb 0 0 0
-                   , Border.width border
-                   , Bg.color <| rgb 1 1 1
-                   , alignBottom
-                   ]
-                ++ List.map (mapAttribute wrapInter)
-                    ([ selection ( toPx 0, toPx cursors.start ) Nothing <| rgba 0.5 0.5 0.5 0.5
-                     , selection ( toPx cursors.end, toPx 1 ) Nothing <| rgba 0.5 0.5 0.5 0.5
-                     , selection ( toPx cursors.start, toPx cursors.end ) (Just IWaveSel) <| rgba 0 0 0 0
-                     , cursor (toPx cursors.start) LoopStart wave.height
-                     , cursor (toPx cursors.end) LoopEnd wave.height
-                     , cursor (toPx cursors.offset) StartOffset wave.height
-                     ]
-                        ++ (case wave.sel of
-                                Just points ->
-                                    [ selection points Nothing <| rgba 0.3 0.3 0.3 0.3 ]
-
-                                Nothing ->
-                                    []
-                           )
-                    )
-
-         else
-            []
+        (case mayCursors of
+            Just cursors ->
+                (List.map (htmlAttribute << Attr.map wrapInter) <| Interact.dragSpaceEvents interState ZWave)
+                    ++ [ Border.color <| rgb 0 0 0
+                       , Border.width border
+                       , Bg.color <| rgb 1 1 1
+                       , alignBottom
+                       ]
+                    ++ (List.map (mapAttribute wrapInter) <|
+                            case cursors of
+                                Sound c ->
+                                    [ selection ( toPx 0, toPx c.start ) Nothing <| rgba 0.5 0.5 0.5 0.5
+                                    , selection ( toPx c.end, toPx 1 ) Nothing <| rgba 0.5 0.5 0.5 0.5
+                                    , selection ( toPx c.start, toPx c.end ) (Just IWaveSel) <| rgba 0 0 0 0
+                                    , cursor (toPx c.start) LoopStart wave.height
+                                    , cursor (toPx c.end) LoopEnd wave.height
+                                    , cursor (toPx c.offset) StartOffset wave.height
+                                    ]
+                                        ++ (case wave.sel of
+                                                Just points ->
+                                                    [ selection points Nothing <| rgba 0.3 0.3 0.3 0.3 ]
+
+                                                Nothing ->
+                                                    []
+                                           )
+
+                                CollarDiv c ->
+                                    [ selection ( toPx 0, toPx c.start ) Nothing <| rgba 0.5 0.5 0.5 0.5
+                                    , selection ( toPx c.end, toPx 1 ) Nothing <| rgba 0.5 0.5 0.5 0.5
+                                    , cursor (toPx c.start) LoopStart wave.height
+                                    , cursor (toPx c.end) LoopEnd wave.height
+                                    ]
+                                        ++ List.indexedMap (\i div -> cursor (toPx div) (Divide i) wave.height) c.divs
+                       )
+
+            Nothing ->
+                []
         )
     <|
         html <|
             canvas
-                [ Attr.hidden <| not visible
+                [ Attr.hidden <| mayCursors == Nothing
                 , Attr.id canvasId
                 , Attr.width wave.size
+                , Attr.height wave.height
                 ]
                 []
 
@@ -228,6 +244,11 @@ cursor pos cur h =
                             [ handle [ centerY, moveDown <| toFloat h / 4 ]
                             , handle [ centerY, moveUp <| toFloat h / 4 ]
                             ]
+
+                        Divide int ->
+                            [ handle [ alignTop, moveUp <| toFloat border ]
+                            , handle [ alignBottom, moveDown <| toFloat border ]
+                            ]
                    )
                 ++ (List.map htmlAttribute <| Interact.draggableEvents <| IWaveCursor cur)
             )

From 7363fd7cc08bc5cea012248197331f7312d2b803 Mon Sep 17 00:00:00 2001
From: cbossut 
Date: Sat, 31 Oct 2020 19:04:34 +0100
Subject: [PATCH 85/85] Fix misuse and misunderstanding of startPercent

---
 scheduler.js       |  7 +++++++
 src/Data/Wheel.elm | 11 ++++++++---
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/scheduler.js b/scheduler.js
index 8e3fcaf..4779255 100644
--- a/scheduler.js
+++ b/scheduler.js
@@ -98,6 +98,9 @@ let scheduler = {
     model.updateVolume()
     
     if (model.soundName) {
+      // WARNING in model, startPercent is of whole sound, here it’s of content
+      model.startPercent = (model.startPercent - model.loopPercents[0]) / (model.loopPercents[1] - model.loopPercents[0])
+
       model.players = []
       model.freePlayer = function(startTime) {
         setTimeout(
@@ -119,6 +122,7 @@ let scheduler = {
     if (model.collar) {
       // WARNING collarOffset : ignore collar startPercent because it’s broken now (see todolist)
       model.startPercent = 0
+
       model.nextBead = 0
       model.duration = model.collar.duration
       model.beadsDurs = model.collar.beads.map(v => v.length)
@@ -132,6 +136,9 @@ let scheduler = {
     }
     
     if (model.mobile) {
+      // WARNING mobileOffset : ignore mobile startPercent because it’s broken now (see todolist)
+      model.startPercent = 0
+
       model.duration = model.mobile.duration
       model.rate = parentRate * model.duration / model.length
       model.subWheels = model.mobile.gears.map(v => this.prepare(t, v, model.gainNode, model.rate))
diff --git a/src/Data/Wheel.elm b/src/Data/Wheel.elm
index bda2486..1b7b907 100644
--- a/src/Data/Wheel.elm
+++ b/src/Data/Wheel.elm
@@ -21,7 +21,7 @@ type alias Wheeled a =
 
 type alias Wheel =
     { name : String
-    , startPercent : Float -- Percent of whole sound, not just looped part
+    , startPercent : Float --TODO Makes no sense, if specific to sound, should be in sound -- Percent of whole sound, not just looped part
     , volume : Float
     , content : WheelContent
     , viewContent : Bool
@@ -85,7 +85,7 @@ default =
 
 fromContent : Conteet -> Wheel
 fromContent c =
-    { default | content = C c }
+    (update (ChangeStart 0) { wheel = { default | content = C c } }).wheel
 
 
 type Mod
@@ -231,7 +231,12 @@ view w pos lengthTmp style mayWheelInter mayHandleInter uid =
             getLoopPercents { wheel = w }
 
         tickPercent =
-            (w.startPercent - loopStart) / (loopEnd - loopStart)
+            case w.content of
+                C (Content.S _) ->
+                    (w.startPercent - loopStart) / (loopEnd - loopStart)
+
+                _ ->
+                    0
 
         ( hoverAttrs, dragAttrs ) =
             Maybe.withDefault ( [], [] ) <|